Pages

Sunday, July 23, 2017

C++ program to swap two given numbers.

This C++ program will swap the values of two given number using third temporary variable.

#include <iostream>
using namespace std;

int main()
{
    int num1, num2, temp;

    cout << "Enter number1:";
    cin >> num1;

    cout << "Enter number2:";
    cin >> num2;

    cout << "Numbers before swapping:";
    cout << "Number1 = " << num1 << ", Number2 = " << num2;

    temp = num1;
    num1 = num2;
    num2 = temp;

    cout << "\nNumbers after swapping:";
    cout << "Number1 = " << num1 << ", Number2 = " << num2;

    return 0;
}

Output of program

Enter number1:10
Enter number2:20
Numbers before swapping:Number1 = 10, Number2 = 20
Numbers after swapping:Number1 = 20, Number2 = 10



C++ program to swap two given numbers without use of temporary variable.

#include <iostream>
using namespace std;

int main()
{
    int num1, num2;

    cout << "Enter number1:";
    cin >> num1;

    cout << "Enter number2:";
    cin >> num2;

    cout << "Numbers before swapping:";
    cout << "Number1 = " << num1 << ", Number2 = " << num2;

    num1 = num1 + num2;
    num2 = num1 - num2;
    num1 = num1 - num2;

    cout << "\nNumbers after swapping: ";
    cout << "Number1 = " << num1 << ", Number2 = " << num2;

    return 0;
}

Output of program:

Enter number1:10
Enter number2:20
Numbers before swapping:Number1 = 10, Number2 = 20
Numbers after swapping :Number1 = 20, Number2 = 10


No comments:

Post a Comment