Call by Value: – In this method the values of the actual parameters (appearing in the
function call) are copied into the formal parameters (appearing in the function definition), i.e., the
function creates its own copy of argument values and operates on them.
The following program illustrates this concept :-
#include<iostream.h>
#include<conio.h>
#include<math.h> //for pow()function
Void main()
{
Float principal, rate, time; //local variables
Void calculateInterest (float, float, float); //function prototype
clrscr();
Cout<<”\nEnter the following values:\n”;
Cout<<”\nPrincipal:”;
Cin>>principal;
Cout<<”\nRate of interest:”;
Cin>>rate;
Cout<<”\nTime period (in yeaers) :”;
Cin>>time;
calculateInterest (principal, rate, time); //function call
Getch ();
}
Void calculateInterest (float p, float r, float t)
{
Float interest; //local variable
Interest = p* (pow((1+r/100.0),t))-p;
Cout<<”\nCompound interest is : “<<interest;
}
Call by Reference: – A reference provides an alias – an alternate name – for the
variable, i.e., the same variable’s value can be used by two different names : the original name
and the alias name.
In call by reference method, a reference to the actual arguments(s) in the calling program is
passed (only variables). So the called function does not create its own copy of original value(s)
but works with the original value(s) with different name. Any change in the original data in the
called function gets reflected back to the calling function.
It is useful when you want to change the original variables in the calling function by the called
function.
//Swapping of two numbers using function call by reference
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num1,num2;
void swap (int &, int &); //function prototype
cin>>num1>>num2;
cout<<”\nBefore swapping:\nNum1: “<<num1;
cout<<endl<<”num2: “<<num2;
swapNumbers(num1,num2); //function call
cout<<”\n\nAfter swapping : \Num1: “<<num1;
cout<<endl<<”num2: “<<num2;
getch();
}
void swapNumbers (int & a, int & b)
{
Int temp=a;
a=b;
b=temp;
}
I genuinely treasure your work, Great post.
Thank you Lyndia.