I dette eksemplet byttes de tre numrene som er angitt av brukeren i syklisk rekkefølge ved bruk av samtale som referanse.
For å forstå dette eksemplet, bør du ha kunnskap om følgende C-programmeringsemner:
- C Pekere
- C Pass adresser og pekere
Program for å bytte element ved hjelp av referanse
#include void cyclicSwap(int *a, int *b, int *c); int main() ( int a, b, c; printf("Enter a, b and c respectively: "); scanf("%d %d %d", &a, &b, &c); printf("Value before swapping:"); printf("a = %d b = %d c = %d", a, b, c); cyclicSwap(&a, &b, &c); printf("Value after swapping:"); printf("a = %d b = %d c = %d", a, b, c); return 0; ) void cyclicSwap(int *n1, int *n2, int *n3) ( int temp; // swapping in cyclic order temp = *n2; *n2 = *n1; *n1 = *n3; *n3 = temp; )
Produksjon
Skriv inn henholdsvis a, b og c: 1 2 3 Verdi før bytte: a = 1 b = 2 c = 3 Verdi etter bytte: a = 3 b = 1 c = 2
Her lagres de tre tallene som er angitt av brukeren i henholdsvis variablene a, b og c. Adressene til disse numrene sendes til cyclicSwap()
funksjonen.
cyclicSwap(&a, &b, &c);
I funksjonsdefinisjonen av cyclicSwap()
har vi tildelt disse adressene til pekere.
cyclicSwap(int *n1, int *n2, int *n3) (… )
Når n1, n2 og n3 inni cyclicSwap()
endres, endres også verdiene til a, b og c inni main()
.
Merk: Den cyclicSwap()
funksjonen er ikke tilbake noe.