C Program to Reverse a String

1. Introduction

Reversing a string is a classic coding challenge and is often asked in interviews. Even though C has ready-made functions for this, it's key to know how it works underneath. This guide explains a C program that reverses a string without library functions.

2. Program Overview

This program will:

1. Get the input string from the user.

2. Reverse the string.

3. Show the reversed string to the user.

3. Code Program

#include <stdio.h>  // For input and output

int main() {  // Start of the program

    char str[100], temp;  // Storage for the string and a helper variable
    int start = 0, end;   // Markers for the start and end of the string

    // Get the string from the user
    printf("Enter the string: ");
    scanf("%s", str);

    // Find out how long the string is
    for (end = 0; str[end] != '\0'; end++);

    // Make 'end' point to the last letter
    end--;

    // Flip the string
    while (start < end) {
        temp = str[start];
        str[start] = str[end];
        str[end] = temp;
        start++;
        end--;
    }

    printf("Reversed string is: %s\n", str);  // Show the flipped string

    return 0;  // End the program

}

Output:

Enter the string: javaguides
Reversed string is: sediugavaj

4. Step By Step Explanation

1. #include <stdio.h>: This gets us the functions for input and output.

2. int main(): Where our program starts running.

3. Variables:

- str holds the string.

- temp helps in switching letters around

.- start and end point to the beginning and end of the string.

4. Getting the String:

- printf asks the user for a string

- scanf saves that string in str.

5. Finding the Length:

- A loop counts the letters in the string. When it's done, the end tells us how many there are.

6. Fixing end:

- We subtract one from the end to make it point to the last letter.

7. Flipping the String:

- A loop switches the letters from start to end until the string is reversed.

8. Showing the Result:

- printf displays the reversed string. 

This example helps us see how flipping a string in C really works, especially the way we switch letters around.

Comments