1

I was interested in the following problem: Take the colors as characters (for example : 'y' for yellow, 'r' for red etc.) into an array and display the same. While displaying there should be a single space between each characters. So to do this I wrote following code:

#include <stdio.h>


 int main(){

char a[10];
int i,n;
printf("Enter the number of colors (less than 10)\n");
scanf("%d", &n);
printf("Enter colors as alphabets : ");
for (i = 0; i < n; i++){
    scanf("%c", &a[i]);
}
printf("Entered colors are : ");
for (i = 0; i<n; i++){
    printf("%c ", a[i]);
}

return 0;
 }

If I enter the size of array as 3 and Colors as r y g , the output is not printing all three inputs instead it is printing only one. Little did I realized that there is a problem with scanf function. What might be the problem?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Infinity_hunter
  • 157
  • 1
  • 7

1 Answers1

1

Use the following conversion specifier

scanf(" %c", &a[i]);
      ^^^

This allows to skip white spaces that for example correspond to the pressed Enter key.

Also after this loop

for (i = 0; i<n; i++){
    printf("%c ", a[i]);
}

place the statement

putchar( '\n' );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335