Program C ++ untuk Menukar Nomor dalam Urutan Siklik Menggunakan Call by Reference

0
(0)

Tiga variabel yang dimasukkan oleh pengguna disimpan dalam variabel Sebuah, b dan c masing-masing.

Kemudian, variabel-variabel ini diteruskan ke fungsi cyclicSwap(). Alih-alih meneruskan variabel aktual, alamat variabel-variabel ini diteruskan.

Ketika variabel-variabel ini ditukar dalam urutan siklik dalam cyclicSwap() fungsi, variabel Sebuah, b dan c dalam main fungsi juga secara otomatis ditukar.

Contoh: Program untuk Menukar Elemen Menggunakan Panggilan dengan Referensi

#include
using namespace std;

void cyclicSwap(int *a, int *b, int *c);

int main()
{
    int a, b, c;

    cout << "Enter value of a, b and c respectively: ";
    cin >> a >> b >> c;

    cout << "Value before swapping: " << endl;
    cout << "a, b and c respectively are: " << a << ", " << b << ", " << c << endl;

    cyclicSwap(&a, &b, &c);

    cout << "Value after swapping numbers in cycle: " << endl;
    cout << "a, b and c respectively are: " << a << ", " << b << ", " << c << endl;

    return 0;
}

void cyclicSwap(int *a, int *b, int *c)
{
    int temp;
    temp = *b;
    *b = *a;
    *a = *c;
    *c = temp;
}

Keluaran

Enter value of a, b and c respectively: 1
2
3
Value before swapping: 
a=1
b=2
c=3
Value after swapping numbers in cycle:
a=3
b=1
c=2

Perhatikan bahwa kami belum mengembalikan nilai apa pun dari cyclicSwap() fungsi.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.