Subscribe Now: standard

Friday, October 23, 2009

How To - Pascals triangle using loop - c++ code


hi
i had posted the code to generate Pascals triangle in c++ using arrays, but it can be done in a more easy way , using just 2 for loops.
And it is just 1/4 the amount of code.
Here is an easy logic in c++ to generate pascals triangle using for loops.
The part that has been marked in red is the code used to center align the triangle. I suggest that if you are getting confused you remove that part for better understanding of the Programs Logic.

please replace the () in red with < and> 
====================================================
 
int main()
{
  int n  , d  , l , k=0;
  cin >> n;
d = n;
k=n;
l = 0;
  for (int y = 0; y < n; y++)
  {
while(l
{
cout<<" ";
d = d-1;
};
if(d
{
k = k-1;
};
d = k;


    int c = 1;
    for (int x = 0; x <= y; x++)
    {
      cout << c << " ";
      c = c * (y - x) / (x + 1);
    }
    cout<<"\n";
  }
  cout<<"\n";
  return 0;
}

==================================================

thats it , for any further help you may mail me at blaise.crowly@gmail.com

Http://blaisemcrowly.co.cc
Blaise M Crowly

No comments:

Post a Comment