Home > Programming > Back to Java Basics-star problems-1

Back to Java Basics-star problems-1

 1: package star;
 2: import java.util.Scanner;
 3: public class Main {
 4:     public static void main(String[] args) {
 5:         Scanner input=new Scanner(System.in);
 6:         System.out.print("Enter No\n");
 7:         int n=input.nextInt();
 8:
 9:         for(int b=0;b<n;b++){
 10:             for(int a=0;a<b+1;a++){
 11:                 System.out.print("*");
 12:             }
 13:             System.out.print("\n");
 14:         }
 15:     }
 16: }
 17:

output:

Enter No
5

*

**

***

****

*****

in this example for loop at line 9 responsible for line breaks while for loop at line 10 responsible for no of stars in a line.

to change this output into following pattern you need to do only a change in line 10 i.e change b+1 into n-b because we need to change only no of stars

for(int a=0;a<n-b;a++){

Enter No

5

*****

****

***

**

*

to change to following pattern we need to add 2 for-loop inside the line breaking for-loop one for add spaces and one for stars.we can create 1,3,5,7 pattern by a<2*b+1 condition.

 1: for(int b=0;b<n;b++){
 2:             for(int a=0;a<n-b;a++){
 3:                 System.out.print(" ");
 4:             }
 5:             for(int a=0;a<2*b+1;a++){
 6:                 System.out.print("*");
 7:             }
 8:             System.out.print("\n");
 9:         }

Enter No

4

*

***

*****

*******

to get following pattern need to add another line breaking for-loop after above one.inside line breaking for-loop we add space to move one character since there are n-1 lines

 1: for(int b=0;b<n-1;b++){
 2:             System.out.print(" ");
 3:             for(int a=0;a<b+1;a++){
 4:                 System.out.print(" ");
 5:             }
 6:             for(int a=0;a<2*(n-b-1)-1;a++){
 7:                 System.out.print("*");
 8:             }
 9:             System.out.print("\n");
 10:         }

Enter No

3

*

***

*****

***

*

Advertisements
Categories: Programming Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: