This Java program generates a centered triangle pattern of numbers based on user input. The numbers in each row increase from 1 to the row index and then decrease back to 1. The pattern is aligned symmetrically using spaces for formatting.
For n = 5, the output is:
1
121
12321
1234321
123454321
package number_patterns;
import java.util.Scanner;
public class Triangle_Pattern
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Enter the size");
int n = s.nextInt();
for(int i = 1; i <= n; i++)
{
int num = 1;
for(int j = i; j <= n; j++)
{
System.out.print(" ");
}
for(int j = 1; j < i; j++)
{
System.out.print(num++);
}
for(int j = 1; j <= i; j++)
{
System.out.print(num--);
}
System.out.println();
}
}
}Scanner s = new Scanner(System.in);- The
Scannerclass is used to take user input. System.inreads the input from the console.s.nextInt()retrieves an integer value entered by the user.
int n = s.nextInt();nstores the number of rows for the triangle pattern, entered by the user.
for(int i = 1; i <= n; i++)- Controls the number of rows in the pattern.
- Runs from
1ton, wherenis the input number.
for(int j = i; j <= n; j++)
{
System.out.print(" ");
}- Creates leading spaces to align the pattern centrally.
- The number of spaces decreases as
iincreases.
int num = 1;
for(int j = 1; j < i; j++)
{
System.out.print(num++);
}- Prints numbers increasing from
1up toi-1. num++incrementsnumafter printing.
for(int j = 1; j <= i; j++)
{
System.out.print(num--);
}- Prints numbers decreasing from
numback to1. num--decrementsnumafter printing.
System.out.println();- Moves to the next line after completing one row.
- The program generates a triangle pattern of numbers with symmetry.
- Uses nested loops to control spaces, increasing numbers, and decreasing numbers.
- Demonstrates fundamental Java concepts such as loops, conditionals, and user input handling.
- Compile the program:
javac Triangle_Pattern.java - Run the program:
java Triangle_Pattern - Enter a number to define the pattern size.
- Observe the structured triangle pattern in the console.
git clone https://github.com/Ananthadatta02/Java-Trainagle_Patterns.git