Saturday 14 September 2013

functions part 4

Q Write a 'c' function to calculate the factorial of the number

(i) When the function  returns the value

#include<iostream.h>
#include<conio.h>
/*function prototype*/
int factorial(int);
void main( )
{
      int num,fact;

      clrscr();

      cout<<endl<<"Enter the number :";
      cin>>num;

      fact=factorial(num); /*function call*/

      cout<<endl<<"Factorial ="<<fact;

      getch();
}
/*function defintion */

int factorial(int num)
{
      int i,fact;

      fact=1;

      for(i=1;i<=num;i++)
            fact=fact*i;
     
      return fact;
}

(ii) When the function doesnot return the value

#include<iostream.h>
#include<conio.h>
/*function prototype */

void factorial(int);

void main()
{
      int num;

      clrscr( );

      cout<<endl<<"Enter the number :";
      cin>>num;

      factorial(num); /* function call*/

      getch();
}

/* function definition */

void factorial(int num)
{
      int i,fact;

      fact=1;

      for(i=1;i<=num;i++)
            fact=fact*i;
     
      cout<<endl<<"Factorial ="<<fact;
}

Q Write a 'c++' program using function to calculate the value
      of c.

            c =     n!
                   ----------
                    r!*(n-r)!
     

#include<iostream.h>
#include<conio.h>
/*function prototype*/
int factorial(int);
void main( )
{
      int n,r,c,factn,factr,factnr;

      clrscr();

      cout<<endl<<"Enter the value of n and r:";
      cin>>n>>r;

      /*calculate the factorial of n */

      factn=factorial(n);

      /*calculate the factorial of r */

      factr=factorial(r);

      /* calculate the factorail of n-r*/
     
      factnr=factorial(n-r);

      /*calculate the value of c */

      c=factn/(factr*factnr);

      cout<<endl<<"c="<<c;

      getch();
}
/*function definition */
int factorial(int num)
{
      int fact,i;
fact=1;

      for(i=1;i<=num;i++)
            fact=fact*i;

      return fact;
}

Q Write a 'C' function to calculate the x ^ y.

      x=5 y=3 x^ y=5^3=5*5*5=125

(i) When the function returns the value

(ii) When the function does not return the value .


Solution :


#include<iostream.h>
#include<conio.h>
/*function prototype*/
int power(int,int);
void main()
{
      int x,y,result;

      clrscr();

      cout<<endl<<"Enter the value of  x and y :";
      cin>>x>>y;

      result=power(x,y); /*function call*/

      cout<<"Result =" <<result;

      getch();
}

/*function defintion*/
int power(int x,int y)
{
      int i,result;

      result=1;

      for(i=1;i<=y;i++)
            result=result*x;

      return result;
}

           



No comments:

Post a Comment