Jul 29, 2024
for
, while
, do while
int n = 4; // number of rows
int m = 5; // number of columns
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
System.out.print("*"); // printing star
}
System.out.println(); // move to next line
}
i == 1
, i == n
, j == 1
, or j == m
.for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (i == 1 || i == n || j == 1 || j == m) {
System.out.print("*");
} else {
System.out.print(" "); // for hollow spaces
}
}
System.out.println();
}
int n = 4;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
n
stars, last with 1 star.for (int i = n; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
n-1
spaces + 1 star, etc.for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n - i; j++) {
System.out.print(" ");
}
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
int number = 1;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(number + " ");
number++;
}
System.out.println();
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
if ((i + j) % 2 == 0) {
System.out.print("1 ");
} else {
System.out.print("0 ");
}
}
System.out.println();
}