If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Here are a few examples of triangular patterns using loops in Java:
markdownCopy code*
**
***
****
*****
javaCopy codepublic class LeftAlignedTriangle {
public static void main(String[] args) {
int n = 5;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
markdownCopy code *
**
***
****
*****
javaCopy codepublic class RightAlignedTriangle {
public static void main(String[] args) {
int n = 5;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n - i; j++) {
System.out.print(" ");
}
for (int k = 1; k <= i; k++) {
System.out.print("*");
}
System.out.println();
}
}
}
markdownCopy code*****
****
***
**
*
javaCopy codepublic class InvertedLeftAlignedTriangle {
public static void main(String[] args) {
int n = 5;
for (int i = 5; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
markdownCopy code*****
****
***
**
*
javaCopy codepublic class InvertedRightAlignedTriangle {
public static void main(String[] args) {
int n = 5;
for (int i = 1; i <= n; i++) {
for (int j = 1; j < i; j++) {
System.out.print(" ");
}
for (int k = i; k <= n; k++) {
System.out.print("*");
}
System.out.println();
}
}
}
You can adjust the value of n
to control the size of the triangles. Experiment with different loop structures to create other interesting patterns as well.
Under Section 107 of the copyright act 1976, allowance is made for fair use for purposes such as criticism, comment, news reporting, scholarship, and research. Fair use is a use permitted by copyright statute that might otherwise be infringing. Non-profit, educational, or personal use tips the balance in favor of fair use.
Comments: 0