Search code examples
javaloopsfor-loopnested-loops

A simple Java loop does not work as intended


In Java, each number is associated with a character. For example:

int ch = 65;
System.out.print((char)(ch)); // output: A

Similarly,

System.out.print((char)(66)); // output: B

and so on

This is my code:

for (int line = 1; line <= 4; line++) {
    for (int ch = 65; ch <= line; ch++) {
        System.out.print((char)(ch));
    }
    System.out.println();
}

I was expecting this output:

A
BC
DEF
GHIJ

Instead, I got:





(yup, nothing!)

What am I doing wrong?


Solution

  • Actually your condition ch <= line is always false.

    To fix it and get the expected result you can change the conditions and the loop limits:

    int startingChar = 65;
    for (int line = 0; line < 4; line++) {
        int ch;
        for (ch = startingChar ; ch <= startingChar + line; ch++) {
            System.out.print((char)(ch));
        }
        startingChar = ch;
        System.out.println();
    }