Search code examples
cmultidimensional-arrayoutputpascals-triangle

C language wrong output...pascal triangle using 2d arrays


So this is my code for printing pascal triangle using 2d arrays but its not giving me the desired output and I cannot determine what's wrong with the logic/code.

#include <stdio.h>

int main()
{
    int num, rows, col, k;
    printf("Enter the number of rows of pascal triangle you want:");
    scanf("%d", &num);
    long a[100][100];

    for (rows = 0; rows < num; rows++)
    {
        for (col = 0; col < (num - rows - 1); col++)
            printf(" ");

        for (k = 0; k <= rows; k++)
        {
            if (k == 0 || k == rows)
            {
                a[rows][k] = 1;
                printf("%ld", a[rows][k]);
            }
            else
                a[rows][k] = (a[rows - 1][k - 1]) + (a[rows - 1][k]);
                printf("%ld", a[rows][k]);
        }
        printf("\n");
    }
    return 0;
}

Solution

  • You don't have curly braces around the statements after the else, so it looks like you'll double-printf() when the condition of the if-statement is true.

    I copied the source into codechef.com/ide and changed the io for num to be just assigned to 6 which produced the following output:

    Enter the number of rows of pascal triangle you want:     
         11
        1111
       11211
      113311
     1146411
    1151010511
    

    It looks like your close, but you want 1, 11, 121, 1331 etc right?

    Wraping the else case produced the following output:

     if (k == 0 || k == rows)
    
       {
            a[rows][k] = 1;
            printf("(%ld)", a[rows][k]);
        }
    
        else{// START OF BLOCK HERE
            a[rows][k] = (a[rows - 1][k - 1]) + (a[rows - 1][k]);
            printf("(%ld)", a[rows][k]);
        }//END OF BLOCK HERE, NOTE THAT IT INCLUDES THE PRINT IN THE ELSE CASE NOW
    
    OUTPUT:
        Enter the number of rows of pascal triangle you want:
             (1)
            (1)(1)
           (1)(2)(1)
          (1)(3)(3)(1)
         (1)(4)(6)(4)(1)
        (1)(5)(10)(10)(5)(1)
    

    But i added () to make it clearer to me. I also added a "/n" to the end of the first printf that asks for the value of num, so that the first line is on a new line.

    printf("Enter the number of rows of pascal triangle you want:\n");