2

I have just written a program to reverse a word. I have first compiled the program as follows:

//This program will reverse a given word

#include <stdio.h>
int main()
{
int letters, i, j;
printf("Enter the number of letters in your word: ");
scanf("%d", &letters);

int word[letters];

printf("Enter %d Letters: ", letters);
for( i = 0; i < letters; i++){
    scanf("%c", &word[i]);
}

for( j = i - 1; j >= 0; j-- ){
    printf("%c", word[j]);
}


return 0;
}

Then, I inputted 5 to store in letters and the word "rubel" (ignore the inverted comma) to reverse. The expected output was "lebur". But unfortunately i got ebur. then i recompiled the code as below:

//This program will reverse a given word

#include <stdio.h>
int main()
{
int letters, i, j;
printf("Enter the number of letters in your word: ");
scanf("%d", &letters);

int word[letters];

printf("Enter %d Letters: ", letters);
for( i = 0; i < letters; i++){
    scanf(" %c", &word[i]);
}

for( j = i - 1; j >= 0; j-- ){
    printf("%c", word[j]);
}


return 0;
}

This time i got expected output which is "lebur". Now, my question is what was wrong before that i didn't get expected output and what have i just done by putting a space that this time i got the expected result. Thanks in advance.

Rubel Hosen
  • 37
  • 1
  • 1
  • 5

1 Answers1

0

In the first case word[0] became \n (you entered 5\n). In the second case the \n was skipped because you told scanf to skip whitespace characters (by ).

Kirill Bulygin
  • 3,658
  • 1
  • 17
  • 23