Search code examples
javaloopssumstringbuilder

Finding total sum of loop after finding all powers of 2 below certain number


I'm new to java/programming in general and this is a homework assignment. This is what I have so far: When I run it I get the powers of 2 below the n input. example if n = 50, output is 2 + 4 + 8 + 16 + 32 + = -2 I would like the + after 32 to be gone and I don't know how to properly sum it. I would want the sum to = 62 in this case. I tried using string builder to take off the last two characters but that isn't working for me.

import java.util.Scanner;
public class Powers {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        int n;
        System.out.print("Enter the upper limit: ");
        n = scan.nextInt();

        int sum = 0;
        int power = 1;

        for (int i = 0; i <= n; i++) {
            power = 2 * power;

            if (power < n && 0 < power) {
                System.out.print(power + " + ");
            }
            sum = sum + power;

        }

        System.out.println(" = " + sum);

    }
}

Solution

  • There are multiple issues here:

    • When reaching the upper limit you simply stop doing the output but continue doing the summation.
    • You use the upper limit as the number of iterations, so in case of 50 in your example, you do a sum of all values between 1 and 2^50, which is the reason why the result is negative, because the sum became larger than the maximum number an int can keep.

    Concerning your question how to break a loop, there is break ;-)

    Your print is always outputting a + which is why you have the + = in your output. Change the output to something like this:

    if (power < n && 0 < power) {
        if (i != 0) {
            System.out.print(" + ");
        }
        System.out.print(power);
    }