PeterPan
PeterPan

Reputation: 744

for doesn't check second condition

You can see my code below. I'm trying to check whether the sum of the entered numbers is above 100 or one of the entered numbers is above 20. If one of these happens the program should quit. If I enter numbers so the sum is higher than 100 the program quits. But if I enter a number higher than 20 the program just continues to run.

#include <stdio.h>
#include <string.h>

int main() {

    int numbers;
    int sum = 0;

    printf("Please enter numbers:\n");

    for (numbers = 0; sum < 100 || numbers < 20; numbers++) {
        scanf("%d", &numbers);
        sum += numbers;
    }
    printf("Sum: %d\n", sum);


    return 0;
}

Upvotes: 1

Views: 51

Answers (1)

R_Kapp
R_Kapp

Reputation: 2858

If one of these happens the program should quit

You want && then, not ||. Think about it; if either sum is less than 100 or numbers is less than 20, your program continues. So, when you enter a value for numbers greater than 20, your code will continue to run until and unless sum is also greater than 100.

Upvotes: 3

Related Questions