Print different patterns using java programs

    Patterns are the sequence of some shapes or numbers in some particular order. These can be created by  sequence of looping statements. Here, three programs are listed below.

part1 of these type of programs blog is linked here.

https://www.blogger.com/blog/post/edit/5251857942821229/5422820259444677124

#Java Program to print right angle triangle:

              This program creates a right angle triangle pattern.

Steps:

  • ·       Create a class sample1 with main() function.
  • ·       Get the number of lines to print the pattern.
  • ·       Using two for loops starts from value 1 to value n.
  • ·       Repeat until it reaches the ‘n’.
  • ·       Just print the * pattern.

class sample1

{

public static void main(String args[])

{

int no=7;

System.out.println("Printing right angle triangle pattern");

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

{

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

 {

  System.out.print("*");

 }

System.out.println();

}

}

}

While you run this code, this below output will shown….

C:\raji\blog>javac sample1.java

C:\raji\blog>java sample1

Printing right angle triangle pattern

*

**

***

****

*****

******

*******

This is the output.

 #Java Program to print reverse right angle triangle:

              This program has the following logic.

  • ·       It gets the number of lines to print as input.
  • ·       Create two loops to print the pattern. Using, from a number to 1, repeat the loop.
  • ·       Print the pattern.

class sample2

{

public static void main(String args[])

{

int no=7;

for(int i=no;i>=1;i--)

{

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

 {

  System.out.print("*");

 }

System.out.println();

}

}

}

The output is given below.

C:\raji\blog>javac sample2.java

C:\raji\blog>java sample2

*******

******

*****

****

***

**

*

#Java program to print a triangle:

  • ·       This program reads the number of lines to print the pattern.
  • ·       Using two loops, the space is printed first, pattern is printed after the space.
  • ·       This will be repeated until the number of lines.

public class triangle1 {

    public static void main(String[] args) {

        int no = 7;

        for (int i = 0; i < no; i++) {

            for (int j = no - i; j > 1; j--) {

                System.out.print(" ");

            }

            for (int j = 0; j <= i; j++) {

                System.out.print("* ");

            }

            System.out.println();

        }

}

}

Output:

C:\raji\blog>javac triangle1.java

C:\raji\blog>java triangle1

      *

     * *

    * * *

   * * * *

  * * * * *

 * * * * * *

* * * * * * *

These are the ways to print different patterns using java program. Enjoy coding!!!!

No comments:

Post a Comment