0% found this document useful (0 votes)
157 views2 pages

4) Using Recursion Reverse The Order of Words in A String Algorithm

This algorithm recursively reverses the order of words in a string by: 1) Passing the string and its length to a recursive function. 2) The function decrements the position until a space or null is encountered. 3) When a space is found, it prints the substring and recursively calls itself, decrementing the position until all words are reversed.

Uploaded by

jetlin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
157 views2 pages

4) Using Recursion Reverse The Order of Words in A String Algorithm

This algorithm recursively reverses the order of words in a string by: 1) Passing the string and its length to a recursive function. 2) The function decrements the position until a space or null is encountered. 3) When a space is found, it prints the substring and recursively calls itself, decrementing the position until all words are reversed.

Uploaded by

jetlin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 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

You might also like