C++ program to swap two integers using reference variable

 

C++ program to swap two integers using class, Object and reference variable

In this tutorial, we will Learn:

What is a reference variable?

Difference between Reference and Pointer Variable.

How to Create and use Reference Variable in C++ programs

Write a C++ program to swap two integers values and display the values before and after swapping using call by reference.

Definition of Reference variable in C++

A reference variable is just another name to an already existing variable.

Difference between Reference and Pointer Variable

Difference between Reference and Pointer Variable

How to Creating Reference Variable

The reference variable is created using the & symbol.

For example, let a is a variable and we can create a reference variable of a as x as follows,

int a =10;

int &x=a;

Here variable x is a reference variable for variable a. Both a and x are pointing at the same memory location. Hence if the value of a is changed then the value of x also changes automatically.

Video Tutorial:

Use of Reference

The reference variables are used to pass the parameter to the functions pass by reference.

Points to Remember

1. Reference variables should not be initilized with a constant value. For example int &a=100 is not allowed.

2. Never return the reference variable from a function as a memory address.

3. Avoid assigning the reference variables to the variables whose memory is dynamically allocated.

The following program demonstrates the C++ program to swap two integers values and display the values before and after swapping using call by reference.

 #include<iostream>
 using namespace std;
 void swap(int &x, int &y)
 {
     int temp;
     temp = x;
     x = y;
     y = temp;
 }
 int main()
 {
     int a, b;
     cout<<"Enter the value of a: ";
     cin>>a;
     cout<<"Enter the value of b: ";
     cin>>b;
     cout<<endl<<"Before swapping: ";
     cout<<"a= "<<a<<" and b= "<<b;
     swap(a, b); 
     cout<<endl<<"After swapping: "; 
     cout<<"a= "<<a<<" and b= "<<b;
 }

OUTPUT:

Enter the value of a: 10

Enter the value of b: 20

Before swapping: a= 10 and b= 20

After swapping: a= 20 and b= 10

Summary:

In this article, we understood the concept of reference variables and write a C++ program to swap two integers values and display the values before and after swapping using class, object, and call by reference (reference variable).

If you like the tutorial share it with your friends. Like the Facebook page for regular updates and YouTube channel for video tutorials.

Leave a Comment

Your email address will not be published. Required fields are marked *

Welcome to VTUPulse.com


Computer Graphics and Image Processing Mini Projects -> Click Here

Download Final Year Project -> Click Here

This will close in 12 seconds