Demonstrate call by value and call by reference using the UDF concept. [ Swap two values with
a function. Demonstrate Call by Value and
Call by Reference]
1. Call By Value
#include<stdio.h>
void swap(int a, int b);
void main(){
int x, y, a, b;
printf("Enter two values:");
scanf("%d %d",&x,&y);
swap(x,y); //call by value
//printf("\nAfter Swapping: x=%d y=%d",x,y);
}
void swap(int a, int b){
int temp;
temp = a;
a = b;
b = temp;
printf("\nAfter Swapping: x=%d y=%d",a,b);
}
2. Call By Reference
#include<stdio.h>
void swap(int *a, int *b);
void main(){
int x, y;
printf("Enter two values:");
scanf("%d%d",&x,&y);
swap(&x,&y); //call by Reference
printf("\nAfter Swapping: x=%d y=%d",x,y);
}
void swap(int *a,int *b){
int temp;
temp = *a;
*a = *b;
*b = temp;
}
No comments:
Post a Comment