Java Arena
Step 6 of 7

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);
    }
}
Input
10
Output
1 doubled 10 times is 1024

With 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.

Your task

Challenge 1 of 3

Read a base and an exponent, and calculate the power with a loop, without Math.pow. For the input 3 and 4 the program prints:

3 to the power 4 is 81

Challenge 2

In how many different orders can n books stand on a shelf? The first place can hold any of the n books, the next any of the n - 1 left, and so on, so the answer is n times (n - 1) times ... times 1. With 0 books there's exactly 1 way (an empty shelf). Read n and print the answer. For the input 5 the program prints:

5 books can be arranged in 120 ways

Challenge 3

Read a number n and print the product of the odd numbers from 1 to n. For the input 7 the program prints 105, because 1 times 3 times 5 times 7 is 105:

105