C Program to Print Reverse of String

In this program, the user is ask to enter the string, after that the reverse string is displayed on the console. The logic behind this is that we have to take to variable i and j which will point to first and last character in string respectively. Then we will swap these two characters and repeat the procedure until both values i and j are equal. Finally you will get reverse string.



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

int main()
{
    char str[20], temp;
    int i, j=0;
    printf("Enter a string: ");
    scanf("%s", str);
    printf("Entered string is\n %s", str);
    i = 0;
    j = strlen(str)-1;

    while(i < j)
    {
        temp = str[i];
        str[i] = str[j];
        str[j] = temp;
        i++;
        j--;
    }
    printf("\nReverse of string is\n %s", str);
    return 0;
}
Output
Enter a string: Congratulations!
Entered string is
 Congratulations!
Reverse of string is
 !snoitalutargnoC