Skip to content
Advertisement

nested for loop for alphabet increment

I have searched everywhere and I cannot figure out how to create this output using a nested for loop in java:

“a

ab

abc

abcd”

continued until z

this is what I have tried

String alphabet = “abcdefghijklmnopqrstuvwxyz”;

    for(int i = 0; i <= 25; i++)
    {
        for(char j = (char)(alphabet.charAt(i)); j<=i; j++)
        {

        System.out.print(j);
        }
        System.out.println();
    }

Please help me!

Advertisement

Answer

Here is the answer:

for (int x = 'a'; x <= 'z'; x++) {   /* Loop from 'a' to 'z' */
    for (int i = 'a'; i<=x; i++){   /* Loop from 'a' to int x */
        System.out.print((char)i);
    }
    System.out.println(); /* New Line */
}

The outer loop switches from one row to another while the inner loop prints the characters ('a' to x)for that particular row.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement