Written by Sai Sameera Thota on April 9, 2013 in Java > Programming

Java Program to Print a Triangle

GET ALERTS:

Get our Latest updates delivered to your mailbox!

The program displays a triangle (using asterisks). The size of the triangle i.e, the number of lines in which the asterisks should be printed is taken as input to the program, 4 for loops are used in the program to display the triangle. For every iteration of the outer loop the the triangle advances to the next line. The inner loops are used to display the triangle.

Java Program to Print a Triangle

//programmingunit.com
import java.io.*;
class triangle 
{
	public static void main(String[] args) throws IOException
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		System.out.print("\nEnter the maximum number of lines : ");
		int n = Integer.parseInt(br.readLine());
		for (int i = 1; i <= n; i++)
        {
                  for (int j = 0; j < (n - i); j++)
                        System.out.print(" ");
                  for (int k = 1; k <= i; k++)
                        System.out.print("*");
                  for (int k = 1; k < i; k++)
                        System.out.print("*");
                  System.out.println();
         }
 
         System.out.println();
	}
}

Output:
Java Program to Print a Triangle

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: