Program to Reverse the Given Sentence

Program to Reverse the Given Sentence

This program will Reverse the Given Sentence and Print the Sentence .


Input :

Welcome to Wisdom Overflow

Output :

Overflow Wisdom to Welcome


Logic To Reverse the Sentence :

  • Get the Sentence from the User and Store it in a String .
  • For reversing , We need to get the First Last word and Print it .Next is the Second last word , etc . . .
  • Traverse the String in reverse order and while Seeing a ” Space ” it indicates we have got a Word in the Sentence .
  • Now Print the Characters until a ” Space ” is seen again .
  • By repeating these steps we will get all word except the first word so, another Loop is used to print the first Word .

Program :

[code lang=”c”]
#include<iostream>
using namespace std;
int main()
{
string sentence;
cout<<"Enter the Sentence:";
getline(cin,sentence); //read string with spaces
int length=sentence.size(); //calculates string length
for(int i=length-1;i>=0;i–)
{
if(sentence[i]==’ ‘) //if condition to split words
{
int k=i+1;
while((sentence[k]!=’ ‘)&&(k!=length)) //while used to print the splitted word
{
cout<<sentence[k];
k++;
}
cout<<" ";
}
}
length=0; //n=0 for print the first word

//loop to print the first word

while((sentence[length]!=’ ‘)&&(sentence[length]!=’\0’)) //’/0′ is important if a single word is given as sentence
//remove ‘/0’ and enter single word to know its importance
{
cout<<sentence[length];
length++;
}
return 0;
}

[/code]

Suriya27

A Programmer who have his programming skills on C,C++, Java and also interested in Android Development. He follows the famous quotes by Linus Torvalds ” Talk is cheap, Show me the code “ .

Leave a Reply

Your email address will not be published. Required fields are marked *