String

In C language string is an Array of the Char variable.

to write a program of the string reverse we have to break this program into steps as always.

  1. Take input from the user.
  2. Reverse the string using the for loop
  3. print the final answer to the user.

First of All, create a schema for the program.

#include <stdio.h>  
#include <string.h>  
int main(int argc, char const *argv[])  
{  
return 0;  
}

Now write some code for the Taking input from the user.
scanf is fine here but keep in mind it can take input up to first space.

 char name[150],rev[150] ;  
 int l=0;  
 printf("Enter a string to reverse\n");  
 // taking input from the user   
 // string should not have the space in between  
 scanf("%s",&name);

This code will take a string from the user, now implement the main logic.

what we are doing here is that
first, we are counting the length of the string and then storing the last variable into the first element of another variable.

l = strlen(name);  
  
 // main logic to reverse the string.  
 /*  
  to reverse the string just put the last element to the   
 first position of the second string.  
 */  
 // with the help of the same we can implement the program of the palindrome.  
 for (int i = 0; i < l; i++)  
  rev[l-i-1] = name[i];

Now we have reversed string in our rev Variable.

printf("Reversed string is %s\n",rev );

That’s it.

All done our program is completed.
PS: there is some other way to reverse the string in c, this way is one of them.

Full program code is.

#include <stdio.h>  
#include <string.h>  
int main(int argc, char const *argv[])  
{  
        char name[150],rev[150] ;  
 int l=0;  
 printf("Enter a string to reverse\n");  
 // taking input from the user   
 // string should not have the space in between  
 scanf("%s",&name);  
l = strlen(name);  
  
 // main logic to reverse the string.  
 /*  
  to reverse the string just put the last element to the   
 first position of the second string.  
 */  
 // with the help of the same we can implement the program of the palindrome.  
 for (int i = 0; i < l; i++)  
  rev[l-i-1] = name[i];  
        printf("Reversed string is %s\n",rev );  
  
return 0;  
}  

The output of this program is.

reverse output

If you like this post check out our other post related to C or CPP.
Please share and subscribe to this blog.