สามารถสลับตัวเลขสามตัวในลำดับวัฏจักรโดยส่งต่อไปยังฟังก์ชัน cyclicSwapping() โดยใช้การเรียกโดยการอ้างอิง ฟังก์ชันนี้จะสลับตัวเลขแบบวนรอบ
โปรแกรมการสลับหมายเลขตามลำดับวงจรโดยใช้การโทรโดยการอ้างอิงมีดังนี้ -
ตัวอย่าง
#include<iostream>
using namespace std;
void cyclicSwapping(int *x, int *y, int *z) {
int temp;
temp = *y;
*y = *x;
*x = *z;
*z = temp;
}
int main() {
int x, y, z;
cout << "Enter the values of 3 numbers: "<<endl;
cin >> x >> y >> z;
cout << "Number values before cyclic swapping..." << endl;
cout << "x = "<< x <<endl;
cout << "y = "<< y <<endl;
cout << "z = "<< z <<endl;
cyclicSwapping(&x, &y, &z);
cout << "Number values after cyclic swapping..." << endl;
cout << "x = "<< x <<endl;
cout << "y = "<< y <<endl;
cout << "z = "<< z <<endl;
return 0;
} ผลลัพธ์
ผลลัพธ์ของโปรแกรมข้างต้นเป็นดังนี้ −
Enter the values of 3 numbers: 2 5 7 Number values before cyclic swapping... x = 2 y = 5 z = 7 Number values after cyclic swapping... x = 7 y = 2 z = 5
ในโปรแกรมข้างต้น ฟังก์ชัน cyclicSwapping() จะสลับตัวเลขสามตัวตามลำดับแบบวนรอบโดยใช้การเรียกโดยการอ้างอิง ฟังก์ชันนี้ใช้อุณหภูมิตัวแปรในการทำเช่นนั้น ข้อมูลโค้ดสำหรับสิ่งนี้มีดังนี้ −
void cyclicSwapping(int *x, int *y, int *z) {
int temp;
temp = *y;
*y = *x;
*x = *z;
*z = temp;
} ในฟังก์ชัน main() ค่าของตัวเลข 3 ตัวจะถูกจัดเตรียมโดยผู้ใช้ จากนั้นค่าเหล่านี้จะแสดงก่อนที่จะทำการสลับ ฟังก์ชัน cyclicSwapping() ถูกเรียกเพื่อสลับตัวเลข จากนั้นค่าจะแสดงขึ้นหลังจากสลับกัน ด้านล่างนี้ −
cout << "Enter the values of 3 numbers: "<<endl; cin >> x >> y >> z; cout << "Number values before cyclic swapping..." << endl; cout << "x = "<< x <<endl; cout << "y = "<< y <<endl; cout << "z = "<< z <<endl; cyclicSwapping(&x, &y, &z); cout << "Number values after cyclic swapping..." << endl; cout << "x = "<< x <<endl; cout << "y = "<< y <<endl; cout << "z = "<< z <<endl;