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:
- Input
- Assignment Operator
- Loop
- 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:
