15,510,281 members
1.00/5 (1 vote)
See more:
qInput : 9

Output:
1
23
456
789

//Or

Input: 10

Output;
1
23
456
78910

//Or

Input:12
Output:
1
23
456
78910
1112

What I have tried:

Java
import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

int input = scan.nextInt();

for(int i = 1; i <= input; i++){

System.out.print(i);

System.out.println();

//Problem is how to make the ouput like a pyramid like this
// 1
// 23
// 456
// 789\\

}

}
}
Posted
Updated 5-Dec-21 21:51pm
v2

## Solution 1

Think about it: what is common to all the prints?
1
23
456
789

1
23
456
78910

1
23
456
78910
1112

They all start with the same number, and each successive line has one more number printed, until the target number is done.
So you need a loop, which prints all the number up to and including the target. Write that first, and test it. Make sure it prints exactly what you expect under all circumstances:
123456789
12345678910
123456789101112

When that works, add a variable outside the loop called printLineAtand a second calledprintingAt. Set both to 1.
Then inside the loop reduce printingAt by one and check it.
If it is zero, increment printLineAtand a setprintingAt to the new value. Then print a newline.

Try it, it's not as complicated as you think.

## Solution 2

A simple way to obtain the result is introducing two variables, to keep track of the current count of digits in the row and the total number of allowed digits in the same row:
Java
import java.util.Scanner;

public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();

int count = 0; int limit = 1;

for(int i = 1; i <= input; i++)
{
System.out.print(i);
++count;
if ( count == limit )
{
System.out.println();
++limit;
count = 0;
}
}
if (count != 0)
System.out.println();
}
}