C Program to Reverse a String
Objective
Write a C program to reverse a string manually.
Algorithm / Approach
- Read a string into
origand find its total length. - Use a
forloop with two variables:istarts atlen-1(the last valid character) and goes down,jstarts at 0 and goes up. - Copy the characters:
rev[j] = orig[i]. - Append the null terminator:
rev[j] = '\0'. - Print the reversed string.
main.c
#include<stdio.h>
int main( ) {
char orig[100], rev[100];
int len=0, i=0, j;
printf("Enter a String : ");
gets(orig);
while(orig[i] != '\0') {
len ++;
i++;
}
for (i=len-1, j=0; i>=0; i--, j++){
rev[j] = orig[i];
}
rev[j] = '\0';
printf("After Reverse : %s\n", rev);
return 0;
}
Expected Output
Enter a String : prowess After Reverse : sseworp
Explanation of the Program
- This is identical to reversing an integer array, but with the crucial added step of manually terminating the destination string with a null character (
'\0'). - Without the null terminator, C won't know where the reversed string ends when you try to print it.
Complexity
Time Complexity
O(n)
Space Complexity
O(n)