w3resource

Java: Generate a following *'s triangle


Reverse * Triangle

Write a Java program to generate the following * triangles.

Test Data
Input number of rows: 6

Pictorial Presentation:

Java conditional statement Exercises: Generate a following *'s triangle


Sample Solution:

Java Code:

import java.util.Scanner;
public class Exercise23 {
   public static void main(String args[]) 
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Input the number: ");
        int n = in.nextInt();
        for (int i = n; i > 0; i--) 
        {
            for (int spc = n - i; spc > 0; spc--) 
            {
                System.out.print(" ");
            }
            for (int j = 0; j < i; j++) 
            {
                System.out.print("*");
            }
            System.out.println();
        }
    }

}

Sample Output:

Input the number: 6                                                                                           
******                                                                                                       
 *****                                                                                                       
  ****                                                                                                       
   ***                                                                                                       
    **                                                                                                       
     *

Flowchart:

Flowchart: Java Conditional Statement Exercises - Generate a following *'s triangle



For more Practice: Solve these Related Problems:

  • Write a Java program to generate a reverse star triangle using a while loop.
  • Write a Java program to print a reverse star triangle pattern recursively.
  • Write a Java program to generate a reverse star triangle and then mirror it to create a symmetric design.
  • Write a Java program to produce a reverse triangle pattern using a user-specified symbol instead of an asterisk.

Go to:


PREV : Pascal's Triangle.
NEXT : Right-Angle Triangle with @ Symbols.

Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.