Adsense 728 * 15

Search

Custom Search

Swap Two Numbers using Call by Value in C, C++

Write a C, C++ program to swap two numbers using call by value.

As compared to call by reference method the actual value is not changed when you pass parameters using call by value method.

What happens when you pass parameters using call by value method.

1.  In call by value method xerox copy of actual parameters is created and passed to the called function.

2. Any change made inside function will not affect the original value of variables inside calling function.

Swap Two Numbers using Call by Value in C


#include <stdio.h>

void swap (int a, int b) {
 
  int temp;
 
  temp = a;
  a = b;
  b = temp;
 
  printf("After swapping first number is %d and second number is %d", a ,b);
 
}

int main(void) {
 
  int first, second;
 
  printf("Enter two numbers : \n");
  scanf("%d %d",&first,&second);
 
  swap(first,second);
 
  /* Check whether actual parameters is changed after swapping. */
  
  printf(" \n After swap function called first number is %d and second number is %d", first ,second);
 
  return 0;
}



Output: 

Enter two numbers : 4   8

After swapping first number is 8 and second number is 4

After swap function called first number is 4 and second number is 8

Swap Two Numbers using Call by Value in C++

#include <iostream>
using namespace std;

void swap (int a, int b) {
 
    int temp;
    
    temp = a;
    a = b;
    b = temp;
    
    cout << "After swapping first and second number is " << a << b;
}

int main() {
 
   int first, second;
 
   cout <<"Enter two numbers \n";
   cin >> first >> second;
 
   swap(first,second);
 
   cout << " \n After swap function called first number is" << first << " and second number is "<< second;
 
   return 0;
}

No comments:

Post a Comment