This is the Java Program to Print * in Triangular Pattern.
Write a Java Program to Print * in Triangular Pattern, upto n lines.
The idea is to use nested loops.
Iterate the first loop from 1 to n. Print the required number of spaces using a nested loop and finally display the * using a nested loop.
Here is the source code of the Java Program to Print * in Triangular Pattern. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.
//Java Program to Print * in Triangular Pattern
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Pattern2 {
// Function to display the pattern
public static void main(String[] args) {
int i,j,k,n;
System.out.println("Enter the number of lines");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try{
n = Integer.parseInt(br.readLine());
}catch (Exception e){
System.out.println("An error occurred");
return;
}
System.out.println("The triangular pattern is");
int space = n-2;
for(i=1; i<=n; i++){
for(k=space;k>=0;k--){
System.out.print(" ");
}
space--;
for(j = 1; j<=i; j++){
System.out.print("* ");
}
System.out.println();
}
}
}
1. In function main(), firstly the number of lines n is entered.
2. The outer loop for(i=1; i<=n; i++) is used to print n lines.
3. The nested loop for(k=space;k>=0;k–), is used to print the required spaces.
4. The nested loop for(j = 1; j<=i; j++), is used to print the required number of *.
Time Complexity: O(n2).
Case 1 (Simple Test Case): Enter the number of lines 8 The triangular pattern is * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Sanfoundry Global Education & Learning Series – Java Programs..
- Apply for Computer Science Internship
- Practice Information Technology MCQs
- Check Java Books
- Practice BCA MCQs
- Check Programming Books