codescracker
c

C Program to Reverse a String



« Previous Program Next Program »

In this tutorial, you will learn and get code about reversing a string in C. Reverse of a string means

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

C Print Reverse of a String

This program just print the given string in reverse order without actually reversing it:

// ----codescracker.com----

#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;
}

The program was written under Code::Blocks IDE, therefore after successful build and run. You will get the following output:

print string in reverse order c

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

c print string in reverse order

Let's take another sample run where user has provided any string that contains spaces say codes cracker dot com:

print string in reverse order c program

Program Explained

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

C Reverse a String

Now this program actually reverse the given string first, and then will print it as output:

// ----codescracker.com----

#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 above program:

Same Program in Other Languages


« Previous Program Next Program »