Pascal Triangle Loop causes infinite loop

So I posted earlier yesterday about a problem with my pascal triangle not working and it was fixed, but now it's causing an infinite loop that I cannot manage to control with any of the if statements within int main(). My code isn't too complicated, but I am new to C++ so my debugging abilities aren't up to par.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>

using namespace std;

int nChooser = 0;
int nCr(int p, int p2);
int factorial(int i);
//void pascal(int row, int element);
int main()
{
    cout << "  Pascal Triangle" << endl;
    cout << "====================" << endl;
    cout << "1" << endl;
    int element = 1, row = 1;
    int totalElements = row+1;


    while(row <= 10)
    {
        if(element == 0)
        {
            element++;
            cout << 1 << " ";

        }
        else if(element == totalElements)
        {
            row++;
            //element = 0;
            cout << 1 << endl;
        }
        else
        {
            cout << nCr(row, element) << " " << endl;
        }
    }
    row++;

}

int nCr(int p, int p2)
{
    int subtract = p - p2;
    return factorial(p)/(factorial(p2)*factorial(subtract));
}

int factorial(int i)
{
    if (i <= 1)
        return 1;
    return (i * factorial(i - 1));
}
The proble with your code is that you don't update element.
You can replace
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
        if(element == 0)
        {
            element++;
            cout << 1 << " ";

        }
        else if(element == totalElements)
        {
            row++;
            //element = 0;
            cout << 1 << endl;
        }
        else
        {
            cout << nCr(row, element) << " " << endl;
        }

with something like it
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
        
while(element < row){
        if(element == 0)
        {
            element++;
            cout << 1 << " ";

        }
        else if(element == totalElements)
        {
            row++;
            //element = 0;
            cout << 1 << endl;
            break;
        }
        else
                cout << nCr(row, element++) << " " << endl;
}
Ohh thanks a bunch. That makes a lot more sense.
EDIT-It only runs once how can I make it run a set # of times, say 10,15,etc
Last edited on
do-while / while / for loops!

1
2
3
4
for( int i = 0; i < 10; ++i )
{
    /* all your current code */
}
Topic archived. No new replies allowed.