Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to Reverse a String

C Code Example — String Programs

ADVERTISEMENT

C Program to Reverse a String

Objective

Write a C program to reverse a string manually.

Algorithm / Approach

  1. Read a string into orig and find its total length.
  2. Use a for loop with two variables: i starts at len-1 (the last valid character) and goes down, j starts at 0 and goes up.
  3. Copy the characters: rev[j] = orig[i].
  4. Append the null terminator: rev[j] = '\0'.
  5. 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)
ADVERTISEMENT