Audrey Tipton
Audrey Tipton

Reputation: 45

How to Write a Summation of Fives in Java

I need to write a program in Java that can take the multiples of five up to a value given by the user, and then add all of the multiples together. I need to write it with a while loop.

Here's what I have so far:

import java.util.Scanner;

public class SummationOfFives {
    public static void main(String[] args){

        //variables
        double limit;
        int fives = 0;

        //Scanner
        System.out.println("Please input a positive integer as the end value: ");
        @SuppressWarnings("resource")
        Scanner input = new Scanner(System.in);
        limit = input.nextDouble();

        //While Loop
        while ((fives+5)<=limit)
        {
            fives = fives+5;
            System.out.println("The summation is: "+fives);
       }
    }
}

When I run this program however, all it gives me is the multiples:

Please input a positive integer as the end value: 
11
The summation is: 5
The summation is: 10

Upvotes: 2

Views: 153

Answers (3)

T.Gounelle
T.Gounelle

Reputation: 6033

The summation you do in fives is wrong. You need another variable multiple initialised to 0 that you will increment by 5 at each step of the loop. The stop condition in the while is (multiple < limit). Then fives are the sum of the multiples.

    double limit;
    int fives = 0;
    int multiple = 0

    //While Loop
    while (multiple<=limit)
    {
        multiple += 5;
        fives = fives + multiple;
        System.out.println("So far, the summation is: "+fives);
   }

Upvotes: 0

J Richard Snape
J Richard Snape

Reputation: 20344

You're nearly there! Think about what your output is telling you. In your while loop, fives is the next multiple of 5 on each iteration. You're not adding it to a total variable anywhere.

So - define a total before the loop e.g.

int total = 0;

keep adding to it in the loop (where your System.out.println is now) e.g.

total = total + fives;

output the total after the loop e.g.

System.out.println(total);

Upvotes: 3

GermaineJason
GermaineJason

Reputation: 589

I added a total variable into your loop that will accumulate the value of all of the summations.

    int counter =1;
    int total = 0;
    //While Loop
    while ((fives+5)<=limit)
    {
        total = counter*5;
        counter++;
        fives = fives+5;
        System.out.println("The summation is: "+fives);
        System.out.println("The total is: "+total);
   }

Upvotes: 0

Related Questions