Google
 
Webcprogramming.com




An Affiliate of AIHorizon




Pascal's Triangle Challenge

#include <iostream>

int compute_pascal(int row, int position)
{
	if(position == 1)
	{
		return 1;
	}
	else if(position == row)
	{
		return 1;
	}
	else
	{
		return compute_pascal(row-1, position) + compute_pascal(row-1, position-1);
	}
}
int main()
{
	int row, position;
	cout<<"Please input a row and a position along the row: ";
	cin>>row>>position;
	if(row<position)
	{
		cout<<"Invalid entry.  Position must be less than or equal to row.";
		return 0;
	}
	else
	{
		cout<<"Value at row "<<row<<" and position "
<<position<<" is "<<compute_pascal(row, position);
	}
	return 0;
}

A nice recursive solution works because each number is computed from only two other numbers, each of which are computed by two other numbers, and the base case is always reached because the algorithm essentially climbs to the apex of the triangle (or to the sides), which will always be reached by the nature of the problem.

Download Source

-----
Interested in advertising with us?
Please read our privacy policy.
Copyright © 1997-2005 Cprogramming.com. All rights reserved.

Geodesy Designs