Pascal's Triangle using mainly functions in C++

user2977810 picture user2977810 · Nov 11, 2013 · Viewed 14.2k times · Source

I was trying to write a code that would display pascals triangle. Instead of displaying the result as : enter image description here

my result is displayed as
1
1 1
1 2 1
1 3 3 1

Please help me figure out how to modify it to be able to get the actual triangle. I cant use arrays and pointers since those aren't covered in my class yet. Here's my code:

#include "stdafx.h"
#include <iostream> 
using namespace std; 
void PascalsTriangle(int);

int main() 
{   
    int n;
    cout << "Enter the number of rows you would like to print for Pascal's Triangle: "; 
    cin >> n;
    PascalsTriangle(n);
    return 0; 
}

void PascalsTriangle (int n){
    int i,j,x;  
    for(i=0;i<n;i++) 
    { 
        x=1; 
        for(j=0;j<=i;j++) 
        { 
            cout << x << " "; 
            x = x * (i - j) / (j + 1); 
        } 
        cout << endl; 
    } 
}

Answer

Surabhil Sergy picture Surabhil Sergy · Nov 11, 2013

Try this :

#include <iostream>
using namespace std;
int main()
{
    int n,k,i,x;
    cout << "Enter a row number for Pascal's Triangle: ";
    cin >> n;
    for(i=0;i<=n;i++)
    {
        x=1;
        for(k=0;k<=i;k++)
        {        
            cout << x << " ";
            x = x * (i - k) / (k + 1);
        }
        cout << endl;
    }
    return 0;
}

EDITED:

#include <iostream>
using namespace std;
int main()
{
    int n,coef=1,space,i,j;
    cout<<"Enter number of rows: ";
    cin>>n;
    for(i=0;i<n;i++)
    {
        for(space=1;space<=n-i;space++)
        cout<<"  ";
        for(j=0;j<=i;j++)
        {
            if (j==0||i==0)
                coef=1;
            else
               coef=coef*(i-j+1)/j;
            cout<<"    "<<coef;
        }
        cout<<endl;
    }
}