C Program to Print Reverse of a String
C Language

C Program to Print Reverse of a String (with Algorithm)


In this article, I will show you how you can write a C Program to Print Reverse of a String. I will explain the algorithm, concepts and then help you to write C Program to Print Reverse of a String.

1. Program Outline

In this program, we will input a string and then print the reversed string in the Terminal. Let’s write this C Program to Print Reverse of a String.
We first need to ask the user with input to get the String. After entering the String, we need to reverse the string and finally print the reversed string.

2. Concepts

To write this C Program to Print Reverse of a String, you need to learn the following concepts of C Programming:

  1. Input
  2. Assignment Operator
  3. Loop
  4. Output

3. Algorithm

To write this C program, follow this Algorithm:

public static String reverse(String orig)
{
    char[] s = orig.toCharArray();
    int n = s.length;
    int halfLength = n / 2;
    for (int i=0; i<halfLength; i++)
    {
        char temp = s[i];
        s[i] = s[n-1-i];
        s[n-1-i] = temp;
    }
    return new String(s);
}

4. Program

Here’s the C Program to Print Reverse of a String:

#include <stdio.h>
int main()
{
  char str[1000], rev[1000];
  int i, j, count = 0;
  printf("Welcome to CodeWin.org!!!\n");
  printf("-----------------------\n");
  printf("Enter a String: ");
  scanf("%s", str);
  printf("\nString Before Reverse: %s", str);
  //finding the length of the string
  while (str[count] != '\0')
  {
    count++;
  }
  j = count - 1;

  //reversing the string by swapping
  for (i = 0; i < count; i++)
  {
    rev[i] = str[j];
    j--;
  }

  printf("\nString After Reverse: %s", rev);
}

5. Output

Here’s the output of the above C Program:

Welcome to CodeWin.org!!!
-----------------------
Enter a String: CodeWin

String Before Reverse: CodeWin
String After Reverse: niWedoC
C Program to Print Reverse of a String
Repl.it compiler

6. Resources

If you want to try this C Program on your own PC or Mobile, you can download these files:

Similar Posts

Leave a Reply

Your email address will not be published.