C Program to Reverse a String

In this tutorial, i am going to show you how to reverse a string in a c program with the help of for loop, function, and pointer.

All C Programs and Algorithm to Reverse a String in C

  • Algorithm to Reverse a String
  • C program to Reverse a String using For Loop
  • C program to Reverse a String using Function
  • C program to Reverse a String using Pointer

Algorithm to Reverse a String

Follow below given algorithm to write a program to reverse a string; as follows:

  • Start
  • Declare all the variables ( integer and character type )
  • Enter the string to be reversed
  • Find out the length of string
  • Swap the position of array element using loop
  • Store the swapped position
  • Print the reversed string as console output
  • Stop

C program to Reverse a String using For Loop

#include <stdio.h>
#include <string.h>
 
int main()
{
  	char Str[100], RevStr[100];
  	int i, j, len;
 
  	printf("\n Please Enter any String :  ");
  	gets(Str);
  	
  	j = 0;
  	len = strlen(Str);
 
  	for (i = len - 1; i >= 0; i--)
  	{
  		RevStr[j++] = Str[i];
  	}
  	RevStr[i] = '\0';
 
  	printf("\n String after Reversing = %s", RevStr);
  	
  	return 0;
}

The result of the above c program; as follows:

Please Enter any String :  hello
String after Reversing = olleh

C program to Reverse a String using Function

#include <stdio.h>
#include <string.h>
void reverse_String(char [], int, int);
 
int main()
{
  	char Str[100], temp;
  	int i, j, len;
 
  	printf("\n Please Enter string :  ");
  	gets(Str);
  	
  	len = strlen(Str);
  	reverse_String(Str, 0, len -1);
 
  	printf("\n After Reversing = %s", Str);
  	
  	return 0;
}
void reverse_String(char Str[], int i, int len)
{
	char temp;
	temp = Str[i];
	Str[i] = Str[len - i];
	Str[len - i] = temp;
	
  	if (i == len/2)
  	{
		return;
  	}
  	reverse_String(Str, i + 1, len);
}

The result of the above c program; as follows:

Please Enter string :  function
After Reversing = noitcnuf

C program to Reverse a String using Pointer

#include <stdio.h>
#include <string.h>
char* reverse_String(char *Str)
{
	static int i = 0;
	static char RevStr[10];
	
	if(*Str)
	{
		reverse_String(Str + 1);
		RevStr[i++] = *Str;
	}
	return RevStr;
}
 
int main()
{
  	char Str[100], temp;
  	int i, j, len;
 
  	printf("\n Please Enter String :  ");
  	gets(Str);
 
  	printf("\n Result = %s", reverse_String(Str));
  	
  	return 0;
}

The result of the above c program; as follows:

Please Enter String :  wow
Result = wow

Be First to Comment

Leave a Reply

Your email address will not be published.