RUN


Program to count word in a sentence

Input : Takes a string and count the number of words in the input string.

Example:

Input: Welcome to C++

Output: Total number of words in a sentence is 3

Algorithm

  1. Create a string, find its length
  2. Start loop from i=0 to i< length
  3. Increment the count variable if empty space is encountered(‘ ‘)
  4. Print the number of words in the sentence as count+1 (number of words is 1 greater than number of spaces).

Code:

// C++ Program To Count Word in a Sentence
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;

int main()

{
	char str[100];

	int i, len, count = 0;

	cout << "Write a sentence : ";

	gets(str);

	len = strlen(str);

	for (i = 0; i < len; i++)

	{

		if (str[i] == ' ')

		{

			count++;
		}
	}

	cout << "Total number of words in a sentence is " << count + 1;

	return 0;

}

Report Error/ Suggestion

Related Posts:

[yuzo_views]



Interview Questions



CopyRight © 2020

CopyRight © 2020