Search code examples
javaloopsinfinite-loop

Multiplication Table For Loop


This is the code I wrote; it's going into an infinite loop and I don't know why..

import java.io.*;

public class Multi{
    public static void main(String args[])throws IOException{

    int num;
    BufferedReader inpt = new BufferedReader (new InputStreamReader (System.in));

    System.out.print("Enter a number: ");
    num=Integer.parseInt(inpt.readLine());

    int z,x,y;

    while (num>=1 || num<=11){
        for(z=1; z<=num; z++){
            for(x=1; x<=z; x++){

                y=z*x;

                System.out.print(y+" ");

            }
            System.out.println();
        }

    }

  }
}

The output I want to show in this one is that when a person inputs a number it will display a multiplication table.

e.g.

Enter a number: 5

Result:

 - 1 2 3 4 5
 - 2 4 6 8 10
 - 3 6 9 12 15
 - 4 8 12 16 20
 - 5 10 15 20 25

Enter a number: 3

 - 1 2 3
 - 2 4 6
 - 3 6 9

Solution

  • Your while condition will never be false:

    while (num>=1 || num<=11)
    

    Every possible number is >= 1 or <= 11. I guess you meant "and" instead of "or".

    Also, you need to put the code that sets num inside the while-loop.