0
0
CProgramBeginner · 2 min read

C Program to Reverse a String with Example and Explanation

To reverse a string in C, use a loop to swap characters from the start and end moving towards the center, like for (int i = 0; i < length / 2; i++) { char temp = str[i]; str[i] = str[length - i - 1]; str[length - i - 1] = temp; }.
📋

Examples

Inputhello
Outputolleh
Inputworld
Outputdlrow
Input
Output
🧠

How to Think About It

To reverse a string, think of it like flipping a row of books: swap the first with the last, the second with the second last, and so on until you reach the middle. This means you only need to loop halfway through the string and swap characters at matching positions from start and end.
📐

Algorithm

1
Get the input string.
2
Find the length of the string.
3
Loop from the start to the middle of the string.
4
In each loop, swap the character at the current position with the character at the corresponding position from the end.
5
After the loop ends, the string is reversed.
6
Print the reversed string.
💻

Code

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

int main() {
    char str[100];
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);
    str[strcspn(str, "\n")] = '\0'; // Remove newline

    int length = strlen(str);
    for (int i = 0; i < length / 2; i++) {
        char temp = str[i];
        str[i] = str[length - i - 1];
        str[length - i - 1] = temp;
    }

    printf("Reversed string: %s\n", str);
    return 0;
}
🔍

Dry Run

Let's trace reversing the string "hello" through the code.

1

Input string

str = "hello"

2

Calculate length

length = 5

3

First iteration (i=0)

Swap str[0] ('h') and str[4] ('o') -> str = "oellh"

4

Second iteration (i=1)

Swap str[1] ('e') and str[3] ('l') -> str = "olleh"

5

Loop ends

String reversed: "olleh"

Iterationistr[i]str[length - i - 1]String after swap
10hooellh
21elolleh
💡

Why This Works

Step 1: Find string length

We use strlen to know how many characters the string has so we know where to stop swapping.

Step 2: Swap characters

Swapping characters from start and end moves the last character to the front and vice versa, reversing the string gradually.

Step 3: Loop only half the string

We only loop to the middle because swapping beyond that would undo the reversal.

🔄

Alternative Approaches

Using a second string to store reversed characters
c
#include <stdio.h>
#include <string.h>

int main() {
    char str[100], rev[100];
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);
    str[strcspn(str, "\n")] = '\0';

    int length = strlen(str);
    for (int i = 0; i < length; i++) {
        rev[i] = str[length - i - 1];
    }
    rev[length] = '\0';

    printf("Reversed string: %s\n", rev);
    return 0;
}
This method uses extra memory for a new string but keeps the original string unchanged.
Using recursion to reverse the string
c
#include <stdio.h>
#include <string.h>

void reverse(char *str, int start, int end) {
    if (start >= end) return;
    char temp = str[start];
    str[start] = str[end];
    str[end] = temp;
    reverse(str, start + 1, end - 1);
}

int main() {
    char str[100];
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);
    str[strcspn(str, "\n")] = '\0';

    reverse(str, 0, strlen(str) - 1);
    printf("Reversed string: %s\n", str);
    return 0;
}
Recursion is elegant but uses more stack memory and can be harder to understand for beginners.

Complexity: O(n) time, O(1) space

Time Complexity

The program loops through half the string length, so the time grows linearly with the string size, making it O(n).

Space Complexity

Swapping characters in place uses no extra memory besides a temporary variable, so space complexity is O(1).

Which Approach is Fastest?

In-place swapping is fastest and most memory efficient compared to using extra strings or recursion.

ApproachTimeSpaceBest For
In-place swappingO(n)O(1)Memory efficient and fast
Using extra stringO(n)O(n)Keeping original string unchanged
RecursionO(n)O(n)Elegant code but uses stack memory
💡
Remember to remove the newline character from input when using fgets before reversing.
⚠️
Forgetting to swap characters only up to the middle causes the string to be reversed twice or corrupted.