Basic

Switch Case

Goto

Operators

if Statement

Nested if

While Loop

For Loop

Patterns

Array

2D Array

String Function Example

Pointers

Recursion Function

Structure

Excersises

Others


C Program to Reverse a String


Write a C program that reverses a given string.

  • Reads a string character-by-character using getchar() until a newline is encountered.
  • Stores each character into the array str while tracking the index i.
  • Prints the string in reverse order using a loop from i - 1 to 0.
  • Displays the reversed string followed by a newline.
Example : pgm.c
#include <stdio.h>

int main() {
    char str[100];
    int i = 0, j;

    printf("Enter a string: ");

    // Read characters manually until newline
    while ((str[i] = getchar()) != '\n') {
        i++;
    }

    // Print in reverse
    printf("Reversed string: ");
    for (j = i - 1; j >= 0; j--) {
        printf("%c", str[j]);
    }

    printf("\n");
    return 0;
}

Output:

Enter a string: Welcome
Reversed string: emocleW