/* * To reverse a sentence without reversing the letters in its words using a recursive function * @author-Karan Narain(karan@iitk.ac.in) * */ #include #include /* * rev takes 2 parameters-A points to the next word in the sentence * B points to the destination for the reversed string */ void rev(char *A,char *B) { int first=0; //used to check if this is the first call char buffer[80],*x,*y,*z,*buf; x=A; y=B; if(*y==' ') //' ' is the chosen initial value stored in passed B,so this will be true only in first call { first=1; *y='\0'; //change the value in B to an empty string } buf=buffer; //loop to store a word in buffer while(*x!=' ' && *x!='\0') { *buf=*x; buf++; x++; } *buf='\0'; //Null-terminate the word stored in buf if(*x!='\0') /* * Make a recursive call passing the remaining sentence and the same destination pointer * The idea is to store one word in buf in every recursive call and when the last word has been stored,start putting them in the destination in reverse order */ rev(x+1,y); while(*y!='\0') //proceed to the end of the words stored in the destination till now y++; buf=buffer; //Make buf point to start of buffer again //put the word in buf into the destination while(*buf!='\0') { *y=*buf; y++; buf++; } *y='\0'; //If this was the first call made,it would be the last to end and so the reversed sentence should be displayed here if(first==1) { printf("\nThe reversed sentence is "); puts(B); } //If this was not the first call,then there are more words to follow and so a space is inserted into the destination and it is then Null-terminated else { *y=' '; y++; *y='\0'; } } int main() { char A[200],B[200]; printf("Enter the sentence\n"); gets(A); //Choose an initial value for the destination B[0]=' '; rev(A,B); return 0; }