Introduction
Reversing a string is one of the fundamental problems in computer programming. It involves reversing the order of characters in a given string. In C programming, strings are handled as arrays of characters, and reversing them involves manipulating these characters. This problem is a great way to understand basic operations on arrays, loops, and string handling in C.
Objective
The objective of this program is to write a C program that accepts a string from the user and reverses it. The program will make use of basic loops, array manipulation, and string handling techniques to achieve this task.
Code
#include
#include
// Function to reverse a string
void reverseString(char str[]) {
int start = 0;
int end = strlen(str) - 1;
char temp;
// Loop to swap characters from the start and end
while (start < end) {
// Swap characters at start and end indices
temp = str[start];
str[start] = str[end];
str[end] = temp;
// Move towards the middle
start++;
end--;
}
}
int main() {
char str[100];
// Ask the user for a string input
printf("Enter a string: ");
fgets(str, sizeof(str), stdin); // Read the string with spaces
str[strcspn(str, "\n")] = 0; // Remove the newline character if present
// Call the function to reverse the string
reverseString(str);
// Display the reversed string
printf("Reversed string: %s\n", str);
return 0;
}
Explanation of the Program
Let’s break down the structure of the program:
- Header Files: The program includes two header files:
stdio.h: Contains functions for input and output, such asprintf()andfgets().string.h: Provides string manipulation functions, likestrlen()andstrcspn().
- reverseString Function: This function takes a string as an argument and reverses it in-place using a two-pointer technique.
startpoints to the beginning of the string, andendpoints to the last character.- It then enters a loop where the characters at
startandendare swapped. After each swap,startis incremented, andendis decremented until both pointers meet in the middle.
- Main Function:
- The
main()function first prompts the user to enter a string and reads it usingfgets()to handle spaces in the input. - The newline character, if present, is removed using
strcspn()to clean the input string. - Then, the
reverseString()function is called to reverse the string, and the reversed string is printed usingprintf().
- The
How to Run the Program
To run this C program, follow these steps:
- Save the Code: Save the C code in a file with a .c extension, such as
reverse_string.c. - Compile the Code: Open your terminal or command prompt and use the C compiler (like
gcc) to compile the code:gcc reverse_string.c -o reverse_string
- Run the Program: Once compiled, you can run the program by typing the following command:
./reverse_string
- Input and Output: The program will prompt you to enter a string. After entering the string, it will print the reversed version of the string.

