Reversing each word in a sentence – Computer Sir Ki Class
  

Login
[lwa]



Solved Problem #CPP#3073 siteicon   siteicon   siteicon  

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

#include <iostream.h>
#include <conio.h>
int main()
{
clrscr();
char s[80];
cout<<"Input Any Sentence : " ;
cin.getline(s,50);
for(int i=0;s[i]!='';i++)
{
if(s[i+1]==' ' || s[i+1]=='')
{
for(int j=i; j>=0 && s[j]!=' '; j--)
cout<<s[j];
cout<<" ";
}
}
getch();
return 0;
}
#include <iostream>
using namespace std;
int main()
{
char s[80];
cout<<"Input Any Sentence : " ;
cin.getline(s,50);
for(int i=0;s[i]!='';i++)
{
if(s[i+1]==' ' || s[i+1]=='')
{
for(int j=i; j>=0 && s[j]!=' '; j--)
cout<<s[j];
cout<<" ";
}
}
return 0;
}

Test it !

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]!=’’;i++)
This is outer loop to traverse the whole string till null character is found.
{
if(s[i+1]==’ ‘ || s[i+1]==’’)
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.


Share

sunmitra| Created: 27-Jan-2018 | Updated: 3-Mar-2018|






Back