To write a C++ program to swap the given numbers by call by value & address.




ALGORITHM:
Step 1: Start the program.
Step 2: Declare the variables and create the function with normal and pointer variables.
Step 3: Call the appropriate functions.
Step 4: Swap the values and print it.
Step 5: Stop the program.

PROGRAM:
#include<iostream.h>
#include<conio.h>
void swap(int x,int y);
void swap(int*x,int*y);
void main()
{
int a,b;
clrscr();
a=10;
b=20;
cout<<"In main function:\n";
cout<<"a: "<<a<<endl;
cout<<"b: "<<b<<endl;
swap(a,b); //swapping with default arguments
cout<<"In main function:\n";
cout<<"a: "<<a<<endl;
cout<<"b: "<<b<<endl;
swap(&a,&b);//swapping with default arguments
cout<<"In main function:\n";
cout<<"a: "<<a<<endl;
cout<<"b: "<<b<<endl;
getch();
}
void swap(int x ,int y)
{
x=x+y;
y=x-y;
x=x-y;
cout<<endl<<"\t"<<"CALLING FUNCTION 1 "<<endl;
cout<<endl<<"after swapping a is: "<<x<<endl;
cout<<endl<<"after swapping b is: "<<y<<endl;
}
void swap(int *x ,int *y)
{
*x=*x+*y;
*y=*x-*y;
*x=*x-*y;
cout<<endl<<"\t"<<"CALLING FUNCTION 2 "<<endl;
cout<<endl<<" after swapping a is: "<<*x<<endl;
cout<<endl<<" after swapping b is: "<<*y<<endl;
}





OUTPUT:
In main function:
a: 10
b: 20
CALLING FUNCTION 1
after swapping a is: 20
after swapping b is: 10
In main function:
a: 10
b: 20
CALLING FUNCTION 2
after swapping a is: 20
after swapping b is: 10
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: