Search code examples
javaloopsfor-loopiterationalphabet

for loop, iteration through alphabet? java


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?


Solution

  • 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 ;)