In this tutorial you will learn about the C Program to Reverse Order of Words in a String and its application with practical example.
C Program to Reverse Order of Words in a String
In this tutorial, we will learn to create a C program that will Reverse the Order of Words in a String in C programming.
Prerequisites
Before starting with this tutorial, we assume that you are the best aware of the following C programming topics:
- Operators in C Programming.
- Usage of Conditional statements in C Programming.
- Basic Input and Output function in C Programming.
- Basic C programming.
What is a string?
A string is a collection of words, numbers, and symbols. The String can be any sentence of English Language.
Algorithm:-
1 2 3 4 5 6 7 8 9 |
1. Declaring the variables for the program. 2. Taking the input statement from the user. 3. Sendind that statement to loop for reversal. 4. Passing that reversed string to the user. 5. Printing the result words. |
Program Description for Reversing the Order of Words in a String:-
In this program, We will first take the input sentence from the user in string format. Then we will reverse that sentence using a short amount of code using the for-loop. Storing the reversed sentence. Printing the reversed sentence from the loop.
With the help of the below, code we will Reverse the Order of Words in a String.
Program Code:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
/* C Program to Reverse Order of Words in a String */ #include <stdio.h> #include <string.h> int main() { //declaring the required variables for the program char str[100]; int i, j, len, firstpoint, lastpoint; //str = it will hold the input string. //i, j = it will hold the integer value for the loop. //firstpoint , lastpoint = it will hold the index values of string. //len = it will hold the integer value for the length of string //Taking the input string from the user printf("\n Please Enter any String : "); gets(str); len = strlen(str); lastpoint = len - 1; //Reversing the string from last to first. printf("\n ***** Given String in Reverse Order ***** \n"); for(i = len - 1; i >= 0; i--) { if(str[i] == ' ' || i == 0) { if(i == 0) { firstpoint = 0; } else { firstpoint = i + 1; } for(j = firstpoint; j <= lastpoint; j++) { //Printing the string in the reverse order printf("%c", str[j]); } lastpoint = i - 1; printf(" "); } } return 0; } |
Output:-
In the above program, we have first initialized the required variable.
- str = string type variable that will hold the value of the input sentence.
- i,j = it will hold the integer value.
- firstpoint, lastpoint = it will hold the integer index value.
Input string from the user for the program.
Reverse The string sentence.
Printing the reversed string.