Call by Value and Reference
Call by Value and Reference
Call by Value and Reference
Aim:
To demonstrate the use of call by value in C programming.
Algorithm:
1. Start
9. stop.
Flowchart:
Start
Read a and b
Swap (a,b)
Swap (int x, int y)
Temp = x
Stop
X=y
y = temp
Print x and y
Stop
Program:
#include<stdio.h>
int swap(int x,int y);
int main()
{
int a,b;
printf("Enter a and b:\n");
scanf("%d\n%d",&a,&b);
swap(a,b);
printf("\nCaller Value: a=%d, b=%d\n",a,b);
}
int swap(int x, int y)
{
int temp;
temp=x;
x=y;
y=temp;
printf("After swapping: x=%d, y=%d",x,y);
}
Output:
Conclusion:
In this program, we observed that even though the `swap` function is called with the arguments `a`
and `b`, the values of `a` and `b` remain unchanged after the function call. This confirms that C uses
call by value parameter passing mechanism, where copies of actual parameters are passed to the
function. Any changes made to the formal parameters inside the function do not affect the actual
parameters outside the function.
Call by reference
Aim:
To demonstrate the use of call by reference in C programming.
Algorithm:
1.Start
3. Inside the function, use pointers to access and modify the original values.
5.stop
Program:
#include<stdio.h>
int swap( int *x, int *y);
int main ()
{
int a,b ;
printf("Enter the value of a and b:\n");
scanf("%d\n%d",&a,&b);
Output:
Conclusion:
Call by reference provides an efficient method for passing arguments to functions, allowing direct
modification of original values without creating copies. This helps in optimizing memory usage and
enhancing code readability and maintainability.