C program to reverse a string without using string function

C program to reverse a string without using string function(strrev)

This C program is to reverse a string without using string function(strrev).For example, reverse of string ‘codedost’ would be ‘tsodedoc’.

Logic

We start our for loop from the end of the string and keep printing each character till we reach the first character.

Dry Run of the Program

Take input string ‘str’.Let us take str=”code”

1st iteration for(i=n-1;i>=0;i–)  i.e.  for(i=4-1;i>=0;i–) i.e. for(i=3;3>=0;i–)

print str[i] i.e. str[3]  hence print e

2nd iteration for(i=n-1;i>=0;i–)  i.e.  for(i=3-1;i>=0;i–) i.e. for(i=2;2>=0;i–)

print str[i] i.e. str[2]  hence print d

3rd iteration for(i=n-1;i>=0;i–)  i.e.  for(i=2-1;i>=0;i–) i.e. for(i=1;1>=0;i–)

print str[i] i.e. str[1]  hence print o

4tht iteration for(i=n-1;i>=0;i–)  i.e.  for(i=1-1;i>=0;i–) i.e. for(i=0;0>=0;i–)

print str[i] i.e. str[0]  hence print c

So final output will be edoc which is the reverse of string code.

Program

#include<stdio.h>
#include<string.h>
        
void main()
{
    int i,n;
    char str[20];
    printf("Enter the String to get reversed\n");
    gets(str);
    n=strlen(str);
    printf("\nReversed string is \n");
    for(i=n-1;i>=0;i--)
    {
       printf("%c",str[i]);
    }
    
}

Output

Share Me!