How to count even numbers in Java?

by dewayne_green , in category: Java , 2 years ago

How to count even numbers in Java?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by matteo , 2 years ago

@dewayne_green use for loop to iterate over numbers and count even numbers in Java, code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
public class Main {
    public static void main(String[] args) {
        // Initialize total even numbers with 0
        int total = 0;
        // loop over from 0 to 100
        for (int i = 0; i <= 100; i++) {
            // Check if number is even or not
            if (i % 2 == 0) {
                // Increase total
                total++;
            }
        }

        // Output: 51
        System.out.println(total);
    }
}


by jimmie.mante , a year ago

@dewayne_green 

There are several ways to count even numbers in Java, but one common solution is to loop through an array or a range of numbers and check if each number is divisible by 2 (i.e., if it is even). Here's an example code snippet that uses a for loop to count even numbers in an array:

1
2
3
4
5
6
7
8
int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int count = 0;
for (int i = 0; i < nums.length; i++) {
  if (nums[i] % 2 == 0) {
    count++;
  }
}
System.out.println("There are " + count + " even numbers in the array.");


In this code, we initialize an array of numbers and a counter variable (count). Then we loop through each element of the array (nums) and check if it's even by using the modulus operator (%) to check if it's divisible by 2. If it is, we increment the counter. Finally, we print out the total count of even numbers.