打印有趣图案的程序
解决有趣的图案问题可以增强对循环的理解。它们至关重要,因为它们有助于构建特定编程语言的坚实基础。各种类型的图案,包括基于数字、基于星号和基于字母的图案。在本文中,我们将讨论一些打印有趣星号图案的 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