برنامه ای برای تعویض اعداد با پیچیدگی Cyclic Order با فراخوانی با ارجاع آدرس Call by Reference
جمعه, ۱۶ مهر ۱۳۹۵، ۰۴:۳۰ ق.ظ
gameover.blog.ir
برنامه زیر سه عدد رو از کاربر می گیره و در متغیرهای a و b و c ذخیره می کنه.سپس این متغیرها رو به ورودی یک تابع ارسال می کنیم با استفاه از روش call by reference (در این روش آدرس جایی از حافظه که متغیر در اون ناحیه ذخیره شده رو داریم و هر تغییری روی متغیر ورودی هم تاثیر داره چون متغیر موقتی دستکاری نمیشه و پردازش روی حافظه اصلی متغیر انجام میشه)سپس مقدار اونها رو عوض می کنیم. روی کد فکر کنید:
#include<iostream>
using namespace std;
void cycle(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;
cycle(&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 cycle(int *a,int *b,int *c){
int temp;
temp=*b;
*b=*a;
*a=*c;
*c=temp;
}
Output
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
۹۵/۰۷/۱۶