Write a program to compute and display the sum of all integers that are divisible by 6 but not divisible by 4 and lie between 0 to 100. The program should also count and display the numbers of such values.

Below is a Java program that computes and displays the sum of all integers between 0 and 100 that are divisible by 6 but not divisible by 4. It also counts and displays the number of such values.

				
					public class SumAndCount {
    public static void main(String[] args) {
        int sum = 0;
        int count = 0;

        for (int i = 0; i <= 100; i++) {
            if (i % 6 == 0 && i % 4 != 0) {
                sum += i;
                count++;
                System.out.print(i + " "); // Display the values
            }
        }

        System.out.println("\nSum of all integers divisible by 6 but not by 4 between 0 and 100: " + sum);
        System.out.println("Number of such values: " + count);
    }
}

				
			

Explanation:

  1. Initialization: We initialize two variables, sum to store the sum of the integers and count to keep track of how many such integers there are.
  2. Loop: We use a for loop to iterate through all integers from 0 to 100.
  3. Condition Check: Inside the loop, we check if a number is divisible by 6 (i % 6 == 0) but not divisible by 4 (i % 4 != 0).
  4. Sum and Count: If the condition is true, we add the number to sum and increment count. We also print the number to show all such values.
  5. Output: After the loop, we print the sum and the count of the numbers.

Output:

When you run the program, it will display the integers that meet the criteria, their sum, and their count. The output should look something like this:

				
					6 18 30 42 54 66 78 90 
Sum of all integers divisible by 6 but not by 4 between 0 and 100: 384
Number of such values: 8

				
			

To compile and run this program:

  1. Save the code in a file named SumAndCount.java.
  2. Open a terminal and navigate to the directory containing the file.
  3. Compile the program using the javac compiler
				
					javac SumAndCount.java

				
			

Run the compiled program using the java interpreter:

				
					java SumAndCount


				
			

You should see the output displayed as shown above.

Scroll to Top