C program to reverse order of words in a string; Through this tutorial, we will learn how to reverse order of words in a string using for loop with if else, for loop with if in c programs.
Programs to Reverse Order of Words in a String in C
- C Program to Reverse Order of Words in a String using For Loop with If Else
- C Program to Reverse Order of Words in a String For Loop with If
C Program to Reverse Order of Words in a String using For Loop with If Else
/* C Program to Reverse Order of Words in a String */ #include <stdio.h> #include <string.h> int main() { char str[100]; int i, j, len, startIndex, endIndex; printf("\n Please Enter any String : "); gets(str); len = strlen(str); endIndex = len - 1; printf("\n ***** Given String in Reverse Order ***** \n"); for(i = len - 1; i >= 0; i--) { if(str[i] == ' ' || i == 0) { if(i == 0) { startIndex = 0; } else { startIndex = i + 1; } for(j = startIndex; j <= endIndex; j++) { printf("%c", str[j]); } endIndex = i - 1; printf(" "); } } return 0; }
The output of the above c program; as follows:
Please Enter any String : hello world ***** Given String in Reverse Order ***** world hello
C Program to Reverse Order of Words in a String For Loop with If
/* C Program to Reverse Order of Words in a String */ #include <stdio.h> #include <string.h> int main() { char str[100]; int i, len; printf("\n Please Enter any String : "); gets(str); len = strlen(str); printf("\n ***** Given String in Reverse Order ***** \n"); for(i = len - 1; i >= 0; i--) { if(str[i] == ' ') { str[i] = '/* C Program to Reverse Order of Words in a String */ #include <stdio.h> #include <string.h> int main() { char str[100]; int i, len; printf("\n Please Enter any String : "); gets(str); len = strlen(str); printf("\n ***** Given String in Reverse Order ***** \n"); for(i = len - 1; i >= 0; i--) { if(str[i] == ' ') { str[i] = '\0'; printf("%s ", &(str[i]) + 1); } } printf("%s", str); return 0; }'; printf("%s ", &(str[i]) + 1); } } printf("%s", str); return 0; }
The output of the above c program; as follows:
Please Enter any String : c programming ***** Given String in Reverse Order ***** programming c