Menu
Coddy logo textTech

Counting Characters

Part of the Logic & Flow section of Coddy's C journey — lesson 21 of 63.

challenge icon

Challenge

Easy

Extend your text utility program from the previous lesson to add character counting functionality. Your program should:

  1. Prompt the user to enter a short sentence by printing: Enter a sentence: followed by a newline
  2. Declare a character array named sentence with 200 elements to store the input
  3. Use scanf with the %s format specifier to read a single word from the user
  4. Print the stored word in the format: You entered: [word]
  5. Use strlen() to calculate the number of characters and print it in the format: Character count: [count]
  6. Use strlen() again to print the length in the format: Length: [length]

Both Character count and Length use strlen() and will produce the same value. The goal of this exercise is to practice calling strlen() multiple times and using its result in different output contexts — reinforcing how the function works and how you can reuse it.

Remember to include the <string.h> header to use the strlen() function.

Your output should display the results in the following format:

Enter a sentence: 
You entered: [word]
Character count: [count]
Length: [length]

For example, if the input is:

Programming

Your output should be:

Enter a sentence: 
You entered: Programming
Character count: 11
Length: 11

Try it yourself

#include <stdio.h>
#include <string.h>

int main() {
    // TODO: Write your code here
    // 1. Print the prompt message
    printf("Enter a sentence:\n");
    // 2. Declare a character array named 'sentence' with 200 elements
    char sentence[200];
    // 3. Read input using scanf with %s format specifier
    scanf("%s", sentence);
    // 4. Print the entered word and its length
    printf("You entered: %s\n", sentence);
    printf("Length: %d\n", strlen(sentence));
    
    return 0;
}

All lessons in Logic & Flow