Reverse a String Using C Programming – Simple Code with Explanation

Introduction

Reversing a string is one of the most basic yet important operations in programming. In this tutorial, you’ll learn how to reverse a string using C programming. This exercise will help you understand how character arrays work and how to manipulate them in place.


C Program to Reverse a String

#include <stdio.h>
#include <string.h>

int main() {
char str[100], temp;
int i, len;

printf("Enter a string: ");
fgets(str, sizeof(str), stdin);

len = strlen(str) - 1; // remove newline character

for (i = 0; i < len / 2; i++) {
temp = str[i];
str[i] = str[len - 1 - i];
str[len - 1 - i] = temp;
}

printf("Reversed string: %s", str);

return 0;
}

Explanation

  • The input string is taken using fgets() to allow spaces.
  • strlen() calculates the string length (excluding \0).
  • A loop swaps characters from the start and end until the midpoint.
  • The result is the reversed version of the input string.

Sample Output

Enter a string: hello world
Reversed string: dlrow olleh

Use Cases

  • Useful in palindrome checking.
  • Foundational logic for string-based algorithms.
  • Helps improve understanding of array indexing and manipulation.
Previous Article

Delete a Character from a Given String in C Programming

Next Article

Convert String into Upper Case in C – Simple Program for Beginners

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨