Simple Number Pattern

Simple Number Pattern

1280 720 mrrohit

To print any patterns of numbers or stars (*) in Java Programming, you have to use two loops.

The first is an outer loop and the second is an inner loop.

The outer loop is responsible for rows and the inner loop is responsible for columns

outer for loop
 
// outer for loop
for(int i=0; i<5; i++)    
         {
//inner for loop will be write here
}

 

 

 

So we will try to implement step by step.
Firstly we will try to achieve

Basic
 
1
1
1
1
1

So we will start with a for loop, here start value of i will be 0 and will be less than 5. So value is going from 0 to 5 so it is increment.
We will use int count = 1;

Basic for loop
 
  {
       int count =1;
       System.out.println(count);
  }

So when we will run this we will see output as same.

This for run in horizontal line, now we need to go for horizontal line also.
Now we need output as :

Basic-3 output
 
1 1 1 1 1 
1 1 1 1 1 
1 1 1 1 1 
1 1 1 1 1 
1 1 1 1 1

Now we will add one inner for loop, it will be responsible to print in horizontal line.

Basic-3
 
for(int i=0; i<5; i++)
      {
         int count =1;
         for(int j=0; j<5;j++)
          {
           System.out.print(count);
           }
          System.out.println();
       }

So now we got output as we expected.

So now we will add count++  in inner for loop.

Basic-4 Code
 
for(int i=0; i<5; i++)
{
  int count =1;
  for(int j=0; j<5;j++)
   {
     System.out.print(count);
    count++;
   }
  System.out.println();
}

and once we will run this code, will get output as

Basic-4 Output
 
1 2 3 4 5 
1 2 3 4 5 
1 2 3 4 5 
1 2 3 4 5 
1 2 3 4 5

Now, we have completed maximum thing, but the output is going from 1 to 5 in every line.
now we need value of count will be always start from 1 and it will increase according to first for loop(outside).
we will also change the value of j<=i.
Now you can run the below code and you will get the desired output.

Simple Number Pattern
 
public class StarAndNumber {
      public static void main(String[] args) {
            // TODO Auto-generated method stub
            for(int i=0; i<5; i++)
            {
                  int count = 1;
                  
                  for(int j=0; j<=i; j++)
                  {
                        System.out.print(count);
                        count++;
                  }
                  System.out.println();
            }
      }
}

 

Feel free to share and ask your doubt freely.
We are always ready to help.
Go through this

Press Ctrl+C to copy the following code.
"