C program to reverse a string without using any library function(strrev)

C program to reverse a string without using any library function(strrev):

In this post, we will learn how to reverse a string in C programming without using any library function, i.e. strrev. A string is consists of characters. So, if we are reversing a string, we need to reverse all characters in that string.

For example, if the string is hello, once reversed, it will be olleh.

If you look closely, we have exchanged the first character with the last character, second character with the second last character etc.

So, the program will take one string as the input and print the reverse string as the output.

Algorithm to reverse a string:

The only way to reverse a string is by using a loop. Below are the steps that we will use:

  • We will use one array of characters to store the string.
  • Initialize two variables, one as the length - 1 of the string, i.e. it is the index of the last character of the string. And another as 0, i.e. the first character index of the string.
  • Swap the characters pointed by the start index and end index variables.
  • Increment the value of the start index variable by 1 and decrement the value of the end index variable by 1 at the end of the loop. This loop will again run and exchange the characters at second and last second characters.
  • Keep the loop running until the value of the start index is less than the end index.
  • Once the loop ends, the string characters will be reversed, i.e. the string will be reversed.

C program:

Below is the complete C program:

#include<stdio.h>
#include<string.h>
 
int main() {
   char givenString[100], tempChar;
   int i = 0, j;
 
   printf("Enter the string to reverse:\n");
   gets(givenString);
 
   j = strlen(givenString) - 1;
 
   while (i < j) {
      tempChar = givenString[i];
      givenString[i] = givenString[j];
      givenString[j] = tempChar;
      i++;
      j--;
   }
 
   printf("Reverse string is: %s\n", givenString);
   return (0);
}

Here,

  • givenString is a character array to hold the string.
  • tempChar is a character to hold a value temporarily while swapping two characters.
  • It is asking the user to enter the string to reverse. This string is read and stored in the variable givenString.
  • i is holding the start index and j is holding the last index of the character in the string.
  • The while loop runs till the value of i is less than j. Inside this loop, it is exchanging the characters at the position i and j. After that,it is incrementing the value of i and decrementing the value of j.
  • Once the while loop ends, givenString will hold the reverse string. It is printing that value.

Sample Output:

If you run this program, it will print output as like below:

Enter the string to reverse:
Hello World
Reverse string is: dlroW olleH

Enter the string to reverse:
Hello 34#$
Reverse string is: $#43 olleH

You might also like: