C program to find reverse of a string

Write a C program to find reverse of a given string using loop. How to find reverse of any given string using loop in C programming. Program to reverse a string without using inbuilt string library strrev() function in C.

Write a C program to find reverse of a string using strrev() library function. How to find reverse of any string using strrev() string function. How to use strrev() string library function in C programming.

Example:
Input string: Hello
Output reverse string: olleH

Required knowledge

Basic C programming, For loop, String



Program to find reverse of a string

/**
 * C program to find reverse of a string without using strrev() function
 */

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

#define MAX_SIZE 100 //Maximum size of the string

int main()
{
    char string[MAX_SIZE], reverse[MAX_SIZE];
    int i, j, len;

    /* Reads string from user */
    printf("Enter any string: ");
    gets(string);

    len = strlen(string);
    j = 0;

    for(i=len-1; i>=0; i--)
    {
        reverse[j] = string[i];
        j++;
    }
    reverse[j] = '\0';

    printf("\nOriginal string = %s\n", string);
    printf("Reverse string = %s", reverse);

    return 0;
}


Note: You can also use in-built library function strrev() to find reverse of any string. strrev() is a string library function defined under string.h header file. It is used to find reverse of any string.


Program to find reverse of a string using strrev()

/**
 * C program to find reverse of a string using strrev() function
 */

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

#define MAX_SIZE 100 //Maximum size of the string

int main()
{
    char string[MAX_SIZE];

    /* Reads a string from user */
    printf("Enter any string: ");
    gets(string);

    printf("\nOriginal string = %s\n", string);

    /* Finds the reverse of text */
    strrev(string);

    printf("Reverse string = %s", string);

    return 0;
}


Output
Enter any string: Hello

Original string = Hello
Reverse string = olleH

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment