john_thomas
john_thomas

Reputation: 21

Java loop divisibility sum and average

I have made a loop that produces the sum and average of numbers 1,2,3,...,to an upperbound 100. What I am having trouble with is modifying my current code so it only includes numbers that are multiples of 7. Here is what I have:

public class SumAndAverageForLoop {

     public void SumAndAverageForLoop() {
         double sum = 0;
         for (double i = 1; i <=100; i++) sum+= i;
         System.out.println ("the average is " + sum/100);

         System.out.println ("the sum is " + sum);

     }
}

I am trying to do it without a main method so I had to create a Launcher class.

Any help is appreciated. Thank you in advance.

Upvotes: 2

Views: 2263

Answers (4)

user3248346
user3248346

Reputation:

In Java 8 this is now easily accomplished without writing error prone looping structures as follows:

IntStream.range(0,100).filter(i -> i % 7 == 0).summaryStatistics();

Result:

IntSummaryStatistics{count=15, sum=735, min=0, average=49.000000, max=98}

Upvotes: 1

bhspencer
bhspencer

Reputation: 13570

In order to determine if a number is divisible by 7 you should use the modulo devision operator % and compare the remainder to 0;

    int sum = 0;
    int count = 0;
    for (int i = 0; i <= 100; i++) {
        if (i % 7 == 0) {
            sum += i;
            count++;
        }
    }
    System.out.println("the average is " + sum/count);

    System.out.println("the sum is " + sum);

Also I wouldn't recommend using a double when all you need is an int. You might get caught out by precision issues further down the road. You could cast your sum to a double before dividing to by count if you want a decimal average. Like this:

System.out.println("the average is " + ((double) sum)/count);

Upvotes: 1

Prudhvi
Prudhvi

Reputation: 2343

Your for loop should increment in 7's for each iteration and also you should maintain a count of your iterations because you need it for finding average.

    int sum = 0;
    int count = 0;
    int average = 0;
    for(int i=7; i<=100; i=i+7)
    {
       sum = sum + i;
       count= count+1;
       average = sum/count;
    }

Upvotes: 0

Alex Glover
Alex Glover

Reputation: 876

I would use the Modulus operator for this use case.

public class SumAndAverageForLoop {

    public void SumAndAverageForLoop() {
        double sum = 0;
        for (double i = 1; i <=100; i++){
            if((i % 7) == 0){
                sum+= i;
            }

        System.out.println ("the average is " + sum/100);

        System.out.println ("the sum is " + sum);

    }

}

Upvotes: -1

Related Questions