Pyramid loop in c

Hi guys, I need help with this pyramid because I want the pattern to be:
1
121
12321
1234321

I don’t know which part of the loop to change. Plss help.

My output is:
pyramid help

here is the code:

#include <stdio.h>

int main() {

    int row, leftHalf, rightHalf;

    printf("\n");
    
    printf("Enter number of rows: ");
    scanf("%d", &row);

    printf("\n");

    for(int i=1; i<=row; i++) {
        //Empty space decrementing right triangle
        for(int j=i; j<=row; j++) {
            printf("  ");
        }
        //incrementing right triangle
        for(int k=1; k<=i; k++) {
            leftHalf = (i-k) + 1;
            printf("%d ", leftHalf);
        }
        //incrementing right triangle
        for(int l=1; l<=i-1; l++) {
            rightHalf = (i-l) + 1;
            printf("%d ", rightHalf);
        }
        printf("\n");
    }

    printf("\n");

    return 0;
}

You know, it would help if you included the output you are currently getting and also if there would be more meaningful variable-names in the code.

Because I have trouble following what the loops are doing. Or why there are 4.
I’d take one for the row, one for counting up, one for counting down. So that’s only 3, but somehow none of the loops is counting down.

1 Like

Ohhh I think I get your point. Wait let me try something.

Also sorry if my code is confusing. I will improve it next time.

Ahh, I still can’t find the solution. I’m so confused…

I already edited my post. I don’t know if it is much more understandable though.

There are a couple of tricks to use.
First off, call the input num_rows and have the first loop count up int row = 1.
This way the following code reference the term “row” for the row you are in - instead of the meaningless i.

Second, you are counting up from 1 to the current number of the row.
Third you count down from the current number of the row to 1.

You do not have to start a for-loop with 1. You don’t have to always increment (i++) but can also decrement (i–) in the loop.

1 Like

@Jagaya thank you. I finally got it. Really took me a lot of brain cells to answer this HAHA.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.