Introduction

Reversing a string is a common task in programming that involves rearranging the characters of the string so that they appear in the opposite order. This operation can be useful in various applications, such as checking for palindromes, manipulating text, or simply for aesthetic purposes. In C, strings are typically represented as arrays of characters, which allows us to manipulate them using standard array operations.

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

#define MAX 100  // Maximum size of the string

void reverseString(char str[]) {
    int start = 0;
    int end = strlen(str) - 1;
    char temp;

    while (start < end) {
        // Swap characters
        temp = str[start];
        str[start] = str[end];
        str[end] = temp;
        
        start++;
        end--;
    }
}

int main() {
    char str[MAX];

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

    // Remove the newline character if present
    str[strcspn(str, "\n")] = '\0';

    printf("Original String: %s\n", str);
    
    reverseString(str);
    
    printf("Reversed String: %s\n", str);

    return 0;
}

Explanation

  1. Includes and Defines: The program includes the stdio.h and string.h headers for input/output and string manipulation functions, respectively. It defines a constant MAX for the maximum size of the string.
  2. Reverse Function: The reverseString function takes a string as input and reverses it in place:
    • It initializes two pointers, start and end, to the beginning and end of the string.
    • A while loop runs as long as start is less than end. Inside the loop, it swaps the characters at these positions and moves the pointers towards the center.
  3. Main Function: In main, the program:
    • Declares a string variable.
    • Prompts the user to enter a string using fgets, which safely reads a line of input.
    • Removes the newline character that fgets might add using strcspn.
    • Displays the original string.
    • Calls the reverseString function to reverse the string.
    • Finally, it prints the reversed string.

Input

The user is prompted to enter a string. Example input:

Enter a string: Hello, World!

Output

The program outputs both the original and reversed strings. For the example input, the output will be:

Original String: Hello, World!
Reversed String: !dlroW ,olleH

Conclusion

This C program effectively demonstrates how to reverse a string using basic string manipulation techniques. Understanding how to work with strings and arrays is crucial in C programming, as it forms the basis for many text processing tasks. The code can be easily adapted to handle different input sizes or to implement other string-related functionalities, making it a versatile example for learning about strings in C.

Leave a Reply

Your email address will not be published. Required fields are marked *

Verified by MonsterInsights