In: Computer Science
MUST BE DONE IN C (NOT C++)
This program should utilize the basics of strings. First, declare and initialize a string. You can name the variable whichever way you want and you can initialize it to whichever value you want. Then, use a for loop to print its characters; one at a time, until you reach the null character. After this, go ahead and declare a second string (since you are not initializing it right away, you will have to specify its length). This string should be long enough to hold all the characters of your first string (plus the null character).
The part 2 of this problem, is to copy the first string into the second one in reverse order. For example, if one string was “Hello World”, then the second string will be “dlroW olleH”. Don’t forget to assign the null character at the end of your second string.
When done, go ahead and use the %s printing method to print the second string.
For detailed description , read the comments in code:-
#include <stdio.h>
int main()
{
char string1[1000];
char string2[1000];
char string3[1000];
int begin, end, count = 0;
//get string1 input from users
printf("Input a string to reverse it \n");
gets(string1);
// Calculate the length of string1 here
while (string1[count] != '\0') //check for the null value in string which is present at last position to get the length of string1
count++;
end = count - 1;
//////this for loop will reverse the content of string1
for (begin = 0; begin < count; begin++) {
string2[begin] = string1[end]; //index 0 of string2 will store the last value of string1
end--; //here decrease the length of string1 by 1 and for loop will start again
}
string2[begin] = '\0';
printf("The reverse string is:- \n");
printf("%s\n", string2);
return 0;
}