Problem Statement: Write a C program to reverse a given string.
Description:
This program demonstrates string manipulation in C. It uses strlen() to determine the length of a string and a for loop to reverse the string by swapping characters. The program also introduces arrays and string handling.
Usage:
The user inputs a string, and the program outputs the reversed string.
Code:
C
#include <stdio.h>
#include <string.h>
int main() {
char str[100], temp;
int i, len;
// Asking user to input a string
printf("Enter a string: ");
gets(str); // Getting the input string
len = strlen(str); // Calculating the length of the string
// Reversing the string
for (i = 0; i < len / 2; i++) {
temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}
// Displaying the reversed string
printf("Reversed string: %s\n", str);
return 0;
}
Explanation:
gets()
reads a string input.strlen()
finds the length of the string.- A
for
loop is used to swap characters from the beginning and end of the string to reverse it.
Test here: