This is the Java Program to Print 1,2,3,4…in Triangular Pattern.
Write a Java Program to print the values 1,2,3,4.. in a 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 values using a nested loop.
Here is the source code of the Java Program to Print 1,2,3,4…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 1,2,3,4...in Triangular Pattern
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Pattern1 {
// 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(j + " ");
}
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 values.
Time Complexity: O(n2).
Case 1 (Simple Test Case): Enter the number of lines 10 The triangular pattern is 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6 1 2 3 4 5 6 7 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 10
Sanfoundry Global Education & Learning Series – Java Programs..
- Practice BCA MCQs
- Practice Information Technology MCQs
- Apply for Java Internship
- Check Programming Books
- Check Java Books