给定正整数 n,以沙漏形式打印数字模式。
示例:
输入:rows_no = 7
输出:
1 2 3 4 5 6 7
2 3 4 5 6 7
3 4 5 6 7
4 5 6 7
5 6 7
6 7
7
6 7
5 6 7
4 5 6 7
3 4 5 6 7
2 3 4 5 6 7
1 2 3 4 5 6 7
// Java code for hour glass
// pattern.
import java.io.*;
class GFG
{
// Function definition
static void pattern(int rows_no)
{
int i, j, k;
// for loop for printing
// upper half
for (i = 1; i <= rows_no; i++) {
// printing i spaces at
// the beginning of each row
for (k = 1; k < i; k++)
System.out.print(" ");
// printing i to rows value
// at the end of each row
for (j = i; j <= rows_no; j++)
System.out.print(j + " ");
System.out.println();
}
// for loop for printing lower half
for (i = rows_no - 1; i >= 1; i--)
{
// printing i spaces at the
// beginning of each row
for (k = 1; k < i; k++)
System.out.print(" ");
// printing i to rows value
// at the end of each row
for (j = i; j <= rows_no; j++)
System.out.print(j + " ");
System.out.println();
}
}
// Driver code
public static void main (String[] args)
{
// taking rows value from the user
int rows_no = 7;
pattern(rows_no);
}
}
// This code is contributed by vt_m.
输出 :
1 2 3 4 5 6 7
2 3 4 5 6 7
3 4 5 6 7
4 5 6 7
5 6 7
6 7
7
6 7
5 6 7
4 5 6 7
3 4 5 6 7
2 3 4 5 6 7
1 2 3 4 5 6 7
时间复杂度: O(rows_no*rows_no),其中rows_no是从用户获取的行值。
空间复杂度: O(1),因为我们不使用任何额外的空间。