مبانی برنامهسازی با c++ جلسه سوم

147
Ali Shakiba – http://shakiba.id.ir

Upload: lucky

Post on 22-Feb-2016

96 views

Category:

Documents


1 download

DESCRIPTION

مبانی برنامه‌سازی با C++ جلسه سوم. علی شکیبا [email protected] فروردین 1392. مباحث این جلسه. حلقه‌ها، توابع. یادآوری. یادآوری. قبل از نوشتن هر برنامه‌ای، صورت مساله را به درستی درک کنید، یک روش برای حل آن مساله ارائه کنید. در هنگام نوشتن برنامه، - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

Page 2: مبانی برنامهسازی با C++ جلسه سوم

مبانی برنامه سازی باC++

جلسه سوم علی شکیبا[email protected]

1392فروردین

Page 3: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

مباحث این جلسهحلقه ها،•توابع.•

Page 4: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

یادآوری

Page 5: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

5

یادآوریقبل از نوشتن هر برنامه ای،•

صورت مساله را به درستی درک کنید،–یک روش برای حل آن مساله ارائه کنید.–

در هنگام نوشتن برنامه،•درک روشنی از ساختارهای برنامه نویسی داشته –

باشید،مانند حلقه ها، شرط ها، توابع و مانند این،•

از الگوهای برنامه نویسی صحیح استفاده کنید،–زبان برنامه نویسی متناسب با مساله خود را –

انتخاب کنید.•

Page 6: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

6

الگوریتم هایک برنامه، برای محاسبه پاسخ یک مساله،•

دنباله ای از دستورات را اجرا می کند.–الگوریتم رویه ای است برای تعیین•

وظایفی که باید برای حل مساله انجام شوند،–ترتیب انجام آن وظایف،–

مثال، دستور پخت یک کیک خامه ای خوشمزه هجده •طبقه!

کنترل جریان برنامه•تعیین ترتیبی که دستورات برنامه اجرا می شوند.–

Page 7: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

7

شبه کدشبه کد•

زبانی مصنوعی و غیر رسمی برای توصیف –الگوریتم ها است،

شبیه به زبان های روزمره است،–نمی توانند توسط یک کامپیوتر اجرا شوند،•

مهم ترین کاربرد آن، امکان فکر کردن درباره –ساختار برنامه است، چرا که:

تبدیل آن به کد برنامه نویسی ساده است،•شبه کد می تواند تنها شامل دستورات اجرایی باشد.–

Page 8: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

8

متغیرمتغیر •

مکانی از حافظه که می توان داده )ها( را در آن –ذخیره نمود،

++ باید دارای نام و نوع داده Cتمام متغیرها در –باشند،

نوع داده قبل از نام متغیر می آید،–انواع داده معمول–

(،intعدد صحیح )•(،charکاراکتر )•(،doubleممیز شناور با دقت مضاعف )•

می توان چندین متغیر از یک نوع را با یک دستور –مشخص نمود.

int test;double grade;char firstChar;

int test1, test2, numberOfPCs;

Page 9: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

9

++Cانواع داده ها در

Page 10: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

10

++ )ادامه(Cانواع داده ها در

Page 11: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

11

( )عملگر Assignmentانتساب ))=

مقدار دهی اولیه در هنگام تعریف متغیرها،•اگر این کار را انجام ندهید، مقدار اولیه متغیر نامشخص –

است و می تواند هر مقداری باشد!عادت خوب برنامه نویسی، مقداردهی اولیه همه متغیرها –

در هنگام تعریف است.int myValue = 0;

انتساب در حین اجرا،•مقادیر سمت راست و سمت چپ–

مقادیر سمت چپ در یک انتساب باید شناسه یک متغیر باشند،•مقادیر سمت راست در یک انتساب می توانند هر عبارتی باشند،•مثال:•

distance = rate * time;"distanceمقدار سمت چپ: "

" rate * timeمقدار سمت راست: "

Page 12: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

12

مبان برهایی برای عملگر انتساب

Page 13: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

13

ثوابتقالب کلی تعریف ثوابت•

const نوع داده NAME_OF_VAR; مقدار = :مثال•

const int NUMBER_OF_STUDENTS = 24;در هر کجای برنامه، می توان از این ثابت با نوشتن –

نامش استفاده کرد،مقدار ثابت در طول برنامه، پس از تعریف؛ غیر –

قابل تغییر است!

Page 14: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

14

دقت محاسبات ریاضیدقت محاسبات ریاضی•

یک اصل مهم در برنامه نویسی است که باید –همواره در نظر گرفته شود،

ممکن است محاسبه عبارات آنگونه که شما انتظار •دارید، پیش نروند!

دقت محاسبات توسط عملگر محاسباتی با –بیشترین اولویت مشخص می شود!

عدم دقت به این مورد، متاسفانه یکی از –++ Cمعمول ترین خطاها در بین برنامه نویسان

است!

Page 15: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

15

مثال هایی از محاسبات ریاض5ی ++Cدر

مثال•– 17 / 5

هر دو عملوند صحیح هستند!•در نتیجه تقسیم صحیح انجام شده است!•

– 17.0 / 5یکی از عملوندها، ممیز شناور دارد، بنابراین •عملگر تقسیم با ممیز شناور اعlمال شده است.•

– int intVar1 =1, intVar2=2;intVar1 / intVar2;

اعمال تقسیم صحیح،• است!0جواب: •

Page 16: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

16

تبدیل نوع دادهدو نوع!•

ضمنی، یا خودکار–به صورت خودکار انجام می شود،•

17 / 5.5منجر به تبدیل زیر می شود:«

17 17.0

صریح–static_cast<double>(intVar)

انجام قابل نی5ز زی5ر دس5تور ب5ا ص5ریح تبدی5ل اس5ت، ام5ا توص5یه می کن5م ب5ه اس5تفاده از دستور

فوق عادت کنید!نام متغیر (نوع داده مقصد)

Page 17: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

17

عملگرهای اختصاریعملگرهای افزایشی و کاهشی•

++، عملگر –•z معادل با ++z = z + 1!است

عملگر --،–•z معادل با --z = z – 1!است

Z++++ و Z ب5ا یکدیگ5ر متفاوت هس5تند! این دو مقدار را ارزیابی کرده و توجیه کنید!

Z++ * 8 و ++Z * 8

Page 18: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

18

ورودی و خروجی کنسولcin, cout, cerr عبارتند از I/Oاشیا مربوط به• تعریف std< در فضای نام iostreamکه در کتابخانه >•

شده اند،برای استفاده از آن ها، می توان از رویه ذیل استفاده •

نمود:

#include <iostream>using namespace std;

،cin++ می گویند که تعاریف مربوط به Cاین دستورات به –cout وcerr!را از کجا به دست بیاورد

Page 19: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

19

قالب دار کردن اعداددستورات زیر، نمایش معمول )با دو رقم اعشار( از •

اعداد ممیز شناور را موجب می شوند،cout.setf(ios::fixed);cout.setf(ios::showpoint);cout.precision(2);

های پس از خود را تحت coutاین دستورات، همه •تاثیر قرار می دهند.

دقیقا دو رقم اعشار پس از ممیز داریم!–مثال:–

cout << "The price is $" << price << endl;نتیجه به صورت ذیل است:•

The price is $78.50دقت نمایش را می توان در هنگام اجرا نیز تغییر داد.•

Page 20: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

20

خروجی خطا ارسال کنیم،cerrکافی است که خروجی را به •

–cerr دقیقا مانند cout،کار می کند مکانیزمی برای تفاوت قائل شدن بین خروجی –

استاندارد و خروجی خطا فراهم می کند، )سعی (کنیم به استفاده صحیح از این اشیا عادت کنیم

Page 21: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

21

cinورودی با استفاده از برای خروجی cout برای ورودی و از شی cinاز شی •

استفاده می شود،تفاوت ها•

"<<" عملگر استخراج از جریان–جهت آن از جریان به سمت متغیر)ها( است.•

” استفاده می شود،cout به جای شی "cinاز شی "–، از هیچ لفظی نمی توان استفاده کرد.cinبرای –

باید ورودی ای برای یک متغیر فراهم کند!•cin >> num;

در کنسول، منتظر دریافت یک ورودی می ماند،–مقدار وارد شده در کنسول را به متغیر منسوب می کند.–

Page 22: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

22

توضیحاتیکی از مهمترین اهداف توضیحات، خواناتر کردن برنامه ها و •

ساده تر کردن فرآیند تغییر آن ها است.دو شیوه کلی:•

– از محل قرار گیری دو اسلش تا پایان خط جاری به عنوان توضیح // .فرض می شود

– ،هر آنچه که بین این دو عالمت قرار بگیرد */*/حتی کاراکتر خط جدید نیز به عنوان توضیح فرض می شود.

از هر دو روش به صورت معlمول استفاده می شود.–

Page 23: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

23

کتابخانه ها++، از قالب Cبرای استفاده از کتابخانه ها در •

دستوری زیر استفاده می کنیم:• #include <Library_Name>

به پیش پردازنده می گوید که کتابخانه مورد نظر را –برای استفاده، به برنامه الحاق کند.

به صورت خیلی ساده می توان گفت که قبل از کامپایل •برنامه، کتابخانه مورد نظر را به برنامه الحاق می کند،

++ وجود دارند.Cکتابخانه های زیادی برای •

Page 24: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

24

عملگرهای رابطه ای

نماد مرسوم

عملگر معادل در زبان C++

مثال در C++ توضیح

عملگرهای رابطه ای> > x > y X بزرگتر ازy.است < < x < y X ازy.کمتر است >= x >= y X بزرگتر یا مساوی باy.است <= x <= y X کوچکتر یا مساوی باy

است.عملگرهای برابری

= == x == y X باy.برابر است != x != y X باy.برابر نیست

Page 25: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

25

ارزیابی عبارات رابطه ایboolنوع داده •

را باز می گرداند،false یا trueمقدار ––True و false ثوابت از پیش تعریف شده برای نوع ،

هستند.boolداده

Page 26: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

26

اولویت عملگرها

بیشترین اولویت

کمترین اولویت

Page 27: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

27

اولویت عملگرها )ادامه(

بیشترین اولویت

کمترین اولویت

Page 28: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

28

اولویت عملگرها )ادامه(

بیشترین اولویت

کمترین اولویت

Page 29: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

29

اولویت عملگرها )ادامه(

بیشترین اولویت

کمترین اولویت

Page 30: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

30

ساختارهای کنترل جریان برنامه

اجرای دنباله ای•دستورات به ترتیبی که در برنامه آمده اند اجرا می شوند،–

انتقال کنترل•دستور بعدی که اجرا می شود، الزاما دستور بعدی نیست!–

سه ساختار کنترل جریان وجود دارد:•ساختار دنباله ای–

به صورت پیش فرض، دستورات برنامه به ترتیبی که در برنامه •آمده اند اجرا می شوند،

ساختارهای انتخاب–• if, if/else, switch

ساختارهای تکرار–• while, do/while, for

Page 31: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

31

ifساختار انتخابی ++ ذیل،Cترجمه شبه کد به کد •

If student’s grade is greater than or equal to 60Print “Passed”

if ( grade >= 60 ) cout << "Passed ;"

 

A decision can be made on any expression. zero - false nonzero - trueExample:3 - 4 is true

Page 32: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

32

عملگر شرطی سه تایی(?:)عملگر شرطی سه تایی•

cout << ( grade >= 60 ? “Passed” : “Failed” );

Condition Value if true Value if false

Page 33: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

33

switchساختار انتخاب چندگانه

Page 34: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

ساختار تکرار

Page 35: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

35

whileساختار تکرار ساختار تکرار•

اجرای فرآیند مادامی که شرط صحیح باشد، تکرار می شود.–شبه کد–

while there are more items on my shopping list Purchase next item and cross it off my list

تا زمانی ادامه می یابد که شرط whileاجرای بدنه حلقه –حلقه نادرست شود!

مثال•int product = 2;while ( product <= 1000 )

product = 2 * product;

 

Page 36: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

36

)ادامه(whileساختار تکرار

Page 37: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

37

کنترل تکرار با شمارندهکنترل تکرار با شمارنده•

اجرای بدنه حلقه تا زمانی ادامه پیدا می کند که –شمارنده به مقدار مشخصی برسد،

تکرار معین•تعداد تکرارها از پیش مشخص است،–

مثال• A class of ten students took a quiz. The grades

(integers in the range 0 to 100) for this quiz are available to you. Determine the class average on

the quiz .

Page 38: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

38

کنترل تکرار با شمارنده )ادامه(شبه کد نمونه:•

Set total to zeroSet grade counter to oneWhile grade counter is less than or equal to tenInput the next gradeAdd the grade into the totalAdd one to the grade counterSet the class average to the total divided by tenPrint the class average

تمرین کالسی: این شبه کد را به یک برنامه معتبر •C.تبدیل کنید ++

Page 39: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

39

کنترل تکرار با شمارنده )ادامه(

1 // Fig. 2.7: fig02_07.cpp2 // Class average program with counter-controlled repetition.3 #include <iostream>4 5 using std::cout;6 using std::cin;7 using std::endl;8 9 // function main begins program execution10 int main()11 {12 int total; // sum of grades input by user13 int gradeCounter; // number of grade to be entered next14 int grade; // grade value15 int average; // average of grades16 17 // initialization phase18 total = 0; // initialize total19 gradeCounter = 1; // initialize loop counter20

Page 40: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

40

کنترل تکرار با شمارنده )ادامه(

21 // processing phase22 while ( gradeCounter <= 10 ) { // loop 10 times23 cout << "Enter grade: "; // prompt for input24 cin >> grade; // read grade from user25 total = total + grade; // add grade to total26 gradeCounter = gradeCounter + 1; // increment counter27 }28 29 // termination phase30 average = total / 10; // integer division31 32 // display result33 cout << "Class average is " << average << endl; 34 35 return 0; // indicate program ended successfully36 37 } // end function main

The counter gets incremented each time the loop executes. Eventually, the counter causes the loop to end.

Page 41: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

41

کنترل تکرار با شمارنده )ادامه(

Enter grade: 98Enter grade: 76Enter grade: 71Enter grade: 87Enter grade: 83Enter grade: 90Enter grade: 57Enter grade: 79Enter grade: 82Enter grade: 94Class average is 81

Page 42: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

42

کنترل تکرار با نگهبانحال فرض کنید مساله قبلی را به صورت زیر تغییر دهیم:•

Develop a class-averaging program that will process an arbitrary number of grades each time the program is run

تعداد دانش آموزان نامشخص است!–برنامه چگونه متوجه شود که لیست پایان یافته است؟–

مقدار نگهبان در این مساله،•مشخص کننده پایان ورود داده ها،–هنگامی که مقدار نگهبان به ورودی داده شد، حلقه خاتمه پیدا –

می کند.باید مقدار نگهبان را به گونه ای انتخاب نمود کهl یک ورودی معتبر –

نباشد،، انتخابی مناسب است.1مثال نمره منفی نداریم، پس مقدار نگهبان -•

Page 43: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

43

کنترل تکرار با نگهبان )ادامه(یادآوری )حل گام به گام مساله(•

شبه کد سطح باال،–Determine the class average for the quiz

اصالح و پاالیش شبه کد–Initialize variablesInput, sum and count the quiz gradesCalculate and print the class average

Page 44: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

44

کنترل تکرار با نگهبان )ادامه(بسیاری از برنامه ها از سه فاز تشکیل شده اند:•

مقداردهی اولیه–مقداردهی اولیه متغیرهای برنامه،•

پردازش–دریافت داده از ورودی، تغییر دادن متغیرهای برنامه،•

خاتمه–محاسبه و چاپ نتایج•

Page 45: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

45

کنترل تکرار با نگهبان )ادامه(مقداردهی اولیه:•

Initialize variablesبه دستورات زیر تبدیل می شود:

Initialize total to zeroInitialize counter to zero

پردازش:•Input, sum and count the quiz grades

به دستورات زیر تبدیل می شود:Input the first grade (possibly the sentinel)While the user has not as yet entered the sentinel

Add this grade into the running total Add one to the grade counter

Input the next grade (possibly the sentinel)

Page 46: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

46

کنترل تکرار با نگهبان )ادامه(خاتمه•

Calculate and print the class average

به دستورات زیر تبدیل می شود:If the counter is not equal to zero

Set the average to the total divided by the counter Print the average

Else Print “No grades were entered ”

تمرین کالسی: این شبه کد را به یک برنامه •++ تبدیل کنید.Cمعتبر

Page 47: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

47

کنترل تکرار با نگهبان )ادامه(1 // Fig. 2.9: fig02_09.cpp2 // Class average program with sentinel-controlled repetition.3 #include <iostream>4 5 using std::cout;6 using std::cin;7 using std::endl;8 using std::fixed;9 10 #include <iomanip> // parameterized stream manipulators11 12 using std::setprecision; // sets numeric output precision 13 14 // function main begins program execution15 int main()16 {17 int total; // sum of grades18 int gradeCounter; // number of grades entered19 int grade; // grade value20 21 double average; // number with decimal point for average22 23 // initialization phase24 total = 0; // initialize total25 gradeCounter = 0; // initialize loop counter

Data type double used to represent decimal numbers.

Page 48: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

48

کنترل تکرار با نگهبان )ادامه(26 27 // processing phase28 // get first grade from user29 cout << "Enter grade, -1 to end: "; // prompt for input30 cin >> grade; // read grade from user31 32 // loop until sentinel value read from user33 while ( grade != -1 ) { 34 total = total + grade; // add grade to total35 gradeCounter = gradeCounter + 1; // increment counter36 37 cout << "Enter grade, -1 to end: "; // prompt for input38 cin >> grade; // read next grade39 40 } // end while41 42 // termination phase43 // if user entered at least one grade ...44 if ( gradeCounter != 0 ) {45 46 // calculate average of all grades entered47 average = static_cast< double >( total ) / gradeCounter;48

static_cast<double>() treats total as a double temporarily (casting).

Required because dividing two integers truncates the remainder.

gradeCounter is an int, but it gets promoted to double.

Page 49: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

49

کنترل تکرار با نگهبان )ادامه(49 // display average with two digits of precision50 cout << "Class average is " << setprecision( 2 )51 << fixed << average << endl;52 53 } // end if part of if/else54 55 else // if no grades were entered, output appropriate message56 cout << "No grades were entered" << endl;57 58 return 0; // indicate program ended successfully59 60 } // end function main

Enter grade, -1 to end: 75Enter grade, -1 to end: 94Enter grade, -1 to end: 97Enter grade, -1 to end: 88Enter grade, -1 to end: 70Enter grade, -1 to end: 64Enter grade, -1 to end: 83Enter grade, -1 to end: 89Enter grade, -1 to end: -1Class average is 82.50

setprecision(2)prints two digits past decimal point (rounded to fit precision).

Programs that use this must include <iomanip>

fixed forces output to print in fixed point format (not scientific notation). Also, forces trailing zeros and decimal point to print.

Include <iostream>

Page 50: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

50

do/whileساختار تکرار

مشابه است، اما whileبا ساختار تکرار •دارای تفاوت های ذیل است:

شرط ادامه حلقه را در انتهای حلقه کنترل می کند،–بدنه حلقه حداقل برای یک بار اجرا می شود،–

به فرم ذیل است:•do{

statement }while ( condition );

Page 51: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

51

)ادامه(do/whileساختار تکرار

Page 52: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

52

)ادامه(do/whileساختار تکرار 1 // Fig. 2.24: fig02_24.cpp2 // Using the do/while repetition structure.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 // function main begins program execution9 int main()10 {11 int counter = 1; // initialize counter12 13 do { 14 cout << counter << " "; // display counter15 } while ( ++counter <= 10 ); // end do/while 16 17 cout << endl;18 19 return 0; // indicate successful termination20 21 } // end function main

1 2 3 4 5 6 7 8 9 10

Notice the preincrement in loop-continuation test.

Page 53: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

53

ساختارهای کنترلی النه ایبیانl مساله•

A college has a list of test results (1 = pass, 2 = fail) for 10 students. Write a program that analyzes the results. If more

than 8 students pass, print "Raise Tuition."با در نظر گرفlتن شرایط زیر•

نمره را دریافت می کند،10برنامه دقیقا –بنابراین از ساختار تکرار با شمارنده می توان استفاده کرد،•

می توان از دو شمارنده استفاده نمود،–یک شمارنده تعداد افراد قبول شده را ذخیره کند،•شمارنده دیگر، تعداد افراد رد شده را ذخیره کند،•

،2 است یا 1نتیجه آزمون یا – را به عنوان مردود در نظر بگیرید.1هر ورودی غیر از •

Page 54: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

54

ساختارهای کنترلی النه ای )ادامه(

شبه کد سطح باال•Analyze exam results and decide if tuition should be raised

پاالیش اولیه•Initialize variablesInput the ten quiz grades and count passes and failuresPrint a summary of the exam results and decide if tuition should be raised

پاالیش سه گامی•Initialize variables

به دستورات زیر تبدیل می شود:Initialize passes to zeroInitialize failures to zeroInitialize student counter to one

Page 55: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

55

ساختارهای کنترلی النه ای )ادامه(

پاالیش سه گامی )ادامه(•Input the ten quiz grades and count passes and failures

به دستورات زیر تبدیل می شود:While student counter is less than or equal to tenInput the next exam resultIf the student passed

Add one to passesElse Add one to failuresAdd one to student counter

Page 56: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

56

ساختارهای کنترلی النه ای )ادامه(

پاالیش سه گامی )ادامه(•Print a summary of the exam results and decide if tuition should be raised

به دستورات زیر تبدیل می شود:Print the number of passesPrint the number of failuresIf more than eight students passed

Print “Raise tuition ”تمرین کالسی: این شبه کد را به یک برنامه •

++ تبدیل کنید.Cمعتبر

Page 57: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

57

ساختارهای کنترلی النه ای Fig. 2.11: fig02_11.cpp // 1)ادامه(

2 // Analysis of examination results.3 #include <iostream>4 5 using std::cout;6 using std::cin;7 using std::endl;8 9 // function main begins program execution10 int main()11 {12 // initialize variables in declarations13 int passes = 0; // number of passes14 int failures = 0; // number of failures15 int studentCounter = 1; // student counter16 int result; // one exam result17 18 // process 10 students using counter-controlled loop19 while ( studentCounter <= 10 ) {20 21 // prompt user for input and obtain value from user22 cout << "Enter result (1 = pass, 2 = fail): ";23 cin >> result;24

Page 58: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

58

ساختارهای کنترلی النه ای )ادامه(

25 // if result 1, increment passes; if/else nested in while26 if ( result == 1 ) // if/else nested in while27 passes = passes + 1; 28 29 else // if result not 1, increment failures 30 failures = failures + 1; 31 32 // increment studentCounter so loop eventually terminates33 studentCounter = studentCounter + 1; 34 35 } // end while36 37 // termination phase; display number of passes and failures38 cout << "Passed " << passes << endl; 39 cout << "Failed " << failures << endl;40 41 // if more than eight students passed, print "raise tuition"42 if ( passes > 8 )43 cout << "Raise tuition " << endl; 44 45 return 0; // successful termination46 47 } // end function main

Page 59: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

59

ساختارهای کنترلی النه ای )ادامه(

Enter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 2Enter result (1 = pass, 2 = fail): 2Enter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 2Enter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 2Passed 6Failed 4

Enter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 2Enter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 1Passed 9Failed 1Raise tuition

Page 60: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

60

forساختار تکرار forساختار کلی حلقه تکرار •

for ( initialization; LoopContinuationTest; increment )

statement

مثال•for( int counter = 1; counter <= 10; counter++ )cout << counter << endl;

را چاپ می کند.10 تا 1اعداد صحیح از –

 

No semicolon after last statement

Page 61: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

61

)ادامه(forساختار تکرار 1 // Fig. 2.17: fig02_17.cpp2 // Counter-controlled repetition with the for structure.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 // function main begins program execution9 int main()10 {11 // Initialization, repetition condition and incrementing 12 // are all included in the for structure header. 13 14 for ( int counter = 1; counter <= 10; counter++ )15 cout << counter << endl; 16 17 return 0; // indicate successful termination18 19 } // end function main

Page 62: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

62

)ادامه(forساختار تکرار

12345678910

Page 63: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

63

)ادامه(forساختار تکرار را می توان با استفاده از forحلقه های تکرار •

بازنویسی کرد.whileحلقه های تکرار initialization;while ( loopContinuationTest){

statement increment;

}مقداردهی اولیه و افزایش•

برای استفاده از چندین متغیر، از , استفاده می شود.–for (int i = 0, j = 0; j + i <= 10; j++, i++)

cout << j + i << endl;

Page 64: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

64

)ادامه(forساختار تکرار

Page 65: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

65

)ادامه(forساختار تکرار 1 // Fig. 2.20: fig02_20.cpp2 // Summation with for.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 // function main begins program execution9 int main()10 {11 int sum = 0; // initialize sum12 13 // sum even integers from 2 through 10014 for ( int number = 2; number <= 100; number += 2 ) 15 sum += number; // add number to sum16 17 cout << "Sum is " << sum << endl; // output sum18 return 0; // successful termination19 20 } // end function main

Sum is 2550

Page 66: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

66

)ادامه(forساختار تکرار مساله محاسبه سود ترکیبی•

• A person invests $1000.00 in a savings account yielding 5 percent interest. Assuming that all interest is left on deposit in the account, calculate and print the amount of money in the account at the end of each year for 10 years. Use the following formula for determining these amounts:

a = p(1+r)• p is the original amount invested (i.e., the principal),

r is the annual interest rate,n is the number of years anda is the amount on deposit at the end of the nth year

n

Page 67: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

67

)ادامه(forساختار تکرار 1 // Fig. 2.21: fig02_21.cpp2 // Calculating compound interest.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 using std::ios;8 using std::fixed;9 10 #include <iomanip>11 12 using std::setw;13 using std::setprecision;14 15 #include <cmath> // enables program to use function pow16 17 // function main begins program execution18 int main()19 {20 double amount; // amount on deposit21 double principal = 1000.0; // starting principal22 double rate = .05; // interest rate23

<cmath> header needed for the pow function (program will not compile without it).

Page 68: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

68

)ادامه(forساختار تکرار 24 // output table column heads25 cout << "Year" << setw( 21 ) << "Amount on deposit" << endl;26 27 // set floating-point number format28 cout << fixed << setprecision( 2 ); 29 30 // calculate amount on deposit for each of ten years31 for ( int year = 1; year <= 10; year++ ) {32 33 // calculate new amount for specified year34 amount = principal * pow( 1.0 + rate, year );35 36 // output one table row37 cout << setw( 4 ) << year 38 << setw( 21 ) << amount << endl;39 40 } // end for 41 42 return 0; // indicate successful termination43 44 } // end function main

pow(x,y) = x raised to the yth power.

Sets the field width to at least 21 characters. If output less than 21, it is right-justified.

Page 69: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

69

)ادامه(forساختار تکرار

Year Amount on deposit 1 1050.00 2 1102.50 3 1157.63 4 1215.51 5 1276.28 6 1340.10 7 1407.10 8 1477.46 9 1551.33 10 1628.89

Numbers are right-justified due to setw statements (at positions 4 and 21).

Page 70: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

70

breakعبارت

•break، و while، for، do/whileدر ساختارهای تکرار–

منجر به خاتمه بالفاصله switchساختار تصمیم ساختار می شود.

اجرای برنامه با اولین دستور بعد از ساختار ادامه –می یابد.

استفاده های معمول•خروج زودهنگام از حلقه های تکرار،–.switchپریدن از بقیه حالت های ساختار –

Page 71: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

71

)ادامه(breakعبارت 1 // Fig. 2.26: fig02_26.cpp2 // Using the break statement in a for structure.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 // function main begins program execution9 int main()10 {11 12 int x; // x declared here so it can be used after the loop13 14 // loop 10 times15 for ( x = 1; x <= 10; x++ ) {16 17 // if x is 5, terminate loop18 if ( x == 5 )19 break; // break loop only if x is 520 21 cout << x << " "; // display value of x22 23 } // end for 24 25 cout << "\nBroke out of loop when x became " << x << endl;

Exits for structure when break executed.

Page 72: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

72

)ادامه(breakعبارت

26 27 return 0; // indicate successful termination28 29 } // end function main

1 2 3 4Broke out of loop when x became 5

Page 73: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

73

continueعبارت

•continue ,while, forکاربرد در ساختارهای تکرار –

do/whileاز اجرای بقیه ساختار صرlف نظر می کند و–تکرار بعدی حلقه را انجام می دهد.–

do/while و whileدر ساختارهای •، شرط حلقه continueبالفاصله پس از عبارت –

آزموده می شود.forدر ساختار •

، عبارت continueبالفاصله پس از عبارت –افزایش اجرا می شود،

شرط حلقه مورد آزمایش قرار می گیرد.–

Page 74: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

74

)ادامه(continueعبارت 1 // Fig. 2.27: fig02_27.cpp2 // Using the continue statement in a for structure.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 // function main begins program execution9 int main()10 {11 // loop 10 times12 for ( int x = 1; x <= 10; x++ ) {13 14 // if x is 5, continue with next iteration of loop15 if ( x == 5 )16 continue; // skip remaining code in loop body17 18 cout << x << " "; // display value of x19 20 } // end for structure21 22 cout << "\nUsed continue to skip printing the value 5" 23 << endl;24 25 return 0; // indicate successful termination

Skips to next iteration of the loop.

Page 75: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

75

)ادامه(continueعبارت

26 27 } // end function main

1 2 3 4 6 7 8 9 10Used continue to skip printing the value 5

Page 76: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

76

ساختارهای کنترلی )جمع بندی(

 

 

Page 77: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

77

ساختارهای کنترلی )جمع بندی(

 

 

Page 78: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

توابع

Page 79: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

79

مقدمهتقسیم و غلبه•

ساختن یک برنامه با استفاده از برlنامه های –کوچک تر

فرآیند توسعه هر کدام از برنامه های کوچکتر، به –دلیل کوچکی، قابل مدیریت تر است.

Page 80: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

80

++Cاجزای برنامه های توابع و کالسl ها،•++ از اجزای جدید و همچنین پیشl تعریف شده Cبرنامه های •

اسlتفاده می کنند:جدید: توابع و کالس های تعریف شده توسط برنامه نویس،–پیش تعریف شده: توابع و کالس های تعریف شده در کتابخانه های –

موجود،•STL, Boost, CGAL, LEDA… ,

برای اسlتفاده از توابع، باید آن ها را فراخوانی کرد:•برای فراخوانی، نیاز به نام و اطالعات ورودی تابع است،–

تعریف توابع•فقط یک بار نوشته می شوند،–از سایر توابع مخفی است.–

Page 81: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

81

++ Cاجزای برنامه های )ادامه(

رئیس و کارمند•رئیس از کارمند خود می خواهد )فراخوانی( کاری –

را انجام دهد و پس از انجام آن کار، نتیجه حاصل را گزارش )بازگرداندن نتیجه( کند.

Page 82: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

82

توابعتوابع•

پیمانه ای کردن برنامه ها،–استفاده مجدد–

توابع یک بار تعریف و چندین بار فراخوانی می شوند،•متغیرهای محلی•

تنها در بدنه توابع شناخته شده هستند،–تمامی متغیرهای تعریف شده در بدنه توابع، محلی هستند،–

پارامترها•متغیرهایی که به عنوان ورودی به تابع مورد فراخوانی داده –

شده اند،با خود اطالعاتی را از جهان بیرون حمل می کنند!–

Page 83: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

83

تعریف توابعنمونه اولیه توابع•

به کامپایلر درباره نوع پارامترهای ورودی و نتیجه –تابع اطالع می دهد:

– int square( int ); بوده و نتیجه آن نیز از intمقدار ورودی تابع از نوع •

است،intنوع فراخوانی تابع•

– square(x);عملگر پرانتز بعد از نام تابع، عملگر فراخوانی تابع –

است، را به تابع پاس می دهد،xlپارامتر • را دریافت می کند )تغییر در آن xتابع یک کپی از پارامتر •

در برنامه فراخواننده نمی شود(،xمنجر به تغییر پس از پایان تابع، نتیجه را بازگردانی می کند.–

Page 84: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

84

تعریف توابع )ادامه(قالب تعریفl توابع•

return-value-type function-name( parameter-list ){ declarations and statements}

لیست پارامترها–پارامترها با کاما از یکدیگر جدا شده اند،•

هرl پارامتر باید دارای یک نوع داده باشد،– استفاده voidدر صورتی که تابع هیچ پارامتری نداشته باشد، از نوع •

می شود و یا لیست پارامترها را تهی در نظر می گیریم.نوع داده نتیجه–

استفاده voidاگر تابع هیچ مقداری را به عنوان نتیجه بازنگرداند، از •می کنیم.

Page 85: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

85

تعریف توابع )ادامه(مثال•

int square( int y ) }

return y * y;{

returnکلمه کلیدی •داده را بازگردانده و کنترل اجرا را به فراخواننده بر –

می گرداند،در صورتی که هیچ داده ای بر نمی گردانید، به عنوان یک عادت خوب •

استفاده کنید.;returnاز عبارت اجرای تابع هنگامی که به { برسد، خاتمه پیدا می کند،–

در این حالت، کنترل اجرا به فراخواننده بازگردانده می شود،•نمی توان یک تابع را درون تابعی دیگر تعریف کرد.•

Page 86: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

86

1 // Fig. 3.3: fig03_03.cpp2 // Creating and using a programmer-defined function.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 int square( int ); // function prototype9 10 int main()11 {12 // loop 10 times and calculate and output 13 // square of x each time14 for ( int x = 1; x <= 10; x++ ) 15 cout << square( x ) << " "; // function call16 17 cout << endl;18 19 return 0; // indicates successful termination20 21 } // end main22

Parentheses () cause function to be called. When done, it returns the result.

Function prototype: specifies data types of arguments and return values. square expects and int, and returns an int.

Page 87: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

87

23 // square function definition returns square of an integer 24 int square( int y ) // y is a copy of argument to function25 { 26 return y * y; // returns square of y as an int 27 28 } // end function square

1 4 9 16 25 36 49 64 81 100

Definition of square. y is a copy of the argument passed. Returns y * y, or y squared.

Page 88: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

88

1 // Fig. 3.4: fig03_04.cpp2 // Finding the maximum of three floating-point numbers.3 #include <iostream>4 5 using std::cout;6 using std::cin;7 using std::endl;8 9 double maximum( double, double, double ); // function prototype10 11 int main()12 {13 double number1;14 double number2;15 double number3;16 17 cout << "Enter three floating-point numbers: ";18 cin >> number1 >> number2 >> number3;19 20 // number1, number2 and number3 are arguments to 21 // the maximum function call22 cout << "Maximum is: " 23 << maximum( number1, number2, number3 ) << endl;24 25 return 0; // indicates successful termination

Function maximum takes 3 arguments (all double) and returns a double.

Page 89: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

89

26 27 } // end main28 29 // function maximum definition; 30 // x, y and z are parameters 31 double maximum( double x, double y, double z ) 32 { 33 double max = x; // assume x is largest 34 35 if ( y > max ) // if y is larger, 36 max = y; // assign y to max 37 38 if ( z > max ) // if z is larger, 39 max = z; // assign z to max 40 41 return max; // max is largest value 42 43 } // end function maximum

Enter three floating-point numbers: 99.32 37.3 27.1928Maximum is: 99.32

Enter three floating-point numbers: 1.1 3.333 2.22Maximum is: 3.333

Enter three floating-point numbers: 27.9 14.31 88.99Maximum is: 88.99

Comma separated list for multiple parameters.

Page 90: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

90

نمونه اولیه توابعنمونه اولیه توابع شlامل•

نام تابع،–تعداد و نوع داده پارامترها،–نوع داده نتیجه تابع،–تنها در صورتی نیاز به تعریف نمونه اولیه تابع داریم که تابع را قبل –

از تعریف آن فراخوانی کرده باشیم.نمونه اولیه باید دقیقا با تعریف تابع همخوانیl داشته باشد:•

نمونه اولیه–double maximum( double, double, double );

تعریف–double maximum( double x, double y, double z )}… {

Page 91: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

91

نمونه اولیه توابع )ادامه(امضای تابع•

نام و پارامترهای نمونه اولیه تابع–• double maximum( double, double, double );

امضای هیچ دو تابعی نمی تواند یکسان باشد،–تبدیل نوع داده خودکار پارامترها•

الزام به اینکه پارامترهای ورودی توابع از نوع داده تعیین شده باشند،–double (4.0) به نوع int (4)تبدیل •

cout << sqrt(4)قواعد تبدیل–

عموما به صورت خودکار انجام می شود،• می تواند منجر به از دست رفتن داده ها شود،int به doubleتبدیل از •

– 3.4 to 3انواع مرکب به باالترین نوع داده تبدیل می شوند:–

• int * double

Function signature

Page 92: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

92

نمونه اولیه توابع )ادامه(Data types

long double

double

float

unsigned long int (synonymous with unsigned long)

long int (synonymous with long)

unsigned int (synonymous with unsigned)

int

unsigned short int (synonymous with unsigned short)

short int (synonymous with short)

unsigned char

char

bool (false becomes 0, true becomes 1)

Page 93: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

93

فایل های سرآمدفایل های سرآمد شامل•

نمونه های اولیه توابع،–تعریف انواع داده و ثوابت.–

استh.پسوند فایل های سرآمد•فایل های سرآمد تولید شده توسط برنامه نویس–

#include “myheader.h”فایل های سرآمد کتابخانه ای•

#include <cmath>

Page 94: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

94

تولید عدد تصادفی<cstdlib> از کتابخانه randتابع •

– i = rand();تولید یک عدد صحیح نامنفی تصادفی بین صفر و –

RAND_MAX است(،32767 )معموال تبدیل به بازه مورد نظر•

%عملگر باقی مانده –• 10 % 3 is 1• x % y is between 0 and y – 1

مثال–i = rand() % 6 + 1;

• “Rand() % 6” generates a number between 0 and 5 (scaling)• “+ 1” makes the range 1 to 6 (shift)

Page 95: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

95

1 // Fig. 3.7: fig03_07.cpp2 // Shifted, scaled integers produced by 1 + rand() % 6.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <iomanip>9 10 using std::setw;11 12 #include <cstdlib> // contains function prototype for rand 13 14 int main()15 {16 // loop 20 times17 for ( int counter = 1; counter <= 20; counter++ ) {18 19 // pick random number from 1 to 6 and output it20 cout << setw( 10 ) << ( 1 + rand() % 6 );21 22 // if counter divisible by 5, begin new line of output23 if ( counter % 5 == 0 )24 cout << endl;25 26 } // end for structure

Output of rand() scaled and shifted to be a number between 1 and 6.

Page 96: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

96

27 28 return 0; // indicates successful termination29 30 } // end main

6 6 5 5 6 5 1 1 5 3 6 6 2 4 2 6 2 3 4 1

Page 97: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

97

تولید عدد تصادفی )ادامه()( را randتمرین کالسی: توزیع احتمال تابع •

بیابید!

Page 98: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

98

1 // Fig. 3.9: fig03_09.cpp2 // Randomizing die-rolling program.3 #include <iostream>4 5 using std::cout;6 using std::cin;7 using std::endl;8 9 #include <iomanip>10 11 using std::setw;12 13 // contains prototypes for functions srand and rand14 #include <cstdlib>15 16 // main function begins program execution17 int main()18 {19 unsigned seed;20 21 cout << "Enter seed: ";22 cin >> seed;23 srand( seed ); // seed random number generator24

Setting the seed with srand().

Page 99: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

99

25 // loop 10 times26 for ( int counter = 1; counter <= 10; counter++ ) {27 28 // pick random number from 1 to 6 and output it29 cout << setw( 10 ) << ( 1 + rand() % 6 );30 31 // if counter divisible by 5, begin new line of output32 if ( counter % 5 == 0 )33 cout << endl;34 35 } // end for 36 37 return 0; // indicates successful termination38 39 } // end main

Enter seed: 67 6 1 4 6 2 1 6 1 6 4

Enter seed: 432 4 6 3 1 6 3 1 5 4 2

Enter seed: 67 6 1 4 6 2 1 6 1 6 4

rand() gives the same sequence if it has the same initial seed.

Page 100: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

تولید عدد تصادفی )ادامه(برای اینکه الزم نباشد مقدار اولیه تصادفی را •

از کاربر دریافت کنیم، می توان از راهکار زیر استفاده کرد:

– srand( time( 0 ) );– time( 0 );

• <ctime>زمان فعلی را به ثانیه بازمی گرداند.•

100

Page 101: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

enumساختار

•Enumerationمجموعه ای مرتب از برچسب ها–

enum typeName {constant1, constant2…};به صورت پیش فرض، اندیس اولین عنصر صفر –

است،برچسب ها باید متمایز باشند،– نمی توان عدد صحیح نسبت enumبه متغیرهای –

داد!مثال:•

enum Status {CONTINUE, WON, LOST};Status enumVar ;

enumVar = WON; // cannot do enumVar = 1101

Page 102: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

)ادامه(enumساختار می توان اندیس اولیه متفاوتی به اولین عنصر •

نسبت داد:enum Months { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC};

102

Page 103: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

رده های حافظهخصوصیت های یک متغیر•

نام، نوع داده، اندازه، مقدار–رده حافظه–

تا چه مدت مقدار آن در حافظه نگهداری شود؟•قلمرو–

در چه جایی از برنامه می توان به متغیرها ارجاع داد؟•قابلیت پیوند–

آیا متغیر فقط در همین فایل قابل ارجاع است یا نه؟•

103

Page 104: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

رده های حافظه )ادامه(رده حافظه خودکار•

هنگامی که اجرای برنامه وارد بلوکی می شود که متغیر در آن تعریف شده، –متغیر ایجاد شده،

و با به رسیدن به پایان آن بلوک، متغیر از بین می رود،–فقط متغیرهای محلی در توابع می توانند خودکار باشند،–

به صورت پیش فرض خودکار هستند،•برای بیان خودکار بودن صریح یک متغیر استفاده می شود، autoاز کلمه کلیدی •

registerکلمه کلیدی –به کامپایلر توصیه می کند که این متغیر را در ثبات های پردازنده جاگذاری کند!•معموال برای متغیرهای پر استفاده مانند شمارنده های حلقه ها کاربرد دارد،•معموال نیازی به آن نیست، زیرا کامپایلرهای امروزی بهینه سازی را خودکار انجام •

می دهند، auto یا registerنمی توان به صورت همزمان از دو کلمه کلیدی –

استفاده کرد• register int counter = 1;

104

Page 105: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

رده های حافظه )ادامه(رده های حافظه استاتیک•

در تمام طول اجرای برنامه از زمان تعریف وجود دارند،–البته قواعد قلمرو در مورد آن ها صادق است، بنابراین ممکن است در –

دسترس نباشند!staticکلمه کلیدی •

متغیرهای محلی در توابع،–در توالی فراخوانی توابع، مقدار خود را حفظ می کنند!–تنها در تابعی که تعریف شده اند، شناخته شده هستند!–

externکلمه کلیدی •برای توابع و متغیرهای عمومی، به صورت پیش فرض استفاده می شود،–

عمومی: توابع یا متغیرهایی که خارج از هر تابعی تعریف می شوند،•در هر تابعی که پس از تعریف شدن آن بیاید، شناخته شده هستند!–

105

Page 106: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

قواعد قلمروقلمرو•

بخشی از برنامه که یک شناسه را می توان در آن –استفاده کرد!

قلمرو فاlیل•در همه توابع شناخته شده است و در خارج از هر تابعی –

تعریف شده است،متغیرهای عمومی، توابع و امضای آن ها،–

قلمرو تاlبع•تنها در بدنه تابع قابل استفاده است،–تنها شناسه ها در این قلمرو قرار می گیرند.–

106

Page 107: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

قواعد قلمرو )ادامه(قلمرو بلوک•

تنها از محل تعریف تا پایان بلوک جاری و کلیه –زیربلوک های آن قابل دسترسی است،

متغیرهای محلی، پارامترهای توابع،– دارای قلمرو بلوکی هستند،staticمتغیرهای –

قلمرو با رده حافظه دو خصوصیت کامال متفاوت •هستند!

107

Page 108: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

1 // Fig. 3.12: fig03_12.cpp2 // A scoping example.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 void useLocal( void ); // function prototype9 void useStaticLocal( void ); // function prototype10 void useGlobal( void ); // function prototype11 12 int x = 1; // global variable13 14 int main()15 {16 int x = 5; // local variable to main17 18 cout << "local x in main's outer scope is " << x << endl;19 20 { // start new scope 21 22 int x = 7; 23 24 cout << "local x in main's inner scope is " << x << endl;25 26 } // end new scope

Declared outside of function; global variable with file scope.

Local variable with function scope.

Create a new block, giving x block scope. When the block ends, this x is destroyed.

108

Page 109: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

27 28 cout << "local x in main's outer scope is " << x << endl;29 30 useLocal(); // useLocal has local x31 useStaticLocal(); // useStaticLocal has static local x32 useGlobal(); // useGlobal uses global x33 useLocal(); // useLocal reinitializes its local x34 useStaticLocal(); // static local x retains its prior value35 useGlobal(); // global x also retains its value36 37 cout << "\nlocal x in main is " << x << endl;38 39 return 0; // indicates successful termination40 41 } // end main42

109

Page 110: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

43 // useLocal reinitializes local variable x during each call44 void useLocal( void )45 {46 int x = 25; // initialized each time useLocal is called47 48 cout << endl << "local x is " << x 49 << " on entering useLocal" << endl;50 ++x;51 cout << "local x is " << x 52 << " on exiting useLocal" << endl;53 54 } // end function useLocal55

Automatic variable (local variable of function). This is destroyed when the function exits, and reinitialized when the function begins.

110

Page 111: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

56 // useStaticLocal initializes static local variable x only the57 // first time the function is called; value of x is saved58 // between calls to this function59 void useStaticLocal( void )60 {61 // initialized only first time useStaticLocal is called62 static int x = 50; 63 64 cout << endl << "local static x is " << x 65 << " on entering useStaticLocal" << endl;66 ++x; 67 cout << "local static x is " << x 68 << " on exiting useStaticLocal" << endl;69 70 } // end function useStaticLocal71

Static local variable of function; it is initialized only once, and retains its value between function calls.

111

Page 112: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

72 // useGlobal modifies global variable x during each call73 void useGlobal( void )74 {75 cout << endl << "global x is " << x 76 << " on entering useGlobal" << endl;77 x *= 10;78 cout << "global x is " << x 79 << " on exiting useGlobal" << endl;80 81 } // end function useGlobal

local x in main's outer scope is 5local x in main's inner scope is 7local x in main's outer scope is 5 local x is 25 on entering useLocallocal x is 26 on exiting useLocal local static x is 50 on entering useStaticLocallocal static x is 51 on exiting useStaticLocal

global x is 1 on entering useGlobalglobal x is 10 on exiting useGlobal

This function does not declare any variables. It uses the global x declared in the beginning of the program.

112

Page 113: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

 local x is 25 on entering useLocallocal x is 26 on exiting useLocal local static x is 51 on entering useStaticLocallocal static x is 52 on exiting useStaticLocal global x is 10 on entering useGlobalglobal x is 100 on exiting useGlobal local x in main is 5

113

Page 114: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

بازگشتتوابع بازگشتی•

توابعی که خود را فراخوانی می کنند،–در این توابع معموال یک )یا چند( حالت اولیه حل –

l،می شونداگر حالتی غیر از حالت اولیه باشد:•

مساله به زیر مسائل شکسته شده،–تابع به صورت بازگشتی برای حل کردن هر یک از –

زیر مساله های کوچکتر فراخوانی می شود،این حالت ادامه می یابد تا به حالت ابتدای برسد و سپس •

پاسخ را به صورت پایین با باال تولید می کند!114

Page 115: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

بازگشت )ادامه(مثال•

n! = n * ( n – 1 ) * ( n – 2 ) * … * 1رابطه بازگشتی: –

• ( n! = n * ( n – 1 )! )

5! = 5 * 4!4! = 4 * 3!…

(1! = 0! = 1حالت پایه )–

115

Page 116: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

1 // Fig. 3.14: fig03_14.cpp2 // Recursive factorial function.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <iomanip>9 10 using std::setw;11 12 unsigned long factorial( unsigned long ); // function prototype13 14 int main()15 {16 // Loop 10 times. During each iteration, calculate 17 // factorial( i ) and display result.18 for ( int i = 0; i <= 10; i++ )19 cout << setw( 2 ) << i << "! = " 20 << factorial( i ) << endl;21 22 return 0; // indicates successful termination23 24 } // end main

Data type unsigned long can hold an integer from 0 to 4 billion.

116

Page 117: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

25 26 // recursive definition of function factorial 27 unsigned long factorial( unsigned long number )28 { 29 // base case 30 if ( number <= 1 ) 31 return 1; 32 33 // recursive step 34 else 35 return number * factorial( number - 1 ); 36 37 } // end function factorial

0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 36288010! = 3628800

The base case occurs when we have 0! or 1!. All other cases must be split up (recursive step).

117

Page 118: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

دنباله فیبوناتچی...8, 5, 3, 2, 1, 1, 0دنباله فیبوناتچی: •

هر عدد، حاصل جمع دو عدد قبلی خودش است!–یک رابطه بازگشتی:–

• fib(n) = fib(n-1) + fib(n-2)نمونه کد متناظر:•

long fibonacci( long n ){if ( n == 0 || n == 1 ) // base case

return n; else

return fibonacci( n - 1 ) + fibonacci( n – 2 );

}118

Page 119: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

دنباله فیبوناتچی )ادامه(تعداد فراخوانی های بازگشتی:•

هر بار فراخوانی بازگشتی، تعداد فراخوانی ها را دو –برابر می کند!

• 30th number = 2^30 ~ 4 billion function callsپیچیدگی نمایی!–

119

Page 120: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

بازگشت و تکراراجرا•

تکرار: حلقه صریح،–بازگشت: فراخوانی بازگشتی،–

خاتمه•تکرار: شرط حلقه نادرست شود،–تکرار: به حالت پایه برسیم.–

در هر دو حالت می توان تکرار بی نهایت •داشت!

باید بین سرعت عملکرد و صراحت بیان، تعادل •120برقرار کرد!

Page 121: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

inlineتوابع inlineتوابع •

قبل از تعریف تابع می آید،inlineکلمه کلیدی –باعث می شود که کامپایلر به جای فراخوانی تابع، بدنه تابع را به –

جای هر فراخوانی جایگذاری کند.سربار فراخوانی تابع را کاهش می دهد،•بودن یک تابع را در نظر نگیرد و آن را inlineکامپایلر می تواند •

فراخوانی کند.استفاده از آن برای توابع کوچک و پرکاربرد توصیه می شود،–

مثال•inline double cube( const double s )

{return s * s * s} ; را s به کامپایلر می گوید که این تابع مقدار constکلمه کلیدی –

تغییر نمی دهد.121

Page 122: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

1 // Fig. 3.19: fig03_19.cpp2 // Using an inline function to calculate.3 // the volume of a cube.4 #include <iostream>5 6 using std::cout;7 using std::cin;8 using std::endl;9 10 // Definition of inline function cube. Definition of function11 // appears before function is called, so a function prototype 12 // is not required. First line of function definition acts as 13 // the prototype.14 inline double cube( const double side ) 15 { 16 return side * side * side; // calculate cube17 18 } // end function cube 19

122

Page 123: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

20 int main()21 {22 cout << "Enter the side length of your cube: ";23 24 double sideValue;25 26 cin >> sideValue;27 28 // calculate cube of sideValue and display result29 cout << "Volume of cube with side " 30 << sideValue << " is " << cube( sideValue ) << endl;31 32 return 0; // indicates successful termination33 34 } // end main

Enter the side length of your cube: 3.5Volume of cube with side 3.5 is 42.875

123

Page 124: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

ارجاع و پارامترهای ارجاعیفراخوانی با مقدار•

یک کپی از پارامتر را به تابع پاس می دهد،–هرگونه تغییر در پارامتر منجر به تغییر در مقدار –

متغیر اصلی نمی شود،از اثرات جانبی ناخواسته جلوگیری می کند،–

فراخوانی با ارجاع•توابع می توانند به صورت مستقیم به داده ها –

دسترسی داشته باشند،تغییرات در داده اصلی اعمال می شوند.–

124

Page 125: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

ارجاع5 و پارا5مترها5ی ارجاع5ی )ا5دامه(

پارامترهای ارجاعی•مانند این است که نام پارامتر را عوض کرده ایم!–

پارامتر را با ارجاع پاس می دهد،• &در نمونه اولیه، بعد از نوع داده از عملگر –

استفاده می شود،• void myFunction( int &data )

• l،در این تعریفdata ارجاعی به یک متغیر از نوع داده صحیح است!

هیچ تغییری در نحوه فراخوانی تابع ایجاد نمی شود،–اما، مقدار اصلی می تواند تغییر کند!•

125

Page 126: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

1 // Fig. 3.20: fig03_20.cpp2 // Comparing pass-by-value and pass-by-reference3 // with references.4 #include <iostream>5 6 using std::cout;7 using std::endl;8 9 int squareByValue( int ); // function prototype10 void squareByReference( int & ); // function prototype11 12 int main()13 {14 int x = 2;15 int z = 4;16 17 // demonstrate squareByValue18 cout << "x = " << x << " before squareByValue\n";19 cout << "Value returned by squareByValue: "20 << squareByValue( x ) << endl; 21 cout << "x = " << x << " after squareByValue\n" << endl;22

Notice the & operator, indicating pass-by-reference.

126

Page 127: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

23 // demonstrate squareByReference24 cout << "z = " << z << " before squareByReference" << endl;25 squareByReference( z );26 cout << "z = " << z << " after squareByReference" << endl;27 28 return 0; // indicates successful termination29 } // end main30 31 // squareByValue multiplies number by itself, stores the 32 // result in number and returns the new value of number 33 int squareByValue( int number ) 34 { 35 return number *= number; // caller's argument not modified36 37 } // end function squareByValue 38 39 // squareByReference multiplies numberRef by itself and 40 // stores the result in the variable to which numberRef 41 // refers in function main 42 void squareByReference( int &numberRef ) 43 { 44 numberRef *= numberRef; // caller's argument modified45 46 } // end function squareByReference

Changes number, but original parameter (x) is not modified.

Changes numberRef, an alias for the original parameter. Thus, z is changed.

127

Page 128: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

x = 2 before squareByValueValue returned by squareByValue: 4x = 2 after squareByValue z = 4 before squareByReferencez = 16 after squareByReference

128

Page 129: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

ارجاع5 و پارا5مترها5ی ارجاع5ی )ا5دامه(

می توان از ارجاعات برای تغییر نام متغیرها در •طول برنامه استفاده کرد!

به یک متغیر یکسان اشاره می کند،–نمی توان از آن در یک تابع استفاده کرد!–

int count = 1; // declare integer variable countInt &cRef = count; // create cRef as an alias for count

++cRef; // increment count (using its alias)

ارجاعات باید در هنگام تعریف شدن، حتما •مقدار دهی اولیه شوند!

129

Page 130: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

1 // Fig. 3.21: fig03_21.cpp2 // References must be initialized.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 int main()9 {10 int x = 3;11 12 // y refers to (is an alias for) x13 int &y = x; 14 15 cout << "x = " << x << endl << "y = " << y << endl;16 y = 7;17 cout << "x = " << x << endl << "y = " << y << endl;18 19 return 0; // indicates successful termination20 21 } // end main

x = 3y = 3x = 7y = 7

y declared as a reference to x.

130

Page 131: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

1 // Fig. 3.22: fig03_22.cpp2 // References must be initialized.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 int main()9 {10 int x = 3;11 int &y; // Error: y must be initialized12 13 cout << "x = " << x << endl << "y = " << y << endl;14 y = 7;15 cout << "x = " << x << endl << "y = " << y << endl;16 17 return 0; // indicates successful termination18 19 } // end main

Borland C++ command-line compiler error message: Error E2304 Fig03_22.cpp 11: Reference variable 'y' must be initialized in function main() Microsoft Visual C++ compiler error message: D:\cpphtp4_examples\ch03\Fig03_22.cpp(11) : error C2530: 'y' : references must be initialized

Uninitialized reference – compiler error.

131

Page 132: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

پارامترهای پیش فرضفراخوانی توابع بدون ارسال برخی از پارامترها•

اگر تعداد پارامترهای ارسال شده کمتر از تعداد تعریف –شده در امضای تابع باشد، پارامترهای سمت راست،

مقادیر پیش فرض را اختیار می کنند،مقادیر پیش فرض–

ثوابت، متغیرهای عمومی و فراخوانی سایر توابع!•int myFunction( int x = 1, int y = 2, int z = 3 );

– myFunction(3)• x = 3, y and z get defaults (rightmost)

– myFunction(3, 5)• x = 3, y = 5 and z gets default

132

Page 133: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

1 // Fig. 3.23: fig03_23.cpp2 // Using default arguments.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 // function prototype that specifies default arguments9 int boxVolume( int length = 1, int width = 1, int height = 1 );10 11 int main()12 {13 // no arguments--use default values for all dimensions14 cout << "The default box volume is: " << boxVolume();15 16 // specify length; default width and height17 cout << "\n\nThe volume of a box with length 10,\n"18 << "width 1 and height 1 is: " << boxVolume( 10 );19 20 // specify length and width; default height21 cout << "\n\nThe volume of a box with length 10,\n" 22 << "width 5 and height 1 is: " << boxVolume( 10, 5 );23

Set defaults in function prototype.

Function calls with some parameters missing – the rightmost parameters get their defaults.

133

Page 134: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

24 // specify all arguments25 cout << "\n\nThe volume of a box with length 10,\n"26 << "width 5 and height 2 is: " << boxVolume( 10, 5, 2 )27 << endl;28 29 return 0; // indicates successful termination30 31 } // end main32 33 // function boxVolume calculates the volume of a box34 int boxVolume( int length, int width, int height ) 35 { 36 return length * width * height; 37 38 } // end function boxVolume

The default box volume is: 1 The volume of a box with length 10,width 1 and height 1 is: 10 The volume of a box with length 10,width 5 and height 1 is: 50 The volume of a box with length 10,width 5 and height 2 is: 100

134

Page 135: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

::عملگر (::)عملگر یکانی واضح سازی قلمرو •

در صورتی که یک متغیر هم نام محلی داشته –باشیم، دسترسی به متغیر عمومی با همان نام را

فراهم می کند،در صورتی که نام ها متفاوت باشند، نیازی به –

استفاده از آن نیست! استفاده می شود:variable::به صورت –

• y = ::x + 3;

135

Page 136: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

1 // Fig. 3.24: fig03_24.cpp2 // Using the unary scope resolution operator.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <iomanip>9 10 using std::setprecision;11 12 // define global constant PI 13 const double PI = 3.14159265358979;14 15 int main()16 {17 // define local constant PI18 const float PI = static_cast< float >( ::PI );19 20 // display values of local and global PI constants21 cout << setprecision( 20 )22 << " Local float value of PI = " << PI 23 << "\nGlobal double value of PI = " << ::PI << endl;24 25 return 0; // indicates successful termination

Access the global PI with ::PI.

Cast the global PI to a float for the local PI. This example will show the difference between float and double.

136

Page 137: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

26 27 } // end main

Borland C++ command-line compiler output:  Local float value of PI = 3.141592741012573242Global double value of PI = 3.141592653589790007 Microsoft Visual C++ compiler output: Local float value of PI = 3.1415927410125732Global double value of PI = 3.14159265358979 

137

Page 138: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

سربارگذاری توابعسربارگذاری توابع•

توابع با نام یکسان، اما پارامترهای متفاوت،–وظیفه یکسانی را انجام می دهند،–

به صورت float و intبرای مثال، تابعی برای محاسبه مجذور •جداگانه:

int square( int x) {return x * x;}float square(float x) { return x * x; }

توابع سربارگذاری شده را با امضایشان از هم •تشخیص می دهند!

بنابراین، تعریف دو تابع با امضای یکسان، اما متفاوت –در نوع داده بازگشتی، مجاز نیست!

138

Page 139: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

1 // Fig. 3.25: fig03_25.cpp2 // Using overloaded functions.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 // function square for int values 9 int square( int x ) 10 { 11 cout << "Called square with int argument: " << x << endl;12 return x * x; 13 14 } // end int version of function square 15 16 // function square for double values 17 double square( double y ) 18 { 19 cout << "Called square with double argument: " << y << endl;20 return y * y; 21 22 } // end double version of function square 23

Overloaded functions have the same name, but the different parameters distinguish them.

139

Page 140: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

24 int main()25 {26 int intResult = square( 7 ); // calls int version27 double doubleResult = square( 7.5 ); // calls double version28 29 cout << "\nThe square of integer 7 is " << intResult30 << "\nThe square of double 7.5 is " << doubleResult 31 << endl; 32 33 return 0; // indicates successful termination34 35 } // end main

Called square with int argument: 7Called square with double argument: 7.5 The square of integer 7 is 49The square of double 7.5 is 56.25

The proper function is called based upon the argument (int or double).

140

Page 141: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

1 // Fig. 3.26: fig03_26.cpp2 // Name mangling.3 4 // function square for int values5 int square( int x ) 6 { 7 return x * x; 8 }9 10 // function square for double values11 double square( double y ) 12 { 13 return y * y; 14 }15 16 // function that receives arguments of types 17 // int, float, char and int *18 void nothing1( int a, float b, char c, int *d ) 19 { 20 // empty function body21 } 22

141

Page 142: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

23 // function that receives arguments of types 24 // char, int, float * and double *25 char *nothing2( char a, int b, float *c, double *d ) 26 { 27 return 0; 28 }29 30 int main()31 {32 return 0; // indicates successful termination33 34 } // end main

_main@nothing2$qcipfpd@nothing1$qifcpi@square$qd@square$qi

Mangled names produced in assembly language.

$q separates the function name from its parameters. c is char, d is double, i is int, pf is a pointer to a float, etc.

142

Page 143: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

1 // Fig. 3.27: fig03_27.cpp2 // Using a function template.3 #include <iostream>4 5 using std::cout;6 using std::cin;7 using std::endl;8 9 // definition of function template maximum 10 template < class T > // or template < typename T >11 T maximum( T value1, T value2, T value3 ) 12 { 13 T max = value1; 14 15 if ( value2 > max ) 16 max = value2; 17 18 if ( value3 > max ) 19 max = value3; 20 21 return max; 22 23 } // end function template maximum 24

Formal type parameter T placeholder for type of data to be tested by maximum.

maximum expects all parameters to be of the same type.

143

Page 144: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

25 int main()26 {27 // demonstrate maximum with int values28 int int1, int2, int3;29 30 cout << "Input three integer values: ";31 cin >> int1 >> int2 >> int3;32 33 // invoke int version of maximum34 cout << "The maximum integer value is: "35 << maximum( int1, int2, int3 ); 36 37 // demonstrate maximum with double values38 double double1, double2, double3;39 40 cout << "\n\nInput three double values: ";41 cin >> double1 >> double2 >> double3;42 43 // invoke double version of maximum44 cout << "The maximum double value is: "45 << maximum( double1, double2, double3 );46

maximum called with various data types.

144

Page 145: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

47 // demonstrate maximum with char values48 char char1, char2, char3;49 50 cout << "\n\nInput three characters: ";51 cin >> char1 >> char2 >> char3;52 53 // invoke char version of maximum54 cout << "The maximum character value is: "55 << maximum( char1, char2, char3 ) 56 << endl;57 58 return 0; // indicates successful termination59 60 } // end main

Input three integer values: 1 2 3The maximum integer value is: 3 Input three double values: 3.3 2.2 1.1The maximum double value is: 3.3 Input three characters: A C BThe maximum character value is: C145

Page 146: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

مراجعمراجع درس:•

جعفرنژاد قمی، عین ا...؛ برنامه نویسی به زبان –C ؛ انتشارات علوم رایانه؛ ویراست چهارم؛++

1391.جعفرنژاد قمی، عین ا... و کریم پور، انیس؛ مبانی –

کامپیوتر و الگوریتم ها؛ انتشارات علوم رایانه؛ .1391ویراست دوم؛

برای آماده سازی مطالب و اسالیدها از مراجع •زیر نیز استفاده کرده ام:

– Deitel, P.J. and Deitel, H.M.; C++: How to program; Prentice-Hall; Fifth Edition; 2005.146

Page 147: مبانی برنامهسازی با C++ جلسه سوم

Ali Shakiba – http://shakiba.id.ir

147