C Program to Reverse a given String

The program to reverse a given string takes input string and output reverse of the string. This is a simple C program intended for beginners of C language. The program is written and 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 help you learn this program, we have following sections: problem definition, program source code and output of the 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.

Output - C Program to Reverse a Given String
Output – C Program to Reverse a Given String
Advertisements