In this tutorial you will learn about the C++ Programs to Swap two numbers and its application with practical example.
In this tutorial, we will learn to create a C++ program that will Swap two numbers in C++ programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C++ programming topics:
- Operators in C++ Programming.
- Basic Input and Output function in C++ Programming.
- Basic C++ programming.
Swapping of Numbers:-
In swapping we swap the data of two variables. In this program, we will use the third variable to swap the data of the first and second variables.
Let us understand with an example.
1 2 3 4 5 6 7 8 9 10 |
a = 100, b = 200 After line 1: flag = a flag = 100 After line 2: a = b a = 200 After line 3 : b = flag b = 100 |
Algorithm for the program:-
1 2 3 4 5 6 7 8 9 |
1. Declare the variables for the program. 2. Taking the input numbers from the user. 3. Swapping that number using third variable. 4. Print the Result. 5. End the program. |
C++ Programs to Swap two numbers
In every programming language, numbers play a very important role in a programming language. As we all know the c++ is a very powerful language. With the help of the c++ programming language, we can make many programs. We can perform many input-output operations using c++ programming. In today’s tutorial, we take the input numbers from the user. Then we will swap two Numbers with the help of the third variable in the c++ programming language.
With the help of this program, we can Swap two numbers.
Program to swap two Numbers:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include <iostream> using namespace std; int main() { //declaring the variables for the program for the program int first = 5; //first integer value for the program int second = 6; //second integer value for the program int flag; //temporary variable for the program //printing the numbers before the swapping cout << "Before swapping." << endl; cout << "a = " << first << ", b = " << second << endl; //Swapping the numbers flag = first; first = second; second = flag; //printing after swapping cout << "\nAfter swapping." << endl; cout << "a = " << first << ", b = " << second << endl; return 0; } |
Output:-
In the above program, we have first initialized the required variable.
- first= it will hold the integer value.
- second = it will hold the integer value.
- flag = it will hold the integer value.
Printing the numbers before the swapping of values.