Complementary task for topic: 5

M Nemeth · 2023-08-29 15:21:04.620218'

Simple strings: Reversal

Simple strings: Reversal

Write a C program that uses scanf() to read a string from the user and then reverses the string. Display the reversed string using printf().

Hint: Strings are closed with '\0' character (End-of-String) and it is a char array. The array contains valid characters, EoS character, and trash, respectively. To reverse it obviously you need the legth of the string (number of valid cahracters). From this point it is the same as reverse an array!

Solution
#include 

int main() {
    char str[100], reversed[100];
    int i, j;

    printf("Enter a string: ");
    scanf("%99[^\n]", str); // Read the string with spaces

    // Calculate the length of the string
    int length = 0;
    while (str[length] != '\0') {
        length++;
    }

    // Reverse the string
    for (i = length - 1, j = 0; i >= 0; i--, j++) {
        reversed[j] = str[i];
    }
    reversed[j] = '\0';

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

    return 0;
}



Explanation
The program uses two char arrays str and reversed to store the input string and the reversed string, respectively.

The user is prompted to enter a string using printf().

The string is read using scanf() with the %[^\n] format specifier, allowing the input to include spaces.

The length of the string is calculated by iterating through the characters in the str array until the null terminator (\0) is encountered.

The string is reversed using a for loop. The variable i starts at the last index of the original string, and j starts at 0. The loop iterates from the last character of the original string to the first character, copying each character to the reversed array.

A null terminator ('\0') is added at the end of the reversed array to terminate the string.
< < previous    next > >