11.1k views
4 votes
Write a program named as reverse.c that reads a message, then prints the reversal of the message. The output of the program should look like this: Enter a message: Don ’t get mad, get even. Reversal is : .neve teg ,dam teg t ’noD Hint: Read the message one character at a time (using getchar) and store the characters in an array. Stop Reading when the array is full or the character read is ‘\\’. The framework of reverse.c is as below: /* reverse.c */ #include #define N 50 int main(){ int arr[N],i=0; char ch; printf("Enter a message: "); /* Put code here to get input from user by using getchar() */ printf("Reversal is: "); } /* Put code here to print out the reversal by using putchar()*/ printf("\\"); return 0;

1 Answer

3 votes

Step-by-step explanation:

#include <stdio.h>

#define N 20

int main()

{

char str[N];

char reverse[N];

int c;

int i;

int j;

int k;

int flag=0;

printf("Enter a string: ");

i=0;

j=0;

while((i<N)&&((c=getchar())!='\\')){

str[i] = c;

i++;

}

k=i;

while((j<=k)&&(i>=0)){

reverse[j]=str[i];

j++;

i--;

flag=1;

}

i=0;

while(i<=k){

putchar(reverse[i]);

i++;

}

return 0;

}

  • The first while loop will read the string character wise.
  • while((i<N)&&((c=getchar())!='\\')) : This statement will check whether it has reached the end of the line or the specific number of characters are reached.
  • 2nd file loop will reverse the string and transfer to another array.
  • Third loop will print the reversed string.
User Kalandar
by
4.7k points