Archive for the ‘Functions’ Category

/* Program to print Pascal triangle */
/* Here nCr=n!/((n-r)!r!)=n*(n-1)*(n-2)………(n-r)/(1*2*3*………..(n-r)) */
#include<stdio.h>

long factorial(int);
void space(int);

main()
{
int i,j,rows;
printf(“\nNo of rows: “);
scanf(“%d”,&rows);
for(i=0;i<rows;i++)
{
space(3*(rows-i));
for(j=0;j<=i;j++)
{
printf(“%3d”,nCr(i,j)); // printing nCr value
space(3);
}
printf(“\n”);
}
}

int nCr(int n,int r) // calculating the value of nCr
{
int i,ncr=1;
for(i=1;i<=n-r;i++)
{
ncr=ncr*(n-i+1)/i;
}
return ncr;
}

void space(int n)
{
int i;
for(i=0;i<n;i++)
printf(” “);
}
Logic

nCr=nCr=n!/((n-r)!r!)=n*(n-1)*(n-2)………(n-r)/(1*2*3*………..(n-r))

Pascal Triangle can be represented with nCr as follows:

0C0

1C0    1C1

2C0     2C1     2C2

…………………………….

…………………………….


(adsbygoogle = window.adsbygoogle || []).push({});

Advertisements

/* Program to find the sum of series 1/1!+2/2!+3/3!+………. */

#include<stdio.h>

long int factorial(int);

main()
{
float sum=0;
int i,n;
printf(“\nEnter the limit: “);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
sum+=(float)i/factorial(i);
printf(“\nSum of the series: %f\n\n”,sum);
}

long int factorial(int n)
{
int i,fact=1;
for(i=1;i<=n;i++)
fact*=i;
return fact;
}

Square of N Numbers

Posted: February 12, 2010 in Functions
Tags:

/* Program to print square of n numbers */

#include<stdio.h>

void square(int);

main()
{
int n,i;
printf(“\nEnter n: “);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
square(i);
printf(“\n”);
}
printf(“\n”);
}

void square(int n)
{
printf(“%3d %5d”,n,n*n);
}

Number Triangle- Alligned

Posted: February 12, 2010 in Functions
Tags:

/* Program to print number triangle using function and adjusts space */

#include<stdio.h>

void numberTriangle(int);
void space(int);    /* to print required space*/

main()
{
int n;
printf(“\nEnter the no.of rows required: “);
scanf(“%d”,&n);
printf(“\nThe number triangle……….\n”);
numberTriangle(n);
}

void numberTriangle(int n)
{
int i,j;
for(i=1;i<=n;i++)
{
space(2*(n-i));
for(j=1;j<=i;j++)
printf(“%d “,j);
j-=2;
for(;j>0;j–)
printf(“%d “,j);
printf(“\n”);
}
printf(“\n”);
}

void space(int n)
{
int i;
for(i=0;i<n;i++)
printf(” “);
}

Number Triangle

Posted: February 12, 2010 in Functions
Tags:

/* Program to print number triangle  using function */

#include<stdio.h>
void numbertriangle(int);

main()
{
int n,i;
printf(“\nEnter no. of rows required: “);
scanf(“%d”,&n);
printf(“\nThe number triangle ……\n”);
numbertriangle(n);
}

void numbertriangle(int n)
{
int i,j;
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
printf(“%d  “,j);
printf(“\n”);
}
printf(“\n”);
}

/* Program to print multiplication table upto n */

#include<stdio.h>

void multiTable(int);

main()
{
int n,i;
printf(“\nEnter n: “);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
multiTable(i);
printf(“\n”);
}
printf(“\n”);
}

void multiTable(int n)
{
int i;
for(i=1;i<=12;i++)
printf(“%5d”,i*n);
}