Search code examples
javavariablesif-statementfor-loopauto-increment

Pyramid Pattern using a Loop


The expected output is as follows:

1
12
123
1234
12345
123456
1234567
12345678
123456789
1234567890
12345678901
123456789012

Following is the starting code I would use:

import java.util.Scanner;

public class Pyramid {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("Type in an integer value");
        Scanner in = new Scanner(System.in);
        int input = in.nextInt();
        String str = "";
        for(int i=1;i<=input;i++){
            str += i;
            System.out.println(str);
        }
    }
}

Following is my output as of now.

Type in an integer value
15
1
12
123
1234
12345
123456
1234567
12345678
123456789
12345678910
1234567891011
123456789101112
12345678910111213
1234567891011121314
123456789101112131415

I've been thinking about how to resolve this issue; if I write an If statement if(i > 9){ i = 0; }. But that would reset my counter?

How can I accomplish this task ? What am I missing ?


Solution

  • You can use the modulo operator to make i loop back around to 0 once it reaches 10:

    str += i % 10;