C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Strings in C

Reverse string

C Program: Reverse a String (Without strrev())

Method 1: Using gets() function

C

#include <stdio.h>

 

int main() {

    char str[100], rev[100];

    int i, j, length = 0;

 

    // Input string

    printf("Enter a string: ");

    gets(str); // unsafe, use fgets() in practice

 

    // Find string length

    for (i = 0; str[i] != '\0'; i++) {

        length++;

    }

 

    // Reverse string manually

    for (i = length - 1, j = 0; i >= 0; i--, j++) {

        rev[j] = str[i];

    }

    rev[j] = '\0'; // Null terminate reversed string

 

    // Display reversed string

    printf("Reversed string: %s\n", rev);

 

    return 0;

}

Output

 
INPUT :
Enter a string: ITDeveloper

OUTPUT :
Reversed string: repoleveDTI

Explanation

  1. The program reads a string from the user.
  2. The length of the string is found using a loop.
  3. A second loop copies characters from the end of str to rev.
  4. The reversed string is null-terminated and printed.

 

C Program: Reverse a String (Without strrev())

Method 2: Using fgets() function

C

#include <stdio.h>

 

int main() {

    char str[100], rev[100];

    int i, j, length = 0;

 

    printf("Enter a string: ");

    fgets(str, sizeof(str), stdin);

 

    // Remove newline character if present

    for (i = 0; str[i] != '\0'; i++) {

        if (str[i] == '\n') {

            str[i] = '\0';

            break;

        }

        length++;

    }

 

    // Reverse the string

    for (i = length - 1, j = 0; i >= 0; i--, j++) {

        rev[j] = str[i];

    }

    rev[j] = '\0';

 

    printf("Reversed string: %s\n", rev);

 

    return 0;

}

Output

 
INPUT :
Enter a string: ITDeveloper

OUTPUT :
Reversed string: repoleveDTI

Explanation

  1. The program reads a string from the user.
  2. The length of the string is found using a loop.
  3. A second loop copies characters from the end of str to rev.
  4. The reversed string is null-terminated and printed.