C/c++

Kei Hâm

Legend of Zelda
có bác nào chỉ cho em bài này với noon wá suy nghĩ không ra
viết chương trình nhập vào n và in ra tam giác pascal tương ứng
ví dụ nhập vào 4 thì xuất ra màn hình như sao
1 1
1 2 1
1 3 3 1
1 4 6 4 1
........
ai có thể chỉ cho em bài này với thanks
 
#include <stdio.h>

int** InitializePascalMatrix( int n, int& p_nRows, int &p_nColumns );
void Print( int** p_ppMatrix, int p_nRows, int p_nColumns );

////////////////////////////////////////////////////////////////////////////////
// Function: InitializePascalMatrix
//
// Initliaze the pascal matrix
// Arguments:
// IN int n - numb of items in the matrix
// OUT int* p_nRows - numb of rows of the matrix
// OUT int* p_nColumns - numb of columns of the matrix
// Remarks:
//
// The return buffer was allocated with new, free its memory with delete
// Author:
// [email protected]
////////////////////////////////////////////////////////////////////////////////

int** InitializePascalMatrix( int n, int& p_nRows, int &p_nColumns )
{
int i, j;
p_nRows = n;
p_nColumns = n+1;

//-------------------------------------------------------
// Allocate memory for the matrix buffer
//-------------------------------------------------------

int** ppTemp = new int*[p_nRows];
for (i=0; i<p_nRows; ++i)
{
ppTemp = new int[p_nColumns];
}
//-------------------------------------------------------

//-------------------------------------------------------
// Zero memory of the buffer
//-------------------------------------------------------

for (i=0; i<p_nRows; ++i)
{
for (j=0; j<p_nColumns; ++j)
{
ppTemp[j] = 0;
}
}
//-------------------------------------------------------


//-------------------------------------------------------
// Set left most bit and right most bit to 1
//-------------------------------------------------------

for (i=0; i<p_nRows; ++i)
{
ppTemp[0] = 1;
ppTemp[i+1] = 1;
}
//-------------------------------------------------------


//-------------------------------------------------------
// Calculate value for other bit
//-------------------------------------------------------

for (i=0; i<p_nRows; ++i)
{
for (j=0; j<p_nColumns; ++j)
{
if (j-1 >= 0 && i-1 >= 0)
{
ppTemp[j] = ppTemp[i-1][j] + ppTemp[i-1][j-1];
}
}
}
//-------------------------------------------------------

return ppTemp;
}


void Print( int** p_ppMatrix, int p_nRows, int p_nColumns )
{
for (int i=0; i<p_nRows; ++i)
{
for (int j=0; j<p_nColumns; ++j)
{
if (p_ppMatrix[j] != 0)
printf( "%5d", p_ppMatrix[j] );
}
printf( "\n" );
}
}

void main()
{
int nRows = 0, nColumns = 0;
int nItems = 10;
int **ppPascalMatrix = InitializePascalMatrix( nItems, nRows, nColumns );
Print( ppPascalMatrix, nRows, nColumns );

delete []ppPascalMatrix;
}
 
Back
Top