Ad

I've Got No Idea How To Write C-code About Pyramid

- 1 answer

I made this by an helper and I tried to unify the location of the sum of each row, but I don't know how to fix it. I think the part of printf("%2d", j) from inner for should be changed, but I have no idea for this.

for (i = 1; i <= s; i++)

{
    sumOfRow = 0;

    for (j = i; j <= s; j++)

    {
        printf("%2d", j);

        sumOfRow += j;
    }

    printf("\t\t%-5d\n", sumOfRow);

    sum += sumOfRow;

}
printf("Sum of all numbers is %d\n", sum);

getchar();

return 0;

}

Ad

Answer

#include <stdio.h>

int main()

{
    int s, i, j, sum = 0;

    // create new variable to store sum of single row
    int row_sum = 0;

    printf("Enter the size:");
    scanf("%d", &s);
    for (i = 1; i <= s; i++)
    {
        row_sum = 0; // reset sum for each row
        for (j = i; j <= s; j++)
        {
            printf("%2d ", j);
            row_sum += j; // add current number to row_sum
        }
        printf("\t%d\n", row_sum);
        sum += row_sum; // add current row_sum to total sum
    }
    printf("%d\n", sum);
    getchar();
    return 0;
}

EDIT

To add padding, you can use the following trick -

printf("%*s", paddingLength, "");

This will print an empty string that will take "paddingLength" characters.

For each value in a row, we have 3 chars, 2 for the value and one for space. So, add a padding of 3*i before printing row_sum.

#include <stdio.h>

int main()

{
    int s, i, j, sum = 0;

    int row_sum = 0;

    printf("Enter the size:");
    scanf("%d", &s);
    for (i = 1; i <= s; i++)
    {
        row_sum = 0;
        for (j = i; j <= s; j++)
        {
            printf("%2d ", j); // this will have fixed length of 3
            row_sum += j;
        }
        printf("\%*s%d\n", 3*i , "", row_sum); // print 3*i whitespace before row_sum
        sum += row_sum;
    }
    printf("%*s%d\n", 3*i, "", sum);
    getchar();
    return 0;
}

Output -

Enter the size:6
 1  2  3  4  5  6    21
 2  3  4  5  6       20
 3  4  5  6          18
 4  5  6             15
 5  6                11
 6                   6
                     91
Ad
source: stackoverflow.com
Ad