Write a C program to Reverse a string without using a library function

CServer Side ProgrammingProgramming

Using strrev() function

  • The function is used for reversing a string.
  • The reversed string will be stored in the same string.

Syntax

strrev (string)

Before working on reversing the string without using function, let’s have a look on how to reverse a string using string function strrev(), so that we can easily find the difference and gets clarity on the concept −

Example

#include<stdio.h>
main (){
   char a[50] ;
   clrscr();
   printf (“enter a string”);
   gets (a);
   strrev (a);
   printf(“reversed string = %s”,a)
   getch ();
}

Output

enter a string Hello
reversed string = olleH

Without using strrev() function

Now let’s see the program to reverse a string without using strrev() function −

Example

#include <stdio.h>
#include <conio.h>
#include <string.h>
void main(){
   char string[20],temp;
   int i,length;
   printf("Enter String : ");
   scanf("%s",string);
   length=strlen(string)-1;
   for(i=0;i<strlen(string)/2;i++){
      temp=string[i];
      string[i]=string[length];
      string[length--]=temp;
   }
   printf("\nReverse string :%s",string);
   getch();
}

Output

Enter String : Tutorialspoint
Reverse string :tniopslairotuT
raja
Published on 08-Mar-2021 14:27:12
Advertisements