Wednesday, 24 August 2016

C Program to reverse a string without using strrev()



This is a simple C program where a string is reversed by replacing its last character with first one until all the characters are replaced.

Look below for program and screenshot.




Download code

PROGRAM : 

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

void reverse_string(char *str)
{
    if (str == 0 || (*str == 0) )
    {
        return;
    }
    char *start = str;
    char *end = start + strlen(str) - 1;
    char temp;
    while (end > start)
    {
        temp = *start;
        *start = *end;
        *end = temp;
        ++start;
        --end;
    }
}

int main(void)
{
    char input[50];
    printf("\nEnter the string :");
    gets(input);
    reverse_string(input);
    printf("%s\n", input);
    return 0;
}

Download code

OUTPUT :  

C Program - Reverse a string