for loop, iteration through alphabet? java

pewpew picture pewpew · Oct 16, 2015 · Viewed 24.9k times · Source

I can iterate through the alphabet, but I'm trying to keep the last iteration and add on the next letter. this is my code.

for(char alphabet = 'a'; alphabet <='z'; alphabet ++ )
        {

            System.out.println(alphabet);
        }

I want it to print out something that looks like this.

a

ab

abc

abcd

abcde..... and so forth. How is this possible?

Answer

Stefan picture Stefan · Oct 16, 2015

You need to add the char alphabet to a string.

String output = "";

for(char alphabet = 'a'; alphabet <='z'; alphabet++ )
    {
        output += alphabet;
        System.out.println(output);
    }

This should work for you ;)