Swap Two Numbers

Program to swap two numbers using a temporary variable

BeginnerTopic: Basic Programs
Back

C++ Swap Two Numbers Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
using namespace std;

int main() {
    int a, b, temp;
    
    cout << "Enter first number (a): ";
    cin >> a;
    
    cout << "Enter second number (b): ";
    cin >> b;
    
    cout << "Before swapping: a = " << a << ", b = " << b << endl;
    
    // Swapping logic
    temp = a;
    a = b;
    b = temp;
    
    cout << "After swapping: a = " << a << ", b = " << b << endl;
    
    return 0;
}
Output
Enter first number (a): 5
Enter second number (b): 10
Before swapping: a = 5, b = 10
After swapping: a = 10, b = 5

Understanding Swap Two Numbers

This program demonstrates variable swapping using a temporary variable. We use a third variable 'temp' to temporarily store the value of 'a' before overwriting it. This is the standard method for swapping two variables.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Table of Contents