Call us at 0700-922-6559 or Click here

Write a program to reverse a string.

Below is a program to reverse a string with step-by-step explanation.



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;



Enter a string to be reversed: Hello

 After the reverse of a string: olleH

Step-by-Step Explanation:

  1. We include two standard libraries – stdio.h for input/output operations and string.h for string manipulation functions.
  2. We declare three variables: str of type char to store the input string, i and j of type int to be used in the loop, and temp of type char to temporarily store a character during the swap.
  3. We prompt the user to enter a string using printf.
  4. 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.
  5. We use the strlen function to find the length of the input string, and store it in variable j. Note that we subtract 1 from the length since we’ll be swapping characters using zero-based indices.
  6. 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 index i with the character at index j. We also increment i and decrement j to move towards the center of the string.
  7. We print the reversed string using printf function, and then we return 0 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.

Leave a Reply

Your email address will not be published. Required fields are marked *