Site icon Study Algorithms

Reverse a string without using Recursion

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;
}
Exit mobile version