Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C++ สลับตัวเลข 3 ตัวแบบ Cyclic ด้วย Call by Reference

สลับค่า 3 ตัวแปรแบบ Cyclic (x→y, y→z, z→x) ผ่าน Pointer (Call by Reference)

โค้ดโปรแกรม

#include <iostream>
using namespace std;

void cyclicSwapping(int* x, int* y, int* z) {
    int temp = *y;
    *y = *x;
    *x = *z;
    *z = temp;
}

int main() {
    int x, y, z;
    cout << "Enter 3 numbers: ";
    cin >> x >> y >> z;
    
    cout << "Before swap: x=" << x << " y=" << y << " z=" << z << endl;
    cyclicSwapping(&x, &y, &z);
    cout << "After swap:  x=" << x << " y=" << y << " z=" << z << endl;
    return 0;
}

ผลลัพธ์

Enter 3 numbers: 2 5 7
Before swap: x=2 y=5 z=7
After swap:  x=7 y=2 z=5

การทำงานของ Cyclic Swap

// เริ่มต้น: x=2, y=5, z=7
temp = *y;    // temp = 5
*y = *x;      // y = 2
*x = *z;      // x = 7
*z = temp;    // z = 5
// ผลลัพธ์: x=7, y=2, z=5

C++ Modern (References)

void cyclicSwap(int& x, int& y, int& z) {
    int temp = y;
    y = x;
    x = z;
    z = temp;
}

// เรียก: cyclicSwap(x, y, z); // ไม่ต้อง &

ใช้ Reference (int&) แทน Pointer โค้ดอ่านง่ายกว่า และปลอดภัยกว่า (ไม่เป็น Null)