Загрузка...

C++ Program to Swap Two Numbers Without a Temporary Variable #shorts

In this C++ program, we demonstrate how to swap the values of two variables without using any third variable. The program takes two integer variables, `a` and `b`, and swaps their values using a technique that relies solely on arithmetic operations.

Here's a breakdown of how the program works:

1. Two integer variables, `a` and `b`, are initialized with values: `a` is set to 30, and `b` is set to 68.

2. To swap the values of `a` and `b` without using a third variable, the program employs three arithmetic operations:
- `a += b`: This statement adds the value of `b` to `a`, effectively storing the sum of `a` and `b` in `a`.
- `b = a - b`: Here, `b` is updated by subtracting the original value of `b` (which is now stored in `a`) from the new `a`. This operation effectively assigns the original value of `a` to `b`.
- `a -= b`: Finally, this statement subtracts the updated `b` value from the updated `a` value, effectively assigning the original value of `b` to `a`.

3. After performing these arithmetic operations, the values of `a` and `b` have been swapped.

4. The program then outputs the swapped values of `a` and `b` to the console, demonstrating that the swap operation has been successfully executed.

Видео C++ Program to Swap Two Numbers Without a Temporary Variable #shorts канала CodeGeek
Яндекс.Метрика
Все заметки Новая заметка Страницу в заметки
Страницу в закладки Мои закладки
На информационно-развлекательном портале SALDA.WS применяются cookie-файлы. Нажимая кнопку Принять, вы подтверждаете свое согласие на их использование.
О CookiesНапомнить позжеПринять