Below is a program to reverse a string with step-by-step explanation.
#include<stdio.h>
#include<string.h>
int main() {
char str[100];
int i, j;
char temp;
printf("Enter a string: ");
scanf("%s", str);
j = strlen(str) - 1;
for (i = 0; i < j; i++, j--) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
printf("The reversed string is: %s\n", str);
return 0;
}
Output-
Enter a string to be reversed: Hello
 After the reverse of a string: olleH
Step-by-Step Explanation:
- We include two standard libraries –
stdio.hfor input/output operations andstring.hfor string manipulation functions. - We declare three variables:
strof typecharto store the input string,iandjof typeintto be used in the loop, andtempof typecharto temporarily store a character during the swap. - We prompt the user to enter a string using
printf. - We read the string entered by the user using
scanffunction. Note that%sis used as the format specifier to read a string input. - We use the
strlenfunction to find the length of the input string, and store it in variablej. Note that we subtract1from the length since we’ll be swapping characters using zero-based indices. - We use a
forloop to iterate over the string. The loop runs from the start of the string (i = 0) to the middle of the string (i < j). On each iteration, we swap the character at indexiwith the character at indexj. We also incrementiand decrementjto move towards the center of the string. - We print the reversed string using
printffunction, and then we return0to indicate that the program has completed successfully.
That’s it! The program reverses the input string and prints the reversed string to the console.
Once you have written the code, you can compile and run it using a C compiler, such as GCC, on your computer. The program will then display output on the screen when executed.
For more information about C programming join our course of C programming.