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.h
for input/output operations andstring.h
for string manipulation functions. - We declare three variables:
str
of typechar
to store the input string,i
andj
of typeint
to be used in the loop, andtemp
of typechar
to 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
scanf
function. Note that%s
is used as the format specifier to read a string input. - We use the
strlen
function to find the length of the input string, and store it in variablej
. Note that we subtract1
from the length since we’ll be swapping characters using zero-based indices. - We use a
for
loop 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 indexi
with the character at indexj
. We also incrementi
and decrementj
to move towards the center of the string. - We print the reversed string using
printf
function, and then we return0
to 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.