Reversing a String – Different Approaches


/* Reversing a String – Using Loop */

#include<stdio.h>

#include<conio.h>

void main()

{

int i=0, n=0;

char str[20];

clrscr();

printf(“Enter a String: “);

scanf(“%s”, str);

/*Counting no. of characters in the string*/

while(str[i] != ”)

{

n++;

i++;

}

printf(“\nThe Reversed String is “);

for(i=n-1; i>=0; i–)

printf(“%c”, str[i]);

getch();

}

/* Reversing String – Using Recursive Function */

#include<stdio.h>

#include<conio.h>

void main()

{

void reverse(void);

clrscr();

printf(“\nEnter the Text: “);

reverse();

getch();

}

void reverse (void)

{

char c;

if(( c = getchar( ) ) != ‘\n’)

reverse();          /* Recursive call */

purchar(c);

}

Advertisements