Program to Reverse a String
Following is the program to Reverse a String using
for loop.#include<stdio.h>
#include<conio.h>
void main()
{
int i, j, k;
char str[100];
char rev[100];
printf("Enter a string\t");
scanf("%s", str);
printf("The original string is %s", str);
for(i = 0; str[i] != '\0'; i++);
{
k = i-1;
}
for(j = 0; j <= i-1; j++)
{
rev[j] = str[k];
k--;
}
printf("The reverse string is %s", rev);
getch();
}
Output
Enter a string studytonight The original string is studytonight The reverse string is thginotyduts
Program to Reverse a String using Recursion
Now let's reverse a string using recursion.
#include<stdio.h>
#include<conio.h>
char* reverse(char* str);
void main()
{
int i, j, k;
char str[100];
char *rev;
printf("Enter a string\t");
scanf("%s", str);
printf("The original string is %s", str);
rev = reverse(str);
printf("The reverse string is %s", rev);
getch();
}
char* reverse(char *str)
{
static int i=0;
static char rev[100];
if(*str)
{
reverse(str+1);
rev[i++] = *str;
}
return rev;
}
Output
Enter a string studytonight The original string is studytonight The reverse string is thginotyduts
No comments:
Post a Comment