Join Regular Classroom : Visit ClassroomTech

Reverse a String in C

What is String?
The string is a character array that ends with a null character denoted by ‘\0’.

Now, in this program, we have to reverse a string in c programming.
Suppose the Input is: codewindow
Then the Output will be: wodniwedoc

We have definitely different approaches to code this program.

  1. Using in-built function strrev()
  2. Without using in-built function strrev()

Using in-built function strrev()

#include <stdio.h>
#include<string.h>
int main(void) {
    char s[100];
    scanf("%[^\n]",s);
    printf("%s\n",s);
    
    strrev(s);
    
    printf("%s\n",s);
	return 0;
}

Input: codewindow
Output: wodniwedoc

Without Using in-built function strrev()

#include <stdio.h>
#include<string.h>
int main(void) {
    char s[100];
    scanf("%[^\n]",s);
    printf("%s\n",s);
    
    for(int start=0,end=strlen(s)-1;    
        start< strlen(s)/2; start++, end--)
    {
        int temp=s[start];
        s[start]= s[end];
        s[end]=temp;
    }
    
    printf("%s\n",s);
	return 0;
}

Input: codewindow
Output: wodniwedoc

Latest Post

Archive