C Program to Reverse a String Using Pointers

1. Introduction

Reversing a string is a common operation in programming and serves as an excellent exercise to understand the workings of pointers. Pointers in C offer a direct way to access memory addresses, making them a powerful tool for string manipulation.

2. Program Overview

1. Declare a character array (string) and pointers to traverse and manipulate the string.

2. Set one pointer at the start and another at the end of the string.

3. Swap the characters at the pointers' positions and move the pointers towards each other.

4. Repeat until the pointers meet or cross each other.

3. Code Program

#include <stdio.h>

// Function to reverse the string using pointers
void reverseString(char *start) {
    char *end = start, temp;

    // Move the 'end' pointer to the last character of the string
    while (*end) {
        end++;
    }
    end--;  // Move back from null terminator to the last character

    // Swap characters from start and end, moving them towards each other
    while (start < end) {
        temp = *start;
        *start = *end;
        *end = temp;
        start++;
        end--;
    }
}

int main() {
    char input[100];

    // Ask the user for the string input
    printf("Enter a string: ");
    gets(input);  // Reads the string input

    reverseString(input);

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

    return 0;
}

Output:

Enter a string: programming
Reversed string: gnimmargorp

4. Step By Step Explanation

1. A reverseString function is defined to reverse the string using pointers.

2. Inside this function, two pointers, start and end, are initialized. start points to the beginning of the string, while end points to the last character.

3. A while loop continues until the start is less than end. Within the loop, the characters at the start and end pointers are swapped, and then the pointers are moved closer to each other.

4. The main function demonstrates this by taking a string input from the user, reversing it, and then printing the reversed string.

Comments