In: Computer Science
String Input Console Application and Program Analysis
Demonstrate an understanding of basic C++ programming concepts by completing the following:
#include<iostream>
#include<string.h>
using namespace std;
int main(){
char str[100],temp;
cout<<"enter a string:";
gets(str);
int i=strlen(str)-1;
for(int j=0;j<i;j++,i--){
temp=str[j];
str[j]=str[i];
str[i]=temp;
}
cout<<"After reversing: "<<str;
return 0;
}
Program analysis:
This program takes an input of a string which can be of maximum
size of 100.
The string length is calculated and is used further to reverse it
The for loop is responsible for reversing the string
The temporary variable 'temp' is used for swapping of the ith and the jth character of the string
The for loop will terminate when i is less than j.
The final result of str is printed.
User Inputs and Outputs:
1.
enter a string: AMMA
After reversing: AMMA
2.
enter a string: calculate
After reversing: etaluclac
3
enter a string: Abacus
After reversing: sucabA
Now we can conclude that the program works fine with given three variable length inputs.
Thus, the only care that needs to be taken is giving the input which is not null. The program doesn't crash. But the output would be null.
The length of the string or the size should also be taken care of while writing the program ad giving the input. Make sure to take the string size which suites the input that is to be given.
Make sure to import the libraries that are required for the functionality of the program. string.h in this case.
Also try to give good naming conventions when you are writing programs for better understanding.