Write a program that reads a string using gets and then counts and displays the number of words.
Difficulty level
This exercise is mostly suitable for students
#include <stdio.h>
#include <string.h>
#include <conio.h>
#define MAX_SIZE 100
main()
{
char sentence[MAX_SIZE];
int length, nb_words, i;
printf("Enter the sentence : ");
gets(sentence);
nb_words = 1;
length = strlen(sentence);
/* for each encountred space, increment the number of words */
for (i = 0; i < length; i++) {
if (sentence[i] == ' ') {
nb_words++;
}
}
printf("There's %d word%s in your sentence sentence\n", nb_words, (nb_words==1?"":"s"));
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Static Binary Search Trees