Saturday, 30 August 2014

#2 Star Pattern Program in Java



In the program the following star pattern will be printed.



At first, we get the number where we want to print the star pattern from the user with the use of Scanner class and store that number in variable n then we make a loop which starts from 0 till n-1.

Inside of that loop there is another loop which is used for giving spaces from left side equal to the line number.

There is one more loop inside the first loop which takes values from 0 to n-1 and used for printing stars and then there is a println statement which is used for going to the next line. 

The program is shown below :

1:  import java.util.Scanner;  
2:    
3:  class StarPattern2  
4:  {  
5:       public static void main(String[] args)  
6:       {  
7:            int n;  
8:            System.out.println("Enter the number till you want a star pattern");  
9:            Scanner scan = new Scanner(System.in);  
10:            n = scan.nextInt();  
11:    
12:            label:     for(int i=0; i<n; i++)  
13:                 {  
14:                      for(int k=i; k>0; k--)  
15:                      {  
16:                           System.out.print(" ");  
17:                      }  
18:                      for(int j=0; j<n-i; j++)  
19:                      {  
20:                           System.out.print("*");  
21:                      }  
22:                      //for jump to next line  
23:                      System.out.println("");  
24:                 }  
25:       }  
26:  }  

Output :



2 comments :

  1. I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.

    python Training in Bangalore | python Training in Bangalore

    ReplyDelete