In: Computer Science
Program Name: Divisible. Write a program that calculates the number of integers in a range from 1 to some user-specified upper bound that are divisible by 3, the sum of those integers, and the number and sum of those integers not divisible by 3. Your program must display meaningful output which includes: the selected upper bound number of integers divisible by 3 sum of integers divisible by 3 number of integers not divisible by 3 sum of integers not divisible by 3
IN JAVA USING A WHILE LOOP
JAVA CODE :
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner s = new
Scanner(System.in);
System.out.print("Enter the upper
bound : ");
int n = s.nextInt(); // read the
upperbound
int i = 1;
int n1 = 0, n2 = 0, sum1 = 0, sum2
= 0;
while(i <= n)
{
if(i % 3 == 0) // if divisible by
3
{
sum1 = sum1 + i; // sum
n1++; // count
}
else{ // if not
sum2 = sum2 + i; // sum
n2++; // count
}
i++;
}
System.out.println("Count of no's
divisible by 3 : " + n1);
System.out.println("Sum of no's
divisible by 3 : " + sum1);
System.out.println("Count of no's
not divisible by 3 : " + n2);
System.out.println("Sum of no's not
divisible by 3 : " + sum2);
}
}
OUTPUT :