HOW TO PRINT TIANGLE PATTERN IN JAVA PROGRAM||JAVA PROGRAM || Singhania coder...
To print a triangle pattern in Java, you can use nested loops to handle the spaces and the stars for each row. Below is a simple example of how to print a right-angled triangle pattern using stars (*
).
Example: Printing a Right-Angled Triangle Pattern
Here is a Java program to print a right-angled triangle pattern with stars:
public class TrianglePattern {
public static void main(String[] args) {
int rows = 5; // Number of rows in the triangle pattern
// Outer loop to handle the number of rows
for (int i = 1; i <= rows; i++) {
// Inner loop to print the stars
for (int j = 1; j <= i; j++) {
System.out.print("* "); // Print star followed by space
}
System.out.println(); // Move to the next line after each row
}
}
}
Output:
*
* *
* * *
* * * *
* * * * *
YOU CAN WATCH YOUTUBE VIDEO ALSO .....
Explanation:- The outer loop (
for (int i = 1; i <= rows; i++)
) runs for each row.
for (int i = 1; i <= rows; i++)
) runs for each row.- The inner loop (
for (int j = 1; j <= i; j++)
) runs and prints stars depending on the row number. For the first row, one star is printed, for the second row, two stars are printed, and so on. - After each row, the
println()
method is used to move to the next line.
Example: Printing an Inverted Triangle Pattern
Here is an example where the triangle is printed upside down:
public class InvertedTrianglePattern {
public static void main(String[] args) {
int rows = 5; // Number of rows
// Outer loop to handle the number of rows
for (int i = rows; i >= 1; i--) {
// Inner loop to print stars
for (int j = 1; j <= i; j++) {
System.out.print("* "); // Print star followed by space
}
System.out.println(); // Move to the next line after each row
}
}
}
Output:
* * * * *
* * * *
* * *
* *
*
SOCIAL MEDIA LINKS..
___________________________________________________
WEBSITE:-https://codingtutorialns.blogspot.com/
POST:-https://www.blogger.com/blog/post/edit/8132997316649709323/8773769701510879235
TELEGRAM CHENNAL:-https://t.me/coding_tutorial4
WHATSAPP CHANNEL:-https://whatsapp.com/channel/0029VaAK6PK2Jl8Gleg1Yj1x
----------------------------------------------------
SHOPING GROUPS
WHATSAPP CHANNEL:-https://whatsapp.com/channel/0029VafacN5LNSa1u1XJnj0J
TELEGRAM CHANNEL:-
https://t.me/WBonline_shopping
In this program, the outer loop runs in reverse, starting from rows
and going down to 1. This creates the effect of an inverted triangle.
Conclusion:
The key to creating triangle patterns in Java is using loops: an outer loop to control the rows and an inner loop to print stars or spaces for each row. You can modify the pattern as needed by changing the number of rows or the content being printed.