BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

C++ Program to Swap Two Numbers using Third variable

Last Updated: December 30, 2017 by Chaitanya Singh | Filed Under: C++ Programs

Here we will see a program to swap two numbers using a temporary third variable. The steps are as follows:
1. User is asked to enter the value of first and second number. The input values are stored in first(num1) and second(num2) variable.
2. Assigning the value of first variable to the third variable.
3. Assigning the value of second variable to the first variable.
4. Assigning the value of third variable to the second variable.

Example: Program to swap two numbers

#include <iostream>
using namespace std;

int main()
{
    int num1, num2, temp;
    cout<<"Enter 1st Number: "; 
    cin>>num1;
    cout<<"Enter 2nd Number: "; 
    cin>>num2;

    //displaying numbers before swapping
    cout<<"Before Swapping: First Number: "<<num1<<" Second Number: "<<num2;

    //swapping
    temp=num1;
    num1=num2;
    num2=temp;

    //displaying numbers after swapping
    cout<<"\nAfter Swapping: First Number: "<<num1<<" Second Number: "<<num2;
    return 0;
}

Output:
C++ Swapping Numbers

Top Related Articles:

  1. C++ Program to display Armstrong Numbers between 1 and 1000
  2. C++ Program to add two numbers
  3. C++ Program to find the Missing Number
  4. C++ Program to check whether the input number is Even or Odd
  5. C++ Program to Find largest element in an array

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

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

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap