Solutions to Part 1 only a. C++ program may contains two more main functions as
ID: 3571196 • Letter: S
Question
Solutions to Part 1 only
Explanation / Answer
Please follow the code and comments for description :
CODE :
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1,s2;
int i;
cout << "Enter any the string :";
cin >> s1;i=0;
i = s1.length() -1;
while(i >= 0)
{
s2 = s2 + s1.substr(i, i - 1);
}
cout<<"Reverse string is: "<< s2;
return 0;
}
In the above code the errors are in the lines 6,8,10.
Here the code reads a string and that return the reverse of the phrase but this could not be achieved as above as the code do not know the size of the string that it is to be read and that the console till waits for the user to enter the data which is a never ending process. So this needs to be replaced with the char array as shown below. This is a pre-defined size of the array that reads the respective data and that return the reverse phrase.
CODE :
#include <iostream>
#include <string>
using namespace std;
int main()
{
char str[5],temp;
int i,j=0;
cout << "Enter any the string :";
cin >> str; // input string
i=0;
j = sizeof(str) -1;
while(i<j) // iterate till the end
{
temp=str[i]; // swap the data
str[i]=str[j];
str[j]=temp;
i++;
j--;
}
cout<<"Reverse string is: "<< str << endl; // print to console
return 0;
}
OUTPUT :
Enter any the string :Michael
Reverse string is: leahciM
Hope this is helpful.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.