C Program to Reverse a Given String
This page contains a C program that reverses a given string. The program uses basic string manipulation techniques to achieve this task.
Program Explanation
The C program to reverse a string follows these steps:
- Include necessary headers: Include the
<stdio.h>
and<string.h>
headers for input/output functions and string manipulation functions. - Main Function: The
main
function is the entry point of the program. - Input String: Define a string that you want to reverse.
- Reverse the String: Use a loop to reverse the string by swapping characters from the start and end.
- Print the Result: Output the reversed string to the console.
C Program Code
/*
* C program to reverse a given string.
*/
#include <stdio.h>
#include <string.h>
/**
* Function to reverse a given string.
* @param str the string to be reversed
*/
void reverseString(char* str) {
int n = strlen(str); // Get the length of the string
for (int i = 0; i < n / 2; i++) {
// Swap characters from start and end
char temp = str[i];
str[i] = str[n - i - 1];
str[n - i - 1] = temp;
}
}
/**
* Main function which is the entry point of the program.
* @return 0 on successful execution
*/
int main() {
// Define the string to be reversed
char str[] = "Hello, World!";
// Print the original string
printf("Original String: %s\n", str);
// Call the reverse function
reverseString(str);
// Print the reversed string
printf("Reversed String: %s\n", str);
return 0;
}
Program Details
The program contains the following:
reverseString
Function: This function takes a string as input and reverses it in place by swapping characters from the start and end.main
Function: The entry point of the program where the string is defined, the reverse function is called, and the results are printed.
Running the Program
To run the program:
- Save the code in a file named
reverse_string.c
. - Compile the program using the command:
gcc reverse_string.c -o reverse_string
. - Run the compiled program using the command:
./reverse_string
.
Explanation of the C Program:
- Header Inclusions: The program includes
<stdio.h>
for input/output functions and<string.h>
for string manipulation functions. - reverseString Function:
- Takes a character array (
char* str
) as input. - Calculates the length of the string using
strlen()
. - Uses a loop to swap characters from the start and end of the string until the middle of the string is reached.
- Takes a character array (
- main Function:
- Defines a string
str
to be reversed. - Prints the original string.
- Calls the
reverseString
function to reverse the string. - Prints the reversed string.
- Defines a string