C Program to Reverse a String Without strrev()

C Program to Reverse a String Without strrev()

Reversing a string is a common exercise in C programming that helps beginners understand string manipulation, arrays, and memory access. While the C standard library provides the strrev() function on some platforms, it’s not universally available. Writing your own reverse function strengthens your understanding of how strings are stored and manipulated in memory.

In this tutorial, we will write a complete C program to reverse a string without using strrev(), explore multiple approaches including loops and recursion. By the end, you will understand both the logic and the implementation of string reversal in C.

What Is A String?

A string in C is an array of characters that ends with a null terminator (\0). Reversing a string involves swapping characters from the start and end, moving toward the center, until all characters are reversed.

This task teaches several important concepts: indexing arrays, using pointers, and writing functions. By mastering string reversal, you also build the foundation for more advanced string processing tasks such as palindrome checks and text manipulation.

Understanding the Problem

The problem is simple: given a string, create another string (or reverse in-place) so that the characters appear in reverse order.

Key points to consider:

  • The string ends with \0.
  • Reversing can be done in-place or by creating a temporary array.
  • Care must be taken not to overwrite characters when reversing in-place.

Program 1: Using a Temporary Array

A simple approach is to copy the string into a temporary array in reverse order, then copy it back to the original array. This method is easy to understand and safe for beginners.

#include <stdio.h>

int main() {

    char str[100], temp[100];
    int length = 0;

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

    // Calculate length
    while(str[length] != '\0' && str[length] != '\n') {
        length++;
    }

    // Reverse into temp array
    for(int i = 0; i < length; i++) {
        temp[i] = str[length - i - 1];
    }

    temp[length] = '\0';

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

    return 0;

}

This program first calculates the string length, then uses a loop to copy characters in reverse order into a temporary array. Finally, it prints the reversed string. Using a temporary array avoids overwriting characters during reversal.

Program 2: In-Place Reversal Using a for Loop

For efficiency, we can reverse the string in-place, swapping characters from the start and end until we reach the middle. This method does not require extra memory.

#include <stdio.h>

int main() {

    char str[100];
    int length = 0;

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

    while(str[length] != '\0' && str[length] != '\n') {
        length++;
    }

    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;

}

This method swaps the first and last characters, moving inward. It is memory-efficient and widely used in real-world applications. The for loop iterates only until half the length since each swap handles two characters.

Program 3: Using Pointers

Pointer arithmetic can be used to traverse the string and reverse it in-place, demonstrating another fundamental C concept.

#include <stdio.h>

int main() {

    char str[100];
    char *start, *end;
    int length = 0;

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

    while(str[length] != '\0' && str[length] != '\n') {
        length++;
    }

    start = str;
    end = str + length - 1;

    while(start < end) {

        char temp = *start;
        *start = *end;
        *end = temp;
        start++;
        end--;

    }

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

    return 0;

}

Here, two pointers, start and end, are used to swap characters directly in memory. This method avoids using indices, which is efficient and elegant, especially for large strings.

Program 4: Using Recursion

Recursion can reverse a string by swapping the first and last characters and calling the function on the substring between them.

#include <stdio.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];
    int length = 0;

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

    while(str[length] != '\0' && str[length] != '\n') {
        length++;
    }

    reverse(str, 0, length - 1);

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

    return 0;

}

The recursive function swaps the first and last characters, then recursively reverses the remaining substring. It continues until the base case start >= end is reached. This method demonstrates the elegance of recursion but uses extra call stack memory.

Performance Comparison

MethodTime ComplexitySpace ComplexityNotes
Temporary ArrayO(n)O(n)Easy to understand, uses extra memory
In-Place for LoopO(n)O(1)Efficient, swaps characters in place
Pointer ArithmeticO(n)O(1)Elegant and efficient for memory handling
RecursionO(n)O(n)Elegant, demonstrates recursion, uses call stack

Which Method Should You Use?

For beginners, the temporary array method is easiest to understand, showing how characters are copied in reverse order.

The in-place loop method is efficient and practical for most real-world applications. It uses no extra memory and executes quickly.

The pointer method is ideal for students who want to learn memory addressing and pointer manipulation.

The recursive method is elegant and demonstrates recursion but consumes extra memory due to call stack usage. It is mainly used for learning purposes rather than large-scale programs.

FAQs

1. Can these programs reverse sentences with spaces?
Yes. Using fgets() ensures the whole line, including spaces, is read and reversed correctly.

2. Is the temporary array method inefficient?
It uses extra memory proportional to the string length, but is simple and suitable for small strings.

3. Which method is best for very large strings?
The in-place loop or pointer method is best, as they do not require additional memory.

Conclusion

Reversing a string without strrev() teaches how to manipulate character arrays and use loops, pointers, or recursion effectively.

We explored four approaches: temporary array, in-place loop, pointers, and recursion. Each has its merits, and by practicing them, you build a strong foundation in string handling and memory management in C.

References & Additional Resources

A curated collection of textbooks, tutorials, and documentation for learning string reversal, pointers, and input handling in C.

  1. Kernighan, Brian W., and Dennis M. Ritchie. The C Programming Language, 2nd Edition, Prentice Hall, 1988 – The foundational text covering strings, pointers, arrays, and core C programming concepts.
  2. GeeksforGeeks: Reverse a String in C – Explains iterative and recursive methods to reverse a string in C with examples.
  3. Tutorialspoint: C Strings – Overview of string declaration, initialization, and operations in C.
  4. cplusplus.com: fgets() Function – Documentation for fgets() used for reading strings from input safely.
  5. Cprogramming.com: Pointers in C – Beginner-friendly guide on using pointers for arrays and string manipulation.
Scroll to Top