Friday, 15 April 2016

C Program to reverse a string.

This program reverses a string using for loop and prints it on the compiler screen. The string is input by the user using gets(). Using gets() allows the compiler to input the spaces of string also. The length of string is calculated using for loop and the result is printed on compiler screen using printf.

Code:
#include<stdio.h>
#include<conio.h>
void main()
{
 int i,count=0;
 char ch[20];
 clrscr();
 printf("Enter the string\n");
 gets(ch);
 for(i=0;ch[i]!='\0';i++)
 {
  count++;
 } 
  printf("Reverse is:");
 for(i=count-1;i>=0;i--)
 {
   printf("%c",ch[i]);
 }
  getch();
}

Reverse a string using strrev. 

This program reverses a string using library function 'strrev' and prints it on the compiler screen. The string is input by the user using gets(). Using gets() allows the compiler to input the spaces of string also. The length of string is calculated using strrev and the result is printed on compiler screen using printf.
Code:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
 char ch[20];
 clrscr();
 printf("Enter the String\n");
 gets(ch);
 printf("Reverse is:");
 printf("%s",strrev(ch));
 getch();
}

Reverse a string using pointers. 

This program reverses a string using pointers and prints it on the compiler screen. The string is input by the user using gets(). Using gets() allows the compiler to input the spaces of string also. The length of string is calculated using pointers and the result is printed on compiler screen using printf.
Code:
#include<stdio.h>
#include<conio.h>
char rev(char s[50],int ,int );
void main()
{
 int i,l;
 char  a[50],b[50];
 clrscr();
 printf("Enter the string\n");
 gets(a);
 l=strlen(a);
 rev(a,0,l-1);
 printf("Reverse string is:");
 puts(a);
 getch();
}
char rev(char *s,int beg,int end)
{
 char p;
 if(beg>=end)
 {
   return 0;
 }
 else
 {
   p=*(s+beg);
   *(s+beg)=*(s+end);
   *(s+end)=p;
   return rev(s,++beg,--end);
 }
}

Output

No comments:

Post a Comment

My Articles