Sie sind auf Seite 1von 2

//4) using recursion reverse the order of words in a string

Algorithm:
1) Input the string
2) Calculate the string length and pass the string and string length into function.
3) Decrement the position of the character until null or space is encountered.
4) If space is encountered print the string from the space
5) Recursively call the function until position i==0 is reached.
Sourcecode:

#include<stdio.h>
#include<string.h>
void main()
{
//char str[100]="one two three";
char str[100]="first second third fourth";
int i,j,len;
void strreverse(char *, int);
clrscr();
len=strlen(str);
strreverse(str,len);
getch();
}
void strreverse(char * str, int i)
{
int j;
if(str[i-1] == ' ' || str[i-1] == NULL)
{
for(j=i;str[j]!= ' '&& str[j] != '\0';j++)
printf("%c",str[j]);
printf(" ");
if(i==0)
return;
else
strreverse(str,i-1);
}
else
{
i--;
strreverse(str,i);
}
}
Output

Das könnte Ihnen auch gefallen