Skip to content
Home ยป C Program To Reverse A Given String

C Program To Reverse A Given String

    The program to reverse a given string takes the input string and output reverse of the string. Each of the characters from the input string is extracted one at a time to achieve this task.

    The program is compiled using Dev-C++ compiler version 4.9.9.2 installed on a Windows 7 64-bit system. However, you can use any other standard C compiler to run this program. To get an error-free program change the source code according to your compiler specifications.

    You must be familiar with following C programming concepts to understand this program.

    Problem Definition

    The program takes an input string at run-time using the builtin function gets (str) where str is a character array. In this array of characters, the beginning characters are exchanged with the ending characters of the string with the help of a temp variable.

    For example

    If the string is “ELEPHANT”. The letter is ‘E’ and ‘T’ are exchanged until all characters are reversed. The final output is TNAHPELE.

    Program Code Reverse a String

    #include <string.h>
    #include <stdio.h>
    #include <conio.h>
    int main()
    {
        char str[100],temp;
        int i,j=0;
        printf("\n Enter the String: ");
        gets(str);
        i=0;
        j = strlen(str)-1;
        while(i<j)
              {
            temp = str[i];
            str[i] = str[j];
            str[j] = temp;
            i++;
            j--;
        }
        printf("\n Reverse String is %s",str);
        getch();
    }

    Output

    The output of the above program is given below. When the program ask for a string input, the user enters – MATHEMATICS. The program reverses the string and give following output.

    Enter the String: MATHEMATICS
    Reverse String is SCITAMEHTAM