Example(s):Palindrome, prime, armstrong, "linear search", reverse etc.
Example(s):1575, 1632, 1539 (Only one at a time)
Login
[lwa]
Solved Problem
#CPP#3073
Problem Statement - Reversing each word in a sentence
Write a program to take a sentence input from the user and then print the sentence by reversing each word in the sentence.
Solution
TC++ #3073
Run Output
Input Any Sentence : Human knowledge is still just a drop in the ocean
namuH egdelwonk si llits tsuj a pord ni eht naeco
char s[80]; cout<<“Input Any Sentence : ” ; cin.getline(s,50);
Here we collect the sentence from the user.
for(int i=0;s[i]!=’\0′;i++)
This is outer loop to traverse the whole string till null character is found.
{ if(s[i+1]==’ ‘ || s[i+1]==’\0’)
This condition tests the word boundary if the next character is a space or the null character (for end of sentence)
{ for(int j=i; j>=0 && s[j]!=’ ‘; j–)
If the next character is after the word boundary then current index is definitely the last character of the word. In such a case we begin from the last character of the word to first character of the word by checking the backward word boundary, which can be space again or is up to the first character.
cout<<s[j];
We keep outputting till the word boundary is arrived in the reversed form.
cout<<” “;
This is to manually give a space if the reversed word is printed. This is done after the inner loop but within the outer loop. } }
Notes
In this method if any punctuation marks are there in the sentence, then they will also form the part of reversed word. User’s are encouraged to modify this program to check for any punctuation marks instead of checking just the space and last character for word boundaries.