0

My assignment code asks a user to enter grades for 5 different courses, however, the code can't use more than 1 scanf statement to store the variables.

How can I use a loop to do the same thing this code does?

  int courseOne;
  int courseTwo;
  int courseThree;
  int courseFour;
  int courseFive;

  scanf ("%d", &courseOne);
  scanf ("%d", &courseTwo);
  scanf ("%d", &courseThree);
  scanf ("%d", &courseFour);
  scanf ("%d", &courseFive);

Thanks!

Edit: Arrays are not allowed to be used. It is explicitly stated in the grade rubrics that a loop must be written for this question.

Steve Summit
  • 45,437
  • 7
  • 70
  • 103

1 Answers1

1

scanf can read multiple variables.

Like with printf, the first variable is the format, the followings contains where to store the data.

Thus, in your example you can use

scanf("%d %d %d %d %d", &courseOne, &courseTwo, &courseThree, &courseFour, &courseFive);

See the manpage for more info.


You state in your comment that arrays are forbidden AND you use a loop. That seem incompatible to me.

  • Either you want to use a loop, thus arrays is the logic way to go
  • Or you want to use normal variables thus you don't need a loop.

It could be possible to use a loop without array/pointer but the code would be really dumb so you should pick one of the two possibilities instead.

Maybe you can't use static arrays int foo[6] but you can use pointer-based arrays such as int* foo = malloc(6*sizeof(int));. If none is allowed your problem loops don't make much sense.

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
Maxime B.
  • 1,116
  • 8
  • 21