How to reverse a string in C

This is a C program to reverse a string without using the library function strrev().

The program finds the length of the string using a while loop. A string is terminated with a NULL character (\0). The program finds the length by looking for the NULL character and then prints the array elements starting from the second last character to the first.

If the user inputs "frog pond" the program prints "dnop gorf"


str_reverse.c

// This is a program to reverse a string 

#include <stdio.h>
#include <conio.h>

int main() 
{
 int i, len;
 char str[100];

 // Read string input
 printf("Enter a string \n");
 gets(str);

 // Find the length of the string
 len = 0;
 while (str[len] !='\0') {
	 len++;
 }

 // Print the string in reverse order
  for (i=len-1; i >= 0; i--) {
	printf("%c",str[i]); }

 // Wait for key press
 getch();

return 0;
}


Post a comment

Name

Your Comment

Email (We dont publish it)

Comments

Nothing yet..be the first to share wisdom.