Write a C program to reverse the string without using strrev() ?
This is simple logic which can reverse whole string without using library function strrev( ) or any other temporary string, we just use one temporary char variable.
#include <stdio.h>
#include <conio.h>
#include <string.h>
void main()
{
char str[10],temp;
int i,len;
printf("Enter String : ");
scanf("%s",str);
len=strlen(str)-1;
for(i=0;i<strlen(str)/2;i++)
{
temp=str[i];
str[i]=str[len];
str[len--]=temp;
}
printf("\nReverse string :%s",str);
getch();
}
Probable errors : Here strlen( ) gives you the length of string without null character and we minus 1 from complete length because our for loop will start with 0(zero). If you do not minus length of string by 1 then your printf function will not print anything because you shift last null character on first position and string will end before start.
Reverse string using recursion
#include<stdio.h>
#define MAX 10 // Maximum size of string
/* Reverse the String using Recursion */
char* ReverseString(char *str)
{
static int i=0;
static char rev[MAX];
if(*str)
{
ReverseString(str+1);
rev[i++] = *str;
}
return rev; // Return index of array every time
}
/* Main method */
int main()
{
char str[MAX];
gets(str);
printf (" %s \n", ReverseString(str));
return 0;
}
Output
Suggested Reading
- Write a C program to reverse the words in a sentence in place
- Write your own trim() or squeeze() function to remove the spaces from a string
- Write a C program which does wildcard pattern matching algorithm

