cvandal
cvandal

Reputation: 794

Count the result from a loop and if statement

I have an array of numbers which I am looping through to find numbers equal to 90 or greater than 90. My current code prints each number that matches the criteria (they are 91, 93, 93, 96, 97) but instead, I would like to count how many numbers match the criteria and print that instead (in this case it would be 5). How would I go about achieving this?

My code is as follows:

for (int i = 0; i < scores.length; i++) {
    if (scores[i] == 90 | scores[i] > 90) {
        System.out.println(scores[i]);
    }
}

Upvotes: 0

Views: 1297

Answers (3)

Lasitha Benaragama
Lasitha Benaragama

Reputation: 2209

int count = 0;
for (int i = 0; i < scores.length; i++) {
    if (scores[i] == 90 | scores[i] > 90) {
        System.out.println(scores[i]);
        count++
    }
}
System.out.println(count);

Try this.

Upvotes: 2

Rohan
Rohan

Reputation: 3078

Declare count variable to keep track of how many numbers satisfy given criteria.

int cnt=0;
for (int i = 0; i < scores.length; i++) {
    if (scores[i] == 90 | scores[i] > 90) {

        cnt++;
    }
 System.out.println("Count : "+cnt);
}

Upvotes: 1

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79875

Before the loop, declare

int countOfScores = 0;

and inside the if block, write

countOfScores++;

Then you can print it out at the end.

Upvotes: 5

Related Questions