OneBite.Dev - Coding blog in a bite size

reverse a string in C

Code snippet on how to reverse a string in C

  #include <stdio.h> 
  #include <string.h> 
  
  int main() 
  { 
    char str[100], temp; 
    int i, j = 0; 
  
    printf("\nEnter the string :"); 
    scanf("%s", str); 
    i = 0; 
    j = strlen(str) - 1; 
  
    while (i < j) { 
        temp = str[i]; 
        str[i] = str[j]; 
        str[j] = temp; 
        i++; 
        j--; 
    } 
  
    printf("\nReverse string is :%s", str); 
    return (0); 
  }

This code takes in a string of characters from the user and reverses it. The inputs are stored in the ‘str’ variable, which is declared as a character array. Variables ‘i’ and ‘j’ are created and assigned to 0 and the length of the string minus 1 respectively. This is used for processing the string, as ‘i’ is incremented and ‘j’ is decremented. Inside the while loop, a ‘temp’ variable is used to temporarily store the characters in the two positions being swapped. Then, the two characters are swapped and the while loop runs until ‘i’ is greater than ‘j’. After the loop is done, the reversed string is printed as the output.

c