Click here to Skip to main content
15,506,747 members
Please Sign up or sign in to vote.
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

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.
 
Share this answer
 
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();
  }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900