C Program to Reverse a Sentence Using Recursion

cprogramming-Logo
C Programming Examples
C String Programs
C Loop Programs
C Function Programs
C Array Programs
C Integer Number Programs
C File I/O Programs

This C program takes a input from user and reverses that sentence using recursion.

Program:
#include <stdio.h>

void reverse();

void main()
{
    printf("Please enter a sentence: ");
    reverse();
}

void reverse()
{
    char c;
    scanf("%c", &c);
    if (c != '\n') {
        reverse();
        printf("%c", c);
    }
}
Program Output:

reverse-sentence-recursion

Explanation:

This program prints "Please enter a sentence: " in screen and then takes input from the user.
reverse() function called and function stores the first letter entered by user and stores in variable c. If that variable is other than '\n' [enter character] then, again reverse() function is called. Then, the second character is stored in variable c of second reverse function. This process goes on until the user enters '\n'.

When, user enters '\n', the last function reverse() function returns to second last reverse() function and prints the last character. Second last reverse() function returns to the third last reverse() function and prints second last character. This process goes on and the final output will be the reversed sentence.


Scroll Back to Top