Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why don't i get the out put for values of 'a' other than 1?

why isn’t the loop starting again with different value of a other than 1.

package com.company;

import java.util.Scanner;

public class ForDemo {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.println();
        System.out.print("ENTER A NUMBER: ");
        int b = sc.nextInt();
        int a;
        
        for(a=1 ;a<11;a=a+1)
        for(b=b;b<16;b=b+1)
        System.out.println(b + " * " + a + " = " + b*a);
    }
}

output:

ENTER A NUMBER: 1

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

1 * 1 = 1

2 * 1 = 2

3 * 1 = 3

4 * 1 = 4

5 * 1 = 5

6 * 1 = 6

7 * 1 = 7

8 * 1 = 8

9 * 1 = 9

10 * 1 = 10

11 * 1 = 11

12 * 1 = 12

13 * 1 = 13

14 * 1 = 14 here it terminates!

required output:

1 * 1 = 1

2 * 1 = 2

3 * 1 = 3

4 * 1 = 4

5 * 1 = 5

6 * 1 = 6

7 * 1 = 7

8 * 1 = 8

9 * 1 = 9

10 * 1 = 10

11 * 1 = 11

12 * 1 = 12

13 * 1 = 13

14 * 1 = 14

15 * 1 = 15

1 * 2 = 2

2 * 2 = 4

3 * 2 = 6

4 * 2 = 8

5 * 2 = 10

6 * 2 = 12

7 * 2 = 14

8 * 2 = 16

9 * 2 = 18

10 * 2 = 20

11 * 2 = 22

12 * 2 = 24

13 * 2 = 26

14 * 2 = 28

15 * 2 = 30 and so on….

>Solution :

Simply assign your input variable (x) at the starting of the inner loop as below will solve your problem.

Till now you were initialized b as the last value of the previous iteration that is why your inner loop is not executed after the first iteration.

public class Simple {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.println();
        System.out.print("ENTER A NUMBER: ");
        int x = sc.nextInt(); // take input as x

        for(int a=1 ;a<11;a++) {
            for (int b = x; b < 16; b = b + 1) { // initialize b with input variable(x)
                System.out.println(b + " * " + a + " = " + b * a);
            }
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading