SCHOOL OF CODE BUILDERS
Learn To CODE. Become A DEVELOPER.
Pages
HOME
DATA STRUCTURES
STRINGS
ARRAYS
MATRIX
BINARY TREES
LINKED LIST
STACK
QUEUE
SORTING
SEARCHING
C
PYTHON
PSEUDOCODE
CONTEST PROBLEMS
ALGORITHMS
PATTERNS
PHP
C PUZZLES
C INTERVIEW QUESTIONS
JAVA
C++
HASHING
RECURSION
BASIC C PROGRAMS
TCS-CODEVITA
FACEBOOK
CONTACT US
C program to print words in reverse order
C program to print words in reverse order
Input:
CodeRegister loves Coding
Output:
Coding loves CodeRegister
Implementation:
/* Source: http://www.coderegister.co.in/2015/07/given-sentence-reverse-words-of.html */ #include
#include
#include
/* Function reverse to print the word from next character of a ' ' character till ' ' character or '\0' character */ void reverse(char *s,int n) { /* If we come across a space character or a null character, stop the recursive call */ if(*(s+n)=='\0' || *(s+n)==' ') return; /* Until that print every character */ printf("%c",*(s+n)); /* And call the recursive function */ reverse(s,n+1); } int main() { char *s; int i; /* allocate memory block of 256 characters & assign starting address to character pointer 's' */ s=(char*)malloc(sizeof(char)*256); /* Get the sentence from the user */ gets(s); /* calculate the size of the sentence using strlen() library function */ i=strlen(s)-1; /* until the index 0 */ while(i>=-1) { /* traverse from last character of the sentence until we encounter a space */ if(*(s+i)==' ' || i==-1) { /* Reverse the string from index next to space until another space or null character */ reverse(s,i+1); /* Print a space for every word */ printf(" "); } /* Decrease the index pointer of the string */ i--; } return 0; }
PREVIOUS
NEXT
HOME