Wednesday, 13 May 2015

Calling Functions

How to Call a function:-  

-  In c++ programs, Functions can be invoked by two method:

- Call by Value.

- Call by reference method.

1:- Call by Value:-
                               In this call by method the value of actual parameter that are appearing in the function call are copied into the formal parameters which are appearing in function definition.

 The following Program illustrates this concept:-

Program:- Calculate of simple interest using a function.

Coding:-

                

#include<iostream.h>


int simpleinterest(float p, float r, float t);  // function prototyping
main()
{
float principal, rate , time;

cout<<" enter value of principal, rate and time";

cout<<"\n principal = "  ;
cin>>principal;

cout<<" \n rate = ";

cin>>rate;

cout<<"\n time = ";
cin>>time;

simpleinterest(principal,rate,time);    // function calling




}

int simpleinterest(float p, float r, float t)     // function definition

{
 float interest;

interest=(p*r*t)/100;

cout<<"\nSimple interest ="<<  interest;

}

Output:-
                  



2:- Call by Reference:- 
                                         A reference provides an alternative name for the variable, i.e the same variable's value can be used by two different names that is the original name and the alternative name. In this call by reference method, a reference method, a reference to the actual arguments in the calling program is passed. so their the called functions does not create its own copy of the original values but works with the original values with different name.

The following program illustrates this concept:

Program:- Write a program for swapping of two numbers using function call by reference method.

Coding:-




 #include<iostream.h>

         int swap(int & a,int & b);                                    // function prototype

              main()
 {
 int n1 , n2;

 cout<<"enter two values";


 cout<<"\n num 1=  ";
 cin>>n1;

 cout<<"\n num 2=  ";
 cin>>n2;

 cout<<"\n before swapping n1 = "<<n1;
 cout<<"\n before swapping n2 = "<< n2;

 swap(n1, n2);                                                  // function calling

 cout<<"\n after swapping n1 ="<<n1;

 cout<<"\n after swapping n2 "<<n2;


}

int swap(int & a,int & b)                                     //function definition

{
int temp =a;

a=b;

b=temp;

}

Output:- 

           


No comments:

Post a Comment