Skip to content

Can I run a while loop inside a for loop? [Java] If so, how would I do it in this scenario?

Im doing some simple maths using loops and my task is as follows:

“Given an integer,N , print its first 10 multiples. Each multiple N * i (where 1 <= N <= ) should be printed on a new line in the form: N x i = result.”

My input has to be :

N

My output:

Print 10 lines of output; each line 'i' (where 1 <= N <= ) contains the result N * i of  in the form: N x i = result.

Sample Input:

2

Sample Output:

2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20

This is what I have done so far:

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {



    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        int N = scanner.nextInt();
        scanner.skip("(rn|[nru2028u2029u0085])?");
        
        for (int i = 0; i >= 1 && i <= 10; i++){
            
            
        }

        scanner.close();
    }
}

Would I be able to use a while loop to state the the integer, N, should be able to print out all the numbers in the inclusive range of 1 to 10 to the calculation of the (sample) input: 2×1=2. 2×2=4 etc.

If I can do it without the while loop i.e just using the for loop or for-each, please advise on how I can do it. Im really confused with this. Thanks.

Answer

I really don’t see the problem, you don’t need a while loop at all, you just need simple maths:

public static void main(String[] args) {
    int N = scanner.nextInt();
    scanner.skip("(rn|[nru2028u2029u0085])?");
        
    // I removed the i >= 1 because it hinders the for loop from even staring,
    // you had i = 0 before, so the i >= 1 would output false. So the for loop would stop
    // instantly. You can just start the loop with the number 1 so you dont multiply by zero.
    for (int i = 1; i <= 10; i++) {
        System.out.println(N + " x " + i + " = " + (N * i));
        /*
        lets say N is 2, then it will output the following:
        2 x 1 = 2
        2 x 2 = 4
        2 x 3 = 6
        2 x 4 = 8
        2 x 5 = 10
        2 x 6 = 12
        2 x 7 = 14
        2 x 8 = 16
        2 x 9 = 18
        2 x 10 = 20
        Just as you want it to.
        */
    }
    
    scanner.close();
}