Reverse a String in C

Spread the love

Reverse a string in C:

Reverse a string in C
Reverse a String in C

Reverse a string in C using for loop:

Here you can learn how to write a program to reverse a string in C using for loop in 2 ways. Want to how For loop in C works?

Example:

#include<stdio.h>

void main()
{
    int a, b, c;
    char s[150];
    char t[150];
    printf("Do you want to reverse the string, then enter the string:\t");
    scanf("%s", s);

    for(a = 0; s[a] != '\0'; a++);
    {
        c = a-1;
    }
    for(b = 0; b <= a-1; b++)
    {
        t[b] = s[c];
        c--;
    }
    printf("After reversing the string the output is %s\n", t);
    
}

Output:

Do you want to reverse the string, then enter the string:	robert
After reversing the string the output is trebor

Example 2: C Program to reverse a string:

#include  <stdio.h>
#include <string.h>
void main()
{
 char *e="hi how are you";
 printf("After Reversing the String: \t ");
 for(int a=(strlen(e)-1);a>=0;a--)
 { 
   printf("%c",e[a]);
 } 
}

Output:

After Reversing the String: 	 uoy era woh ih

C Program to reverse a string:

Swapping the characters Using iteration method:

#include <stdio.h>
int main()
{
char string[1000], r[1000];
int i, j, c = 0;
scanf("%s", string);


while (string[c] != 0)
{
c++;
}
j = c - 1;

for (i = 0; i < c; i++) 
{
r[i] = string[j];
j--;
}

printf(r);
}

Output:

david
divad

Reverse a String in C Using Recursion Method:

Reverse a string in C
Reverse a String in C
#include <stdio.h>
#include <string.h>

void re(char *a, int start, int finish)
{
char c;
if (start >= finish)
return;
c = *(a + start);
*(a + start) = *(a + finish);
*(a + finish) = c;
re(a, ++start, --finish);
}

int main()
{
char b[100];
scanf("%s", b);
re(b, 0, strlen(b) - 1);
printf(b);
return 0;
}

Output:

ramesh
hsemar

C

1 thought on “Reverse a String in C”

  1. Pingback: C Program to calculate Simple Interest 2 ways - IT Examples

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top