Computer Science, asked by lalitkhanna1977, 1 year ago

How to print the following pattern in java
1
12
123
1234
12345

Answers

Answered by QGP
9

Pattern Questions in Java


Pattern Questions in Java, or in any programming language are supposed to be answered by logic of loops. We cannot simply use System.out.println() commands to print the sentences.

So we employ logical methods. Let us analyze the pattern.


-> The Pattern consists of 5 rows

-> Each line has an increasing number of digits

-> Each line starts with 1


This all means that we will have to set a loop which will execute five times.

So a structure like this would work:

for(int i=1;i<6;i++)

{

       \\code

}


This would set up a loop which will execute 5 times, and the variable we have used here is i

Now, we see that we have to print the numbers themselves. So we can put a print statement.


We would now have:


for(int i=1;i<6;i++)

{

       System.out.print(i);

}


However this would provide only five numbers: 12345.


We have to print an increasing sequence inside. We will have to set another loop structure. Let us take another loop variable j


We see that if we set the end condition j<=i, then we have something wonderful.


Our Temporary Code:

for(int i=1;i<6;i++)

{

       for(int j=1; j<=i; j++)

       {

               System.out.print(j)

       }

       System.out.println();

}


In the first row, value of i is 1, and so by end condition of j<=i, only 1 will be printed in the first row.

The System.out.println() will then print a new line.


In the second row, i=2, and so the loop of j will essentially print 12, since it will run two times.


Similarly, in fifth row, i=5. The loop of j will run five times, and print 12345.


This way the complete pattern is printed.


CODE:

Here's the final code:


public class P1

{

   public static void main(String[] args)

   {

       for(int i=1;i<6;i++)

       {

           for(int j=1;j<=i;j++)

           {

               System.out.print(j);

           }

           System.out.println();

       }

   }

}


A Screenshot is also attached.

Attachments:

Anonymous: Fantastic
QGP: Thank You :)
Anonymous: Perfect explanation. :)
QGP: Thanks to both of you :)
Answered by atrs7391
0

Easiest program:

package com.company;  

public class Main {

  public static void main(String[] args) {

      int s = 0;

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

          s = s*10+i;

          System.out.println(s);

      }

  }

}

Output:

1

12

123

1234

12345

Similar questions