English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C Language Basic Tutorial

C Language Flow Control

C Language Functions

C Language Arrays

C Language Pointers

C Language Strings

C Language Structure

C Language File

C Other

C Language Reference Manual

C program uses recursion to reverse a sentence

Comprehensive Collection of C Programming Examples

In this example, you will learn to get a sentence from the user and reverse it using recursion.

To understand this example, you should understand the followingC programming languageTopic:

Use recursion to reverse a sentence

#include <stdio.h>
void reverseSentence();
int main() {
    printf("Enter a sentence: ");
    reverseSentence();
    return 0;
}
void reverseSentence() {
    char c;
    scanf("%c", &c);
    if (c != '\n') {
        reverseSentence();
        printf("%c", c);
    }
}

Output result

Enter a sentence: margorp emosewa
awesome program

This program first prints 'Enter a sentence', and then the reverseSentence() function is called.

This function stores the first letter of the user's input in the variable c. If the variable is not \n (newline character), reverseSentence() is called again.

This process continues until the user clicks enter.

When the user presses the enter key, the reverseSentence() function starts printing the last character.

Comprehensive Collection of C Programming Examples