C Program to Reverse Order of Words in a String

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] = '\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

Recommended C Programs

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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