Write a program for reverse printing of a given string in c

20 Sep 2022 Balmiki Mandal 0 C Programming

"Reverse printing of a given string" means printing out the characters of a given string in reverse order, without actually modifying the original string. This is different from simply reversing the string, which would change the order of the characters in the original string.

For example, if we have the string "hello", the reverse of that string is "olleh". However, if we are asked to print the string in reverse order, we would print out the characters in the string in the order "o", "l", "l", "e", "h".

Reverse printing of a string can be useful in situations where we need to display the string backward without changing its original order, or if we want to process the string in reverse order without modifying it.

 

Write a c program for reverse printing of a given string

#include<stdio.h>
void main()
{
    char s[10];
    int i;
    printf("Enter the string:");
    scanf("%s",s);
    printf("Before:%s\n",s);
    for(i=0;s[i];i++);//finding the length of the string i=5
    printf("After:");
    for(i=i-1;i>=0;i--)
    printf("%c",s[i]);
    printf("\n");
}

Output:

Enter the string: ELECTRO4U

Before: ELECTRO4U

After: U4ORTCEL

 

Write a c program for reverse printing of a given string using strlen

#include <stdio.h>
#include <string.h>

int main() {
   char str[100]; // declare a string to store user input

   // Read input string from user
   printf("Enter a string: ");
   scanf("%s", str);

   // Print the string in reverse order
   int len = strlen(str);
   for (int i = len - 1; i >= 0; i--) {
      printf("%c", str[i]);
   }
   printf("\n");

   return 0;
}

In this program, we first declare a character array str of size 100 to store the user input string. We then read the input string from the user using the scanf() function.

Next, we determine the string length using the strlen() function from the string.h library. We then use a for loop to iterate through the string in reverse order, starting from the last character and ending at the first character. During each iteration, we print out the character at the current position in the string.

Finally, we print a newline character to move the cursor to the next line after the reversed string is printed.

When we run this program and enter a string, it will output the reverse of the input string:

Enter a string: Hello, world! !dlrow ,olleH

We can see that the program prints the input string in reverse order.

 

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.