Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: Creating number Pyramids with For Loops

1. ## Creating number Pyramids with For Loops

So, I just had a random urge (after reading a previous post) to make an infinite loop that creates this output:

1
12
123
1234
12345
1234
123
12
1
12
123
.... etc.

So far I have this:

import java.util.Scanner;

public class ForTriangle {
public static void main(String args[]){

Scanner scan = new Scanner(System.in);
System.out.println("Enter length of numbers");
int number = scan.nextInt();

int a = 1;
int b = 1;

while(b < number){
for(a = 1; a <= number; a++){
for(b = 1; b <= a; b++){
if(b == number)
a = 0;
System.out.print(b);
}
System.out.println();
}

}

}//End MM
}//End MC

When the user enters 5, it produces:

1
12
123
1234
12345
1
12
123
1234
12345
etc...

Any tips?

2. ## Re: Creating number Pyramids with For Loops

Any tips?
You can look at it as two sequences, one like this:
1
12
123
1234
and one like this
12345
1234
123
12
A loop that does those two over and over could be about right

3. ## Re: Creating number Pyramids with For Loops

If I try to do this, the first for loop will run on forever, and ever.. And the second for loop will never be used because the first for loop never ended. I already seemed to have lost interest in this.. Thanks for replying so quickly though Sean!

4. ## Re: Creating number Pyramids with For Loops

You need an outer 'loop forever' with two inner loops. Inside the outer loop the first inner loop loops from min to max - 1, then it exits. The second inner loop loops from max to min + 1, then exits. After the second inner loop exits, the outer 'loop forever' makes the first loop run again...