C程序打印金字塔图案
给定一个正整数 n。任务是按照以下示例中的说明打印金字塔图案。
例子:
Input : 2
Output :
1
22
1
Input : 3
Output :
1
22
333
22
1
Input : 5
Output :
1
22
333
4444
55555
4444
333
22
1
算法:
//Print All Pattern
printPattern(int N)
// Print upper pattern
/* 1
22
333
...
N...(N)times */
for i->1 to N
for j->1 to i
print i
print next line
// Print lower triangle
/* N-1....(N-1)times
...
333
22
1 */
for i->N-1 to 0
for j->i to 0
print i
print next line
C++
// C++ program to print the pyramid pattern
#include
using namespace std;
// Print the pattern upto n
void printPattern(int n)
{
// Printing upper part
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= i; j++)
cout << i;
cout << "\n";
}
// printing lower part
for (int i = n - 1; i > 0; i--)
{
for (int j = i; j > 0; j--)
cout << i;
cout << "\n";
}
}
// Driver Code
int main()
{
int n = 8;
printPattern(n);
return 0;
}
Java
// Java program to print the pyramid pattern
class GFG {
// Print the pattern upto n
static void printPattern(int n)
{
// Printing upper part
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++)
System.out.print(i);
System.out.print("\n");
}
// printing lower part
for (int i = n - 1; i > 0; i--) {
for (int j = i; j > 0; j--)
System.out.print(i);
System.out.print("\n");
}
}
// Driver code
public static void main(String arg[])
{
int n = 8;
printPattern(n);
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python program to print
# the pyramid pattern
# Print the pattern upto n
def printPattern(n):
# Printing upper part
for i in range(n+1):
for j in range(1,i+1):
print(i,end="")
print("")
# printing lower part
for i in range(n - 1,0,-1):
for j in range(i,0,-1):
print(i,end="")
print("")
# driver code
n = 8
printPattern(n)
# This code is contributed
# by Anant Agarwal.
C#] 0; $i--)
{
for ($j = $i; $j > 0; $j--)
echo $i;
echo "\n";
}
}
// Driver Code
$n = 8;
printPattern($n);
// This code is contributed by mits
?>
JavaScript
输出:
1
22
333
4444
55555
666666
7777777
88888888
7777777
666666
55555
4444
333
22
1