Multiplying in a loop
A product is built up like a sum, with one difference: it starts at 1, not 0. Starting at 0 would make every product 0.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int doublings = Integer.valueOf(scanner.nextLine());
int value = 1;
for (int i = 0; i < doublings; i++) {
value *= 2;
}
System.out.println("1 doubled " + doublings + " times is " + value);
}
}
101 doubled 10 times is 1024With 0 as the input the loop doesn't run, and the value stays 1, which is right: doubling zero times changes nothing. (The same loop calculates 2 to the power of the input.)
Products grow fast. An int holds values up to 2147483647 (module 4), so these programs only work for fairly small inputs. The tests here stay inside that limit.