user2852927
user2852927

Reputation: 3

powers of 2 java code help with my input different outcome

import java.util.Scanner;

public class PowersOf2
{
    public static void main(String[] args)
    {
        int inputPowersOf2;        
        int PowerOf2 = 1;   
        int exponent;
        int exponent2;

        Scanner scan = new Scanner(System.in);

        System.out.println("How many powers of 2 would you like printed?");
        inputPowersOf2 = scan.nextInt();
        System.out.println("\n\n");
        if(inputPowersOf2 >= 2)
        {
            System.out.println("Here are the first " + inputPowersOf2 + " powers of 2:");
            System.out.println();
        }
        else
        {
            System.out.println("Here is the first power of 2:");
            System.out.println();
        }

        exponent2 = 0;
        exponent = 0;
        while(exponent <= inputPowersOf2)
        {
            System.out.print("2^" + exponent2 + " = ");
            exponent2++;
            System.out.println((PowerOf2 = 2 * PowerOf2) / 2);
            exponent++;
        }
    }
}

why is it when i say give me 1 power of two it prints

2^0
2^1

and when i say give me 2 powers of two it prints

2^0
2^1
2^2

and so on...

Upvotes: 0

Views: 839

Answers (2)

neutrino
neutrino

Reputation: 2317

Replace

while(exponent <= inputPowersOf2)

with

while(exponent < inputPowersOf2)

As others said in comments, this is very, very easy to solve using the debugger.

Hope that helps,

Upvotes: 1

Krishna Chaitanya
Krishna Chaitanya

Reputation: 61

You could retrace the steps manually on a paper using small inputs and then proceed to larger inputs.

just replace the code while(exponent <= inputPowersOf2) because it runs one extra time becuase of the "=" sign.

Upvotes: 0

Related Questions