c-plus-plus
  1. c-plus-plus-swap-number

C++ Program to Swap Numbers

Swapping two numbers in C++ can be done in a variety of ways, including using a temporary variable or using arithmetic operations. In this example, we will use a temporary variable to swap two numbers.

Syntax

void swapNumbers(int& a, int& b) {
    int temp = a;
    a = b;
    b = temp;
}

In the above syntax, we have defined a function called "swapNumbers" which takes in two integer parameters by reference. Inside the function, we have created a temporary variable called "temp" to hold the value of one of the numbers while we swap them.

Example

#include <iostream>
using namespace std;

void swapNumbers(int& a, int& b) {
    int temp = a;
    a = b;
    b = temp;
}

int main() {
    int x = 10;
    int y = 20;
    cout << "Before swapping: x = " << x << ", y = " << y << endl;
    swapNumbers(x, y);
    cout << "After swapping: x = " << x << ", y = " << y << endl;
    return 0;
}

Output

Before swapping: x = 10, y = 20
After swapping: x = 20, y = 10

Explanation

In the above example, we have two variables "x" and "y" that we want to swap. We call the "swapNumbers" function and pass in the two variables by reference. Inside the function, we create a temporary variable "temp" and assign the value of "a" to it. We then assign the value of "b" to "a" and finally assign "temp" (which holds the original value of "a") to "b".

Use

Swapping two numbers is a common task in programming, and it can be useful in many different situations. For example, if you are sorting an array of numbers, you may need to swap two elements in order to get them in the right order. Similarly, if you are working with matrices or vectors, you may need to swap rows or columns in order to perform certain operations.

Important Points

  • Swapping two numbers can be done in a variety of ways, including using a temporary variable or using arithmetic operations.
  • The easiest way to swap two numbers is to use a temporary variable.
  • Swapping two numbers is a common task in programming and can be useful in many different situations.

Summary

In summary, swapping two numbers in C++ is a simple task that can be accomplished using a temporary variable. We have provided a sample program that demonstrates how to swap two numbers, along with an explanation of how it works and some of its common uses.

Published on: