Search code examples
cpascals-triangle

Pascal's triangle in C weird output


I'm trying to write a program to display Pascal's triangle up to a user-inputted number of levels. We aren't allowed to use the factorial method. My current code is this:

#include <stdio.h>

void trianglePrint(const int numLevels);

int main() {
  int numLevels;

  printf("Please enter how many levels of Pascal's Triangle you would 
  like to see: ");
  scanf("%d", &numLevels);

  trianglePrint(numLevels);


  return 0;
}

void trianglePrint(const int numLevels) {
  int pascalTriangle[28][28];
  int i, j;

  for (i = 0; i < numLevels; ++i) {
    for (j = 0; j <= i; ++j) {
      if (i == 0 || i == 1 || j == 0 || j == numLevels) {
        pascalTriangle[i][j] = 1;
        printf("%d ", pascalTriangle[i][j]);
      }
      else {
        pascalTriangle[i][j] = pascalTriangle[i - 1][j - 1] + 
        pascalTriangle[i - 1][j];
        printf("%d ", pascalTriangle[i][j]);
      }
    }
    printf("\n");
  }

}

We're only supposed to be able to go up to 28 levels, which is why I am using an array of size 28 in both dimensions.
This works fine for about 6 levels of the triangle, but for larger levels it gives really large integers. I assumed it was due to uninitialized arrays, but I'm not sure. Does anyone know where the error is?


Solution

  • If you change

    if (i == 0 || i == 1 || j == 0 || j == numLevels)
    

    to

    if (i == 0 || i == 1 || j == 0 || j == i)
    

    (thanks to Melpomene), then all accesses to your array end up on already intiailised members.

    That solves the strange numbers.

    Output:

    Please enter how many levels of Pascal's Triangle you would like to see: 6
    1
    1 1
    1 2 1
    1 3 3 1
    1 4 6 4 1
    1 5 10 10 5 1
    
    Process returned 0 (0x0)   execution time : 2.264 s
    Press any key to continue.
    

    Note:
    Also initialising an array is a wise precaution. You could initialise with values which help finding an error, instead of hiding it, e.g. 42.