Reverse a String Using Pointers in C

In C programming, you can reverse a string by manipulating its characters using pointers. This avoids using array indexing and demonstrates pointer arithmetic.

1. Problem Statement

Write a C program to reverse a string entered by the user using pointers.

2. Algorithm

Step 1: Start the program.

Step 2: Declare a character array and a pointer.

Step 3: Input the string from the user.

Step 4: Set one pointer to the beginning and another to the end of the string.

Step 5: Swap the characters at the two pointers and move them towards each other until they meet.

Step 6: Print the reversed string.

Step 7: End the program.

3. C Program

C
Program to reverse a string using pointers
#include <stdio.h>
#include <string.h>

int main() {
    char str[100], *start, *end, temp;

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

    start = str;
    end = str + strlen(str) - 1;

    while(start < end) {
        temp = *start;
        *start = *end;
        *end = temp;
        start++;
        end--;
    }

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

    return 0;
}

4. Example

Input:
Enter a string: HelloWorld
Output:
Reversed string: dlroWolleH

Notes

Pointers can be used to traverse and manipulate strings efficiently. Swapping characters using two pointers is a common technique for reversing a string in C.