Reputation: 5457
well I've got it how to construct the pascal triangle and the code below is flawless but...in this code i am making the 1 to appear in first row by creating a new for loop especially for it... is there a way to generate pascal triangle without using an exclusive for loop for the 1 to appear in first... any help is much appreciated :)
//pascal triangle with ncr function
#include <stdio.h>
#include <conio.h>
int ncr(int i,int j);
int main()
{
int i,j,v,n,f,s;
printf("Enter the number of rows required\n");
scanf("%d",&n);
f=n;
//this is what i am exclusively using for printing 1 in 1st row
for(;f>0;f--)
{
printf(" ");
}
printf("1\n");
//is there a way to generate the above 1 using only the below for loop
for(i=1;i<=n;i++)
{
for(s=n-i;s>0;s--)
{
printf(" ");
}
for(j=0;j<=i;j++)
{
v=ncr(i,j);
printf("%d ",v);
}
printf("\n");
}
}
int ncr(int i,int j)
{
int k;
float ans=1;
for(;j>=1;j--)
{
ans=((ans*i)/j);
i--;
}
k=ans;
return(k);
}
Upvotes: 0
Views: 1819
Reputation: 4465
If you look carefully, you'll notice that the ncr
function is defined inside the main
method. Move the implementation of ncr
outside of main
.
Also, noticed by @BLUEPIXY, your implementation of ncr
has an excess ;
:
int ncr(int i,int j); //<<right here
{
//...
EDIT Solution to second problem (see Pascal's Triangle on Wikipedia)
The "first" row of the triangle is actually the zeroth row. Your outer loop starts with i = 1
and therefore the "first" row contains 1C0
and 1C1
. The "first" or zeroth row should actually contain only 0C0
. New loop:
//notice how the i here has changed to 0
for(i=0;i<=n;i++)
{
for(s=n-i;s>0;s--)
{
printf(" ");
}
for(j=0;j<=i;j++)
{
v=ncr(i,j);
printf("%d ",v);
}
printf("\n");
}
Upvotes: 1