Sunday, 22 June 2014

Pascal tringle in c++

The purpose of my blog page is to help you peoples in c++ by sharing codes of different algorithms .

As it is my first post so I start with the code of making pascal triangle.


Pascal triangle code

------------------------------------------------------------------------------------------------------------

// danyal siddiqui
// pascal triangle



#include <iostream>
#include <iomanip>

using namespace std;

void printPascal(int n);
int main ()
{
int num;
cout<<"Enter the  value of the size fo pascal triangle you want to make :";
cin>>num;
printPascal(num);
cout<<endl<<endl;
return 0;
}

void printPascal(int n)
{
int ** ptrToPtr=new int* [n];
for(int i=0;i<n;i++)
{
ptrToPtr[i]=new int [i+1]; // To made the respective arrays of pointer arrays
}

// this nested loop fill 1 & 0 to fill 1 in the last row and first column
for(int i=0;i<n;i++)
{
for(int j=0;j<i+1;j++)
{
if(j==0||i==n-1 )
ptrToPtr[i][j]=1;
else
ptrToPtr[i][j]=0;
}
}


// this loop is to fill the pascal from bottom

for(int i=n-2/* i is intialize from second last row*/,a=n-1;i>=0;i--,a--)
{
for(int j=1;j<a;j++)
{
ptrToPtr[i][j]=ptrToPtr[i][j-1]+ptrToPtr[i+1][j];
}
}

for(int i=0;i<n;i++) // this loop is to diplay the pascal triangle
{
for(int j=0;j<i+1;j++)
{
cout<<left<<setw(3)<<ptrToPtr[i][j];
}
cout<<endl;
}

// now to delete the memory generated by new

for(int i=0;i<n;i++)
{
delete [] ptrToPtr[i];
ptrToPtr[i]=0; // avoid to make it the dangling pointer
}
delete [] ptrToPtr;
ptrToPtr=0;
}

------------------------------------------------------------------------------------------------------------

Output :




This code is for the beginners you would also modify it my using different data structures and recursion  and  in my next posts i will discuss about the different data structures and also different concepts of object oriented programming.


    

0 comments:

Post a Comment