How we can write a program to get out put given below in c??

1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1

Recommended Answers

All 2 Replies

Sart here

int main()

   // put your code here


It's totally easy. Take a look:

#include <stdio.h>

int main(void)
    for (int i = 1; i <= 5; ++i) {
        for (int j = 1, x = 2 * i; j < x; ++j)
            printf("%.*s%d%s", j>1?0:2*(5-i),j>1?"":"\
                   ",j<=i?j:i-j%i,j<x-1?" ":"\n");


But seriously, you need a loop for the rows, a loop inside to handle the increment part, and another loop immediately after to handle the decrement part. I wouldn't recommend handling both the increment and decrement in a single loop (like above) as it complicates the algorithm unnecessarily.

You also don't need to make a pyramid yet, but I suspect that's going to be the next thing your teacher asks for. To handle that you need to print a decreasing number of spaces before printing out the numbers for each row. The spaces will start at half the length of a row and end at 0.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.