This code calculates the sum of the series 2^0 + 2^1 +….2^n where n is a number input by the user.
My Code
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Type a number: ");
int inputNum = Integer.parseInt(reader.nextLine());
int tick = 0;
int result = 0;
while (tick <= inputNum){
result += (int)Math.pow(2, tick);
tick++;
}
System.out.println("The result is " + result);
}
}
Model Code
Comments
I think I did fairly well on this one. I had a couple of problems. My code was refused as I hadn’t converted the double output by Math.pow(2, tick) back into an integer and I spent quite a while trying to figure out why it didn’t work only to find that I have used =+ instead of +=. For some reason this makes a difference.