Reputation: 1
so I want to create a numerical right triangle in java using a nested loop and I created this:
public class nestedloop
{
public nestedloop()
{
loop();
}
public static void main(String [] args)
{
new nestedloop();
}
public static void loop()
{
System.out.println(" Enter a number ");
int n= IBIO.inputInt();
for (int i = 1; i <=n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
However, as you can see, it creates a right triangle formed out of asterisks and I want it to create it through increasing numbers like this:
1
23
456
78910
I'm confused as to what I need to replace the Asterix with. I was thinking it could be another loop but everything I have tried failed miserably.
Upvotes: 0
Views: 2077
Reputation: 1033
Just create a counter:
public static void loop(){
System.out.println(" Enter a number ");
int n= IBIO.inputInt();
int counter = 0;
for (int i = 1; i <=n; i++) {
for (int j = 1; j <= i; j++) {
System.out.println(++counter);
}
}
}
Upvotes: 2