Q-16: Write a C/C++ program that swaps two numbers using:
(i) Call by value
(ii) Call by reference
    

Call by value - C


#include<stdio.h> void Swap(int a, int b); void main() { int a, b; printf("Enter the value of a: "); scanf("%d",&a); printf("Enter the value of b: "); scanf("%d",&b); system("cls"); printf("Before calling Swap() : a = %d & b = %d",a,b); Swap(a,b); printf("\n\nBut not Swapped inside main() : a = %d & b = %d",a,b); } void Swap(int a, int b) { int temp = a; a = b; b = temp; printf("\nSwapped Inside Swap() : a = %d & b = %d",a,b); }

OUTPUT

Enter the value of a:  5
Enter the value of b:  9

Before calling Swap()     :  a = 5   &   b = 9
Swapped Inside Swap() :  a = 9   &   b = 5

But not Swapped inside main() :  a = 5   &   b = 9
  

Call by reference - C


#include<stdio.h> void Swap(int *a, int *b); void main() { int a, b; printf("Enter the value of a: "); scanf("%d",&a); printf("Enter the value of b: "); scanf("%d",&b); system("cls"); printf("Before Swapping: a = %d & b = %d",a,b); Swap(&a,&b); printf("\nAfter Swapping : a = %d & b = %d",a,b); } void Swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; }

OUTPUT

Before Swapping:  a = 45   &   b = 20
After Swapping   :  a = 20   &   b = 45
  

Call by value - C++


#include<iostream> using namespace std; class Swapper { public: void Swap(int a, int b); }; void Swapper::Swap(int a, int b) { int temp = a; a = b; b = temp; cout<< "Swapped Inside Swap() : a = "<< a<< " & b = "<< b<< endl; } int main() { int a, b; Swapper object; cout<< "Enter the value of a: "; cin>> a; cout<< "Enter the value of b: "; cin>> b; system("cls"); cout<< "Before calling Swap() : a = "<< a<< " & b = "<< b<< endl; object.Swap(a,b); cout<< "\nBut not Swapped inside main() : a = "<< a<< " & b = "<< b<< endl; return 0; }

OUTPUT

Enter the value of a:  12
Enter the value of b:  56
  
Before calling Swap()     :  a = 12   &   b = 56
Swapped Inside Swap() :  a = 56   &   b = 12
  
But not Swapped inside main() :  a = 12   &   b = 56
  

Call by reference - C++


#include<iostream> using namespace std; class Swapper { public: void Swap(int *a, int *b); }; void Swapper::Swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } int main() { int a, b; Swapper object; cout<< "Enter the value of a: "; cin>> a; cout<< "Enter the value of b: "; cin>> b; system("cls"); cout<< "Before Swapping: a = "<< a<< " & b = "<< b<< endl; object.Swap(&a,&b); cout<< "After Swapping : a = "<< a<< " & b = "<< b<< endl; return 0; }

OUTPUT

Before Swapping:  a = 20  &  b = 60
After Swapping   :  a = 60  &  b = 20