Write a  C++ Program to Swap Two Numbers

C++ Program to Swap Two Numbers with and without using varibles

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn C++ programming concepts. You can learn C++ language at your own speed and time. One can learn concepts of C++ language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

C++ Program to Swap Two Numbers with and without using varibles
C++ Program to Swap Two Numbers with and without using varibles

Write a  C++ Program to Swap Two Numbers

PROGRAM: C++ Program to Swap Two Numbers

/*C++ Program to Swap Two Numbers using temporary variable*/
#include <iostream>
using namespace std;

int main()
{
    int a = 5, b = 10, temp;

    cout << "Before swapping." << endl;
    cout << "a = " << a << ", b = " << b << endl;

    temp = a;
    a = b;
    b = temp;

    cout << "\nAfter swapping." << endl;
    cout << "a = " << a << ", b = " << b << endl;

    return 0;
}


/*C++ Program to Swap Two Numbers without using temporary variable*/

#include <iostream>
using namespace std;

int main()
{
    
    int a = 5, b = 10;

    cout << "Before swapping." << endl;
    cout << "a = " << a << ", b = " << b << endl;

    a = a + b;
    b = a - b;
    a = a - b;

    cout << "\nAfter swapping." << endl;
    cout << "a = " << a << ", b = " << b << endl;

    return 0;
}

Leave a Reply

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