Call by value
Program :
#include<stdio.h>
void swp(int a,int b);
main()
{
int a,b,temp;
clrscr();
printf("enter the values of a and b\n");
scanf("%d%d",&a,&b);
printf("\nvalues before calling swap function\n a:%d, b:%d\n",a,b);
swp(a,b);
getch();
}
void swp( int num1,int num2)
{
int temp;
printf("\ninside the function swap before swaping\n");
printf("num1:%d, num2:%d\n",num1,num2);
temp=num1;
num1=num2;
num2=temp;
printf("\ninside the function swap after swaping\nnum1:%d, num2:%d\n",num1,num2);
printf("\nvalues after calling swap function\n a:%d, b:%d\n",num1,num2);
}
Output:
Enter the values of a and b
55
66
values before calling swap function
a:55, b:66
inside the function swap before swaping
num1:55, num2:66
inside the function swap after swaping
num1:66, num2:55
values after calling swap function
a:66, b:55
Enter the values of a and b
23
32
values before calling swap function
a:23, b:32
inside the function swap before swaping
num1:23, num2:32
inside the function swap after swaping
num1:32, num2:23
values after calling swap function
a:32, b:23
Call by reference:
Program:
#include<stdio.h>
void swap (int *a,int *b);
int main()
{
int a,b;
clrscr();
printf("Enter two numbers\n");
scanf("%d%d",&a,&b);
printf("Values before calling swap function\n");
printf("a:%d\t b:%d\n",a,b);
swap (&a,&b);
printf("Values after calling swap\n");
printf("a:%d\t b:%d\n",a,b);
getch();
}
void swap(int *pa,int *pb)
{
int temp,a,b;
printf("Inside the function swap before swapping\n");
printf("a:%d\t b:%d\n",*pa,*pb);
temp=*pa;
*pa=*pb;
*pb=temp;
printf("Inside the function swap after swapping\n");
printf("a:%d\t b:%d\n",*pa,*pb);
}
Output:
Enter two numbers
55
66
Values before calling swap function
a:55 b:66
Inside the function swap before swapping
a:55 b:66
Inside the function swap after swapping
a:66 b:55
Values after calling swap
a:66 b:55
Enter two numbers
22
33
Values before calling swap function
a:22 b:33
Inside the function swap before swapping
a:22 b:33
Inside the function swap after swapping
a:33 b:22
Values after calling swap
a:33 b:22
Thank Your Valuable Comment Tool to Insert codes in Comments : Convert My Code. Hide