In: Computer Science
SOLVE IN C: 6.31 LAB: Print string in reverse
Write a program that takes in a line of text as input, and outputs that line of text in reverse. You may assume that each line of text will not exceed 50 characters.The program repeats, ending when the user enters "Quit", "quit", or "q" for the line of text.
Ex: If the input is:
Hello there Hey quit
then the output is:
ereht olleH yeH
Hint: Use the fgets function to read a string with spaces from the user input. Recall that if a newline character is read from the user input before the specified number of characters are read, the newline character itself is also written into the string.
Screenshot of the code:
Sample
Output:
Code to copy:
//Include the necessary header files
#include <stdio.h>
#include <string.h>
//Declare the maximum size as 50
#define MAX 50
//The main function
int main(void)
{
// Declare the array, names to store the input strings
char names[MAX];;
// Declare the 2-D array to store the characters of the input
//strings
char arr[10][50];
// Declare the required variables
int i, j, index, length;
// Initialize the index and length to 0.
index = length = 0;
while(1)
{
// Take the strings as input in the array names such that the // maximum length does not exceed the value stored in MAX.
fgets(names, MAX, stdin);
//length is the variable that stores the length of
//all the strings stored in names.
length = strlen(names);
//delete the trailing spaces.
names[length - 1] = '\0';
//If the user enters Quit/quit/q, then the break statement is // encountered.
if(!strcmp(names,"quit") || !strcmp(names,"Quit") ||!strcmp(names,"q") )
{
break;
}
//Copy the strings stored in names to the array arr
strcpy(arr[index], names);
// Increment the index
index++;
}
//Iterate the loop from 0 to index
for(i = 0; i < index; i++)
{
//Iterate the strings in reverse manner, starting from the //end.
for(j = strlen(arr[i]) - 1; j >= 0; j--)
{
//Print the reveresed strings
printf("%c", arr[i][j]);
}
//Print the reversed strings in separate lines.
printf("\n");
}
return 0;
}