มี 2 วิธีในการสลับค่าตัวแปร 2 ตัว: ใช้ตัวแปรชั่วคราว (temp) และไม่ใช้ตัวแปรชั่วคราว
วิธีที่ 1: ใช้ตัวแปรชั่วคราว (temp variable)
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 5, temp;
temp = a;
a = b;
b = temp;
cout << "Value of a is " << a << endl;
cout << "Value of b is " << b;
return 0;
}
ผลลัพธ์
Value of a is 5 Value of b is 10
ขั้นตอน: 1) เก็บ a ไว้ใน temp 2) กำหนด b ให้ a 3) กำหนด temp ให้ b
วิธีที่ 2: ไม่ใช้ตัวแปรชั่วคราว (Arithmetic Method)
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 5;
a = a + b; // a = 15
b = a - b; // b = 10
a = a - b; // a = 5
cout << "Value of a is " << a << endl;
cout << "Value of b is " << b;
return 0;
}
ผลลัพธ์
Value of a is 5 Value of b is 10
ใช้หลักการคณิตศาสตร์: บวกทั้งคู่เก็บไว้ที่ a แล้วลบย้อนกลับเพื่อแยกค่าเดิมออกมา (ควรระวัง overflow สำหรับตัวเลขใหญ่)