Search code examples
cloopsfor-loop

Trouble Returning to Previous input in loop


I am creating a program that will have me enter 6 grades 1-50 and have it give me the total amount of points and the percentage of the scores. The only trouble I am having on it is that when the if loop activates, it will not return to the previous input and will skip to the next input. How do I make it so that it returns to the previous input so that it can be re-entered?

#include <stdio.h>
int main() {
      int percent;
      int totalscore;
      const int score[5];
   for (int grades = 1; grades <= 6; grades++) { 
         printf("please enter the grade for assignment #%d: ", grades);
         scanf("%d", &score[grades]);
   if (score > 0 , score > 51);
      printf("Please enter a number between 1 and 50\n");
      
   }
   totalscore = score[1] + score[2] + score[3] + score[4] + score[5] + score[6];
   printf("Over 6 assignments you earned %d points out of a possible 300 points!\n", totalscore); 
percent = totalscore / 3 ;
   printf("Your grade is %d percent.", percent);
   return 0;
   }


Solution

  • I can see some beginner's flaws in the input part itself.

    The if condition is not correct. - you want to check the input value entered at a particular index, not the whole array. Also, you have closed the if condition by giving ; which breaks the scenario.

    I have updated the code piece.

      for (int grades = 1; grades <= 6; grades++) {
        printf("please enter the grade for assignment #%d: ", grades);
        scanf("%d", & score[grades]);
    
        // updated if condition. 
        if (score[grades] < 1 || score[grades] > 50) {
          printf("Please enter a number between 1 and 50\n");
          grades--;
        }
    
      }
    

    EDIT -

    updating the condition to accept inputs only from 1-50. Thanks @ Jonathan Leffler