列印有趣圖案的程式
解決有趣的圖案問題可以增強對迴圈的理解。它們至關重要,因為它們有助於構建特定程式語言的堅實基礎。各種型別的圖案,包括基於數字、基於星號和基於字母的圖案。在本文中,我們將討論一些列印有趣星號圖案的 Java 程式。
列印有趣圖案的程式
圖案 1
方法
宣告並初始化一個整數“n”,它指定行數和列數。
定義一個 for 迴圈,該迴圈將執行到“n”。在這個迴圈中定義一個 if-else 塊。
if 塊將在第 1 行和最後一行列印“n”次星號,else 塊將在第 2 行到第 4 行列印“n/2”次空格,並在中間列印一個星號。
示例
public class P1 {
public static void main(String[] args) {
int n = 5;
for(int i = 1; i <= n; i++) {
// till number of rows
if(i == 1 || i == n) {
for(int str = 1; str <= n; str++) {
System.out.print("*\t");
}
} else {
for(int spc = 1; spc <= n/2; spc++) {
System.out.print("\t");
}
for(int str = 1; str <= 1; str++){
System.out.print("*");
}
}
System.out.println();
// to move cursor to next line
}
}
}
輸出
* * * * * * * * * * * * *
圖案 2
方法
宣告並初始化一個整數“n”,它指定行數。
建立一個巢狀的 for 迴圈,外部迴圈將執行到“n”,內部 for 迴圈將執行到空格數並列印空格。列印後,我們將空格計數減 1。
再次使用另一個內部 for 迴圈,該迴圈將執行到星號數並列印星號。列印後,我們將星號計數加 2。
示例
public class P2 {
public static void main(String[] args) {
int n = 5;
int spc = n-1; // initial space count
int str = 1; // initial star count
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= spc; j++) { // spaces
System.out.print("\t");
}
spc--;
for(int k = 1; k <= str; k++) { // stars
System.out.print("*\t");
}
str += 2;
System.out.println();
}
}
}
輸出
* * * * * * * * * * * * * * * * * * * * * * * * *
圖案 3
方法
宣告並初始化一個整數“n”,它指定行數。
定義巢狀的 for 迴圈,外部迴圈將從“n”執行到 1,第一個內部迴圈將列印空格,第二個內部迴圈將列印星號。
示例
public class P3 {
public static void main(String[] args) {
int n=5;
for(int i = n; i >= 1; i--) {
for(int spc = n-i; spc >= 1; spc--){ // spaces
System.out.print("\t");
}
for(int str = 1; str <= i; str++){ // stars
System.out.print("*\t");
}
System.out.println();
}
}
}
輸出
* * * * * * * * * * * * * * *
圖案 4
方法
宣告並初始化一個整數“n”,它指定行數。
建立一個巢狀的 for 迴圈,外部迴圈將執行到“n”,第一個內部 for 迴圈將執行到空格數並列印空格。第二個內部迴圈將列印星號。
現在,使用一個 if-else 塊,if 塊將檢查行號是否小於 3。如果小於 3,則執行 if 塊以遞減空格計數並遞增星號計數。
如果行號大於 2,則執行 else 塊以遞增空格計數並遞減星號計數。
示例
public class P4 {
public static void main(String[] args) {
int n = 5;
int spc = 2;
// initial space count
int str = 1;
// initial star count
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= spc; j++) {
// spaces
System.out.print("\t");
}
for (int j = 1; j <= str; j++) {
// stars
System.out.print("*\t");
}
if ( i <= 2) {
spc--;
str += 2;
} else {
spc++;
str -= 2;
}
System.out.println();
}
}
}
輸出
* * * * * * * * * * * * *
圖案 5
方法
宣告並初始化一個整數“n”,它指定行數。
定義巢狀的 for 迴圈,外部迴圈將執行到“n”,第一個內部迴圈將列印空格,第二個內部迴圈將列印星號。
示例
public class P5 {
public static void main(String[] args) {
int n = 5;
for(int i = 1; i <= n; i++){
for(int spc = 1; spc <= n-i; spc++) {
System.out.print("\t");
}
for(int str = 1; str <= i; str++) {
System.out.print("*\t");
}
System.out.println();
}
}
}
輸出
* * * * * * * * * * * * * * *
結論
在本文中,我們討論了關於有趣星號圖案的問題。這些圖案解決方案將幫助您解碼圖案問題的邏輯,並使您能夠獨立解決其他圖案。
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP