Monday, August 20, 2018

New to C,Loop Issues [closed]

I want to enter value to my array and between 0 and 101 and trying to put zero or 101 will return an error but putting anything from 1-100 will allow me to enter a second number.

but i am stuck when write code to add a second number the loop keeps going in 1 and i cant figure out my error. any help would be apreciated

#include 
#include 

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
char letter;

int main() 
{
    int i;
    int grades[12] ;

    for ( i = 0; i < 12; i++) 
        do{//loops the following peice of code if values over 100 or less than 0 are entered 

            printf("Please Enter Grade 1:\n");
            scanf("%f", & grades[i]);
            if (grades > 100 || grades < 0)
                printf("Invalid Entry please enter another between 0 and 100:\n");
        }while(grades < 100 || grades > 0);
}

Solved

The mistake here is you're comparing the whole array to a value. What you want is one element, plus you need to test that you're outside of the acceptable bounds:

while(grades[i] > 100 || grades[i] < 0);

As Jonathan points out below, the logic in your code tests that it's within, which means only valid answers will loop forever, the opposite of what you wanted.


No comments:

Post a Comment