educative.io

Is my code wrong?

I am trying to write a pascal triangle. I finished the code and try to test on site but it showed output is wrong. I tried to do on VS and it worked. Is that a site problem or is there a problem with my code?

#include <iostream>

using namespace std;

void printPascalTr(int size) { //define your function

 

  int const size1 = size;

    int Pascal[size1][size1] = { {1},{1,1} };

    for (int i = 2; size1 > i; i++) {

        for (int j = 0; size1 > j; j++) {

            if (j == 0 ) {

                Pascal[i][j] = 1;

                cout << Pascal[i][j] << " ";

            }

            else {

                Pascal[i][j] = Pascal[i - 1][j - 1] + Pascal[i - 1][j];


            }

        }

        cout << "\n";

    }

    for (int h = 0; h < size1; h++)

    {

        for (int k = 0; k < size1; k++)

        {

            if (Pascal[h][k] == 0) {

            }

            else {

                cout << Pascal[h][k] <<" ";

            }

       

        }

        cout << "\n ";

    }

}

Course: Learn C++ from Scratch - Free Interactive Course
Lesson: Exercise 4: Pascal Triangle - Learn C++ from Scratch

1 Like

Hi @EmpeRa,

I fixed the problems in your code. Try the following code:

#include <iostream>
using namespace std;
void printPascalTr(int size) { //define your function
  int const size1 = size;
    int Pascal[size1][size1];
    for(int row=0; row<size1; row++)
        for(int col=0; col<size1; col++)
            Pascal[row][col]=0;

    Pascal[0][0]=1;
    Pascal[1][0]=1;
    Pascal[1][1]=1;

    for (int i = 2; size1 > i; i++) {
        Pascal[i][0]=1;
        for (int j = 1; i >= j; j++) {
          Pascal[i][j]=Pascal[i-1][j-1]+Pascal[i-1][j];
        }
    }
    for (int h = 0; h < size1; h++)
    {
        for (int k = 0; k <=h; k++)
        {
            cout <<Pascal[h][k]<<" ";
        }
        cout << "\n";
    }
}

In C++, the size of an array needs to be known at compile time. If the value of “size” is not known at compile time, the compiler will generate an error. Therefore, if you try to run the code with an unknown value of “size” on Visual Studio, it will result in an error. To fix this, replace “size” with a known value, such as a numeric constant, before running the code.

I hope this helps!