I need to program a number pattern pyramid like that:
Here is my code:
#include<stdio.h>
int main()
{
int i, j, rows = 5;
for (i = 1; i <= 5; i )
{
for (j = 1; j <= i; j )
{
printf("%d ", j);
}
printf("\n");
}
for (i = 0; i <= 5; i )
{
for (j = 0; j <= i; j )
{
printf("%d ", j);
}
printf("\n");
}
}
Where am I doing wrong? I need to flip somehow the first triangle pattern and mix it with the second. Please help.
CodePudding user response:
Your pyramid is 6 levels high. The max number is 5. This is not a coincidence. There is a direct relationship.
If n
is 5
, you need to do something 6 times, from 0
to n
. There's a loop.
for (int i = 0; i <= n; i ) {
...
}
On each row you need to do print from i
to 0
, and then from 1
to i
. That's two loops.
for (int j = i; j > 0; j--) {
...
}
for (int j = 1; j <= i; j ) {
...
}
Of course, you also need to indent a number of spaces inversely related to i
, which is another loop.
for (int j = 0; j <= /* Fill in here for inverse relationship */; j ) {
...
}
CodePudding user response:
You have to include all 3 for loops in one for loop which runs 6 times. First you have to print spaces. Then first half of the triangle and then the other half. After that you have to print \n
.
#include<stdio.h>
int main()
{
int i, j,k,l;
for (i = 0; i <=5; i )
{
for (j = 5; j > i; j--)
{
printf(" ");
}
for (k = i; k >=0; k--)
{
printf("%d ", k);
}
for (l = 1; l <=i; l )
{
printf("%d ", l);
}
printf("\n");
}
}