I'm new here, but it looks like an awesome place to get some help.

My assignment is to write a recursive function that determines the value of a unit of Pascal's triangle given the row and column, then use that to display the triangle with n number of rows. It's taken me quite a while to just understand how the Pascal's triangle works, much less code it. I don't totally understand the mathematical logic for it. I've finally coded it with an iterative loop, but I'm not sure I can figure it out recursively... or if I am supposed to... anyway, I've got my plain vanilla loop coded here.

#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;
}

If anybody can help or guide me, it'd be great.

If anybody can help or guide me, it'd be great.

Code looks fine to me, except that it doesn't have the right form. To do that you need to add some spaces.

tip: if you change this line: cout << x << " "; the answer will be kind of simple.

What is the logic behind the formula you have used in loop ..... you worked it out yourself or there is a reason behind it???/ I have an assignment and i have chosen this to implement, so preparing myself for the viva so please???

This is the code for the recursive version I've made:

#include <iostream>

long calc(int n, int r) {
     if ((n == 0) || (r == 0) || (n == r)) return 1;
     else return (calc(n-1,r-1) + calc(n-1,r));
}

int main() {
    printf("Enter a number = ");
    int num;
    scanf("%i", &num);
    for (int i = 0; i<=num; i++) {
        for (int j = num; j > i; j--) printf("   ");
        for (int k = 0; k <= i; k++) printf("%6d", calc(i,k));
        printf("\n");
    }
    return 0;
}

Yea shellexecutor yours one is right. I have tried a code also.

#include<stdio.h>
#include<conio.h>
int pascal(int,int);
void space(int,int);

int main()
{
	int n,i,j;
	printf("\nEnter the no. of rows  ");
	scanf("%d",&n);
	for(i=1;i<=n;i++)
	{
		space(n-i,3);
		for(j=1;j<=i;j++)
		{
			printf("%3d",pascal(i,j));
			space(1,3);
		}
		printf("\n");
	}
	getch();
	return 0;
}

int pascal(int row,int column)
{
	if(column==0)
		return 0;
	else if(row==1&&column==1)
		return 1;
	else if(column>row)
		return 0;
	else
		return (pascal(row-1,column-1)+pascal(row-1,column));
}

void space(int n,int mul)
{
	int i;
	n*=mul;
	for(i=0;i<n;i++)
		printf(" ");
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.