C Program to Reverse Order of Words in a String

In this tutorial, i am going to show you how to reverse order of words in a string with the help of for loop with if else, for loop with if in c programs.

All C Programs to Reverse Order of Words in a String

  • 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 result 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] = '\0';
			printf("%s ", &(str[i]) + 1);	
		} 
	}
	printf("%s", str);
	
  	return 0;
}

The result of the above c program; as follows:

Please Enter any String :  c programming
*****  Given String in Reverse Order  ***** 
programming c

More C Programming Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *