Basic

Switch Case

Goto

Operators

if Statement

Nested if

While Loop

For Loop

Patterns

Array

2D Array

String Function Example

Pointers

Recursion Function

Structure

Excersises

Others


C Program to Reverse a String Using Recursion Function


Write a C program to reverse a string using recursion function.

  • Take user input using fgets() and remove the trailing newline character if present.
  • Call the recursion function reverseString() with starting and ending indices.
  • Inside the recursion function, swap characters at start and end indices.
  • Recursionly reverse the substring by moving inward until the base case is met.
Example : pgm.c
#include <stdio.h>
#include <string.h>

// Recursion function to reverse a string
void reverseString(char *str, int start, int end) {
    if (start >= end)
        return;

    // Swap characters at start and end
    char temp = str[start];
    str[start] = str[end];
    str[end] = temp;

    // Recursion call for the remaining substring
    reverseString(str, start + 1, end - 1);
}

int main() {
    char str[100];

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    // Remove newline character if exists
    size_t len = strlen(str);
    if (len > 0 && str[len - 1] == '\n')
        str[len - 1] = '\0';

    reverseString(str, 0, strlen(str) - 1);

    printf("Reversed string: %s\n", str);

    return 0;
}

Output :

Enter a string: hello
Reversed string: olleh