Title: Solving a Java Programming Challenge with Nested Loops
```java
public class NestedLoopsChallenge {
public static void main(String[] args) {
// Define the size of the pattern
int size = 5;
// Pattern 1: Printing a Square Pattern
System.out.println("Pattern 1: Square Pattern");
for (int i = 0; i < size; i ) {
for (int j = 0; j < size; j ) {
System.out.print("* ");
}
System.out.println();
}
System.out.println();
// Pattern 2: Printing a Right Triangle Pattern
System.out.println("Pattern 2: Right Triangle Pattern");
for (int i = 0; i < size; i ) {
for (int j = 0; j <= i; j ) {
System.out.print("* ");
}
System.out.println();
}
System.out.println();
// Pattern 3: Printing an Inverted Right Triangle Pattern
System.out.println("Pattern 3: Inverted Right Triangle Pattern");
for (int i = size; i > 0; i) {
for (int j = 0; j < i; j ) {
System.out.print("* ");
}
System.out.println();
}
System.out.println();
// Pattern 4: Printing a Pyramid Pattern
System.out.println("Pattern 4: Pyramid Pattern");
for (int i = 0; i < size; i ) {
for (int j = size i; j > 1; j) {
System.out.print(" ");
}
for (int j = 0; j <= i; j ) {
System.out.print("* ");
}
System.out.println();
}
}
}
```
This Java program demonstrates the use of nested loops to print various patterns. The `main` method contains four different patterns:
1.
Square Pattern
: Prints a square made of asterisks.2.
Right Triangle Pattern
: Prints a right triangle with the base increasing in size.3.
Inverted Right Triangle Pattern
: Prints an inverted right triangle with the base decreasing in size.4.
Pyramid Pattern
: Prints a pyramid with increasing width of asterisks.You can adjust the `size` variable to change the dimensions of the patterns. This program showcases the versatility of nested loops in creating different visual patterns in Java.
版权声明
本文仅代表作者观点,不代表百度立场。
本文系作者授权百度百家发表,未经许可,不得转载。