jeudi 26 janvier 2017

How to prevent the wrong value entered by the user from getting stored in the variable?

I'm trying to prevent the user from entering a wrong value in this simple C program by using an if statement within while loop. But the problem is that whenever the user enters a wrong value, it gets stored in the variable and the same value is then use for further calculations. Here's the actual program:

#include <stdio.h>
#include <stdlib.h>
/*Program to calculate the marks obtained scored by the class in a quiz*/

    int main()
    {
    float marks, average, total = 0.0;
    int noStudents;
    printf("Enter the total number of students: ");
    scanf("%d", &noStudents);
    int a=1;
    while(a<=noStudents)
    {
        printf("Enter marks obtained out of 20: ");
        scanf("%f", &marks);
        if(marks<0 || marks >20)
        {
            printf("You have entered wrong marks\nEnter again: ");
            scanf("%d", &marks);
        }
        total = total+marks;
        a++;
    }
    average = total/(float)noStudents;
    printf("Average marks obtained by the class are: %f", average);


    return 0;
}

Aucun commentaire:

Enregistrer un commentaire