C++ | Interchanging(Swapping) two numbers using function

Introduction

This is program to interchange two numbers using function. The program is given below. The program can be extended by using more numbers and interchanging them. Go enjoy the program. Lets begin…..

Program to interchange() two numbers using function

#include<iostream.h>
#include<conio.h>
//function prototype
void change(int,int);
//main function
void main()
{
//clear the screen.
clrscr();
//declare variables as int.
int a,b;
//Input the numbers
cout<<“Enter the a.”<<endl;
cin>>a;
cout<<“Enter the b.”<<endl;
cin>>b;
//call function.
change(a,b);
//get character
getch();
}

//function
void change(int a,int b)
{
int c;
c=a;
a=b;
b=c;
cout<<“a = “<<a<<endl;
cout<<“b = “<<b<<endl;
}

Output

Enter the a.
1
Enter the b.
2
a = 2
b = 1

How does it work

  1. You enter the numbers.
  2. The function changes the position of numbers in variables.
  3. The output is printed.

Extending it

The program can be extended by using more numbers and changing there positions. Go extend it.

Explanation.

  1. Include ‘iostream.h’ and ‘conio.h’ files.
  2. Declare the function prototype.
  3. Add void main.
  4. Start program by first clearing the screen.
  5. Declare the variables as int (name them as you want.)
  6. Add the cout and cin of numbers.
  7. Call the function.
  8. Add the function definition outside the void main().

At the end

You learnt creating the C++ program of Interchanging or swapping two numbers using function. So now enjoy the program.

Please comment on the post and share it.
And like it if you liked.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s