C Program to Reverse a String

In this tutorial, you will learn and get code for reversing a string in C. Reversing a string means

For example, if the given string is "codescracker," then its reverse will be "rekcarcsedoc."

C Print the Reverse of a String

This program just prints the given string in reverse order without actually reversing it.

#include<stdio.h>
#include<conio.h>
int main()
{
    char str[50], i, j, count=0;
    printf("Enter any string: ");
    gets(str);
    for(i=0; str[i]!='\0'; i++)
        count++;
    for(j=(count-1); j>=0; j--)
        printf("%c", str[j]);
    getch();
    return 0;
}

This program was built and run in the Code::Blocks IDE. The following snapshot shows the output:

print string in reverse order c

Provide any string, say "codescracker," and press the ENTER key to see the string in reverse order:

c print string in reverse order

Consider another scenario in which the user enters any string containing spaces, such as "codes cracker dot com."

print string in reverse order c program

Program Explained

Here is a list of some of the main steps used in the above program:

C Reverse a String

Now this program actually reverses the given string first and then prints it as output:

#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
    char str[100], temp;
    int i=0, j;
    printf("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("\nReverse of the String is:\n%s", str);
    getch();
    return 0;
}

Here is the first sample run:

c program to reverse string

Here is another sample run:

c reverse any string

Program Explained

Here are some of the main steps used in the above program:

The same program in different languages

C Quiz


« Previous Program Next Program »


Liked this post? Share it!