Sunday, April 22, 2012

Using C++ to make a Pascal Triangle

/*My friend asked me how to make a Pascal triangle in C++, I helped him but got a little debug problem,  but I fix it finally.*/
#include "stdafx.h"
#include <iostream>
using namespace std;
int xnumber(int input)
{
 int a=1;
 while( input>=2 )/*The number can't be 0, I dont know why, but I this is the number that fix the whole program*/
 {
  a = input * a ;
  //cout<<a<<" ";
  input--;
 }
 return a;
}
 int C(int n,int r)
 {
  int a = n-r;
  a = xnumber(n)/(xnumber(r) * xnumber(a));
  return a;
 }
 int _tmain(int argc, _TCHAR* argv[])
{
 int a,line=1,lineneeded;
 cout<<"Plz write down how many lines U need"<<endl;
 cin>>lineneeded;
 cout<<"1 "<<endl ;
while(line <= lineneeded)
 {
  a=1;
  cout<<"1 ";
  //cout<<line;
  while(a <= line)
  {
   cout<<C(line,a)<<" ";
   a++;
  }
  cout<<endl;
  line++;
 }
 cout<<endl;
 system("pause");
 return 0;
}
=====================================END===============================
The out put of this program is going to be a pascal triangle, but the input can't higher than 12.
out put:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
       .
       .
       .

No comments:

Post a Comment