Write a C program to reverse a string

Description: Take a word as input and print it in reverse order.

Hint:

  • Use two variables for the first and last index. Swap the characters and move both towards the middle.

C program to reverse a string

#include <stdio.h>
#include <string.h>

int main(void) {
    char s[50];

    printf("Enter a word: ");
    scanf("%49s", s);

    int left = 0, right = strlen(s) - 1;
    while (left < right) {
        char temp = s[left];
        s[left] = s[right];
        s[right] = temp;
        left++;
        right--;
    }
    printf("Reversed: %s\n", s);
    return 0;
}

Output:

Output of the above program is

Enter a word: Hello
Reversed: olleH

How it works

  • “Hello” has 5 characters. First ‘H’ and ‘o’ are swapped, then ‘e’ and ‘l’. The middle ‘l’ stays.
  • The loop stops when left is not less than right.

Read Reverse a String in C.


Learn more about the similar topics:
Tutorials
C Arrays
C Two Dimensional Arrays
C Passing Arrays to Functions
C Strings
C String Input and Output
C String Functions
C strlen() Function
Exercises & Assignments
Write a C program to find the sum and average of array elements
Write a C program to find the largest element in an array
Write a C program to print the elements of an array in reverse order
Write a C program to sort an array using bubble sort
Write a C program to search an element in an array
Write a C program to add two matrices
Write a C program to find the length of a string without using strlen
Interview Questions & Answers
What is an array in C?
How is a string stored in C?
How to reverse a string in C?
What is the difference between memcpy() and strcpy() in C?