Home Strings Reverse a string without using Recursion

Reverse a string without using Recursion

by nikoo28
0 comment

Question: Write a program in C to reverse a string using recursion

Input: Hello Everyone
Output: enoyrevE olleH

We discussed the method to reverse the string using recursion in this post. But a recursive method is generally not preferred as it takes a longer execution time.
This is also a classic interview question and we need to do it in place. We also need to be careful for the null character.

#include<stdio.h>

void reverse(char *str)
{
	// Mark a pointer to the start of string
	char * end = str;
	
	char temp;
	
	if(str)
	{
		// Find the end of the string
		while(*end)
			++end;
	}
	
	// end now points at the last character of the string
	// but the last character is null, so we need to step back one character
	end--;
	
	// Swap characters from start of the string with the end of the string
	// until the pointers meet in the middle
	while(str < end)
	{
		temp = *str;
		*str++ = *end;
		*end-- = temp;
	}
}

//driver program
int main(void)
{
	char str[100] = "Hello Everyone";
	
	reverse(str);
	
	printf("%s",str);
	
	return 0;
}
0 comment

You may also like

Enclose codes in [code lang="JAVA"] [/code] tags

This site uses Akismet to reduce spam. Learn how your comment data is processed.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More