Practical 7
Call By value:
#include<iostream.h>
void swap(int x, int y);
int main ()
{
int a 100;
int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
swap(a, b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
return 0;
}
void swap(int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
return;
}
output:
Before swap, value of a :100
Before swap, value of b : 200
After swap, value of a :100
After swap, value of b : 200
Call by Reference:
#include<iostream.h>
void swap(int &x, int &y);
int main ()
{
int a = 100;
int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
swap(a, b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
return 0;
}
void swap(int &x, int &y) //no need to use pointer ! in c++ we can pass address like this
{
int temp;
temp = x;
x = y;
y = temp;
return;
}
output:
Before swap, value of a :100
Before swap, value of b : 200
After swap, value of a :200
After swap, value of b : 100
No comments:
Post a Comment