0

Please help with nested loops

I am trying to make a program that prints the pascals triangle on the console in C++. For that, I am using nested `while` loops. My code: ``` void pascalsTriangle(int num){ int a=1,b=1,n=1,r=1,out; while(n<=num){ cout << 1 << " "; // Just prints initial 1 while(r<=n){ out= combination(n,r); cout << out << " " ; r++; } cout << endl; n++; } ``` The `combination` function works perfectly and returns nCr data, so don't worry about it. This is my expected output (with num parameter =5 , for example) ``` 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 ``` However I am getting this: ``` 1 1 1 1 1 1 1 1 1 1 ``` What am I doing wrong? When I remove the outside loop and set n to like `5`, I do get the expected output, i.e: ``` 1 5 10 10 5 1 ``` What is it that I am doing wrong? Here's the full code for anyone looking: ``` #include <iostream> using namespace std; int factorial(int n){ int fact=1; int i=1; while(i<=n){ fact=fact*i; i++; } return fact; } int combination(int n, int r){ int a,b,c,comb; a = factorial(n); b = factorial(r); c = factorial(n-r); comb = (a/(b*c)); return comb; } void pascalsTriangle(int num){ int a=1,b=1,n=5,r=1,out; cout << 1 << " "; while(r<=n){ out= combination(n, r); cout << out << " " ; r++; } } int main() { cout << "Pascals triangle: " <<endl; int input; cin >> input; pascalsTriangle(input); return 0; } ```

4th Feb 2022, 2:55 PM
Aditya Aparadh
Aditya Aparadh - avatar
3 ответов
+ 3
Reset r=1 before the inner while loop.
4th Feb 2022, 4:02 PM
Brian
Brian - avatar
+ 3
Brian Yes I already got it. That was a really annoying problem. Still, Appreciate the help... I have posted the code for Pascal's Triangle on my profile, if you want to check out.. It's beautiful...
4th Feb 2022, 4:26 PM
Aditya Aparadh
Aditya Aparadh - avatar
+ 2
Aditya Aparadh very well done! Now the output is beautifully formatted. The code is readable and elegant. Good job!!
4th Feb 2022, 9:41 PM
Brian
Brian - avatar