C Program to Reverse a String

C-String-Programs C-Programs

In this article, we are going to learn how to reverse a string in the C language. Here we are going to take two strings in which one will hold the string that we want to reverse and the second will hold the string which is reverse of the first string.

1. C Program to Reverse a String


#include <stdio.h>

int main() {
   char str1[] = "DevEnum Tutorial";    
   char str2[100];                

   int len = 0;
   
   while(str1[len] != '
#include <stdio.h>

int main() {
   char str1[] = "DevEnum Tutorial";    
   char str2[100];                

   int len = 0;
   
   while(str1[len] != '\0') 
   {
      len++;
   }

   for(int i = --len; i >= 0; i--);

   int k = 0;
   printf("\n The Reverse of '%s' is: - ",str1);

   while(len >= 0)
   {
      str2[len] = str1[k];
      len--;
      k++;
   }

   str2[k] = '\0';           

   printf("%s\n", str2);

   return 0;
}
') { len++; } for(int i = --len; i >= 0; i--); int k = 0; printf("\n The Reverse of '%s' is: - ",str1); while(len >= 0) { str2[len] = str1[k]; len--; k++; } str2[k] = '
#include <stdio.h>

int main() {
   char str1[] = "DevEnum Tutorial";    
   char str2[100];                

   int len = 0;
   
   while(str1[len] != '\0') 
   {
      len++;
   }

   for(int i = --len; i >= 0; i--);

   int k = 0;
   printf("\n The Reverse of '%s' is: - ",str1);

   while(len >= 0)
   {
      str2[len] = str1[k];
      len--;
      k++;
   }

   str2[k] = '\0';           

   printf("%s\n", str2);

   return 0;
}
'; printf("%s\n", str2); return 0; }

Output

The Reverse of 'DevEnum Tutorial' is: - lairotuT munEveD

C Program to Reverse a String


We can make this program compact by using strlen() function as:

#include <stdio.h>
#include <string.h>

int main() {
   char str1[] = "DevEnum Tutorial";    
   char str2[100];                

   int len = strlen(str1);  

   for(int i = --len; i >= 0; i--);

   int k = 0;
   printf("\n The Reverse of '%s' is: - ",str1);

   while(len >= 0)
   {
      str2[len] = str1[k];
      len--;
      k++;
   }

   str2[k] = '
#include <stdio.h>
#include <string.h>

int main() {
   char str1[] = "DevEnum Tutorial";    
   char str2[100];                

   int len = strlen(str1);  

   for(int i = --len; i >= 0; i--);

   int k = 0;
   printf("\n The Reverse of '%s' is: - ",str1);

   while(len >= 0)
   {
      str2[len] = str1[k];
      len--;
      k++;
   }

   str2[k] = '\0';           

   printf("%s\n", str2);

  
'; printf("%s\n", str2);

Output

The Reverse of 'DevEnum Tutorial' is: - lairotuT munEveD