Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 실 습실 습 6-2 WEEK 2 - FUNCTIONS THAT RETURN A VALUE.

Slides:



Advertisements
Similar presentations
Copyright © 2003 Pearson Education, Inc. Slide 1.
Advertisements

Copyright © 2002 Pearson Education, Inc. Slide 1.
Pass by Value. COMP104 Pass by Value / Slide 2 Passing Parameters by Value * A function returns a single result (assuming the function is not a void function)
Chapter 6 Advanced Function Features Pass by Value Pass by Reference Const parameters Overloaded functions.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 5 Functions for All Subtasks.
Chapter 8 Scope, Lifetime and More on Functions. Definitions Scope –The region of program code where it is legal to reference (use) an identifier Three.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 11 – Fundraiser Application: Introducing Scope.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1 ; Programmer-Defined Functions Two components of a function definition.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 1- 1.
Chapter 5 Functions.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 6 Functions.
More on Functions Programming. COMP104 Lecture 19 / Slide 2 Passing Parameters by Reference l To have a function with multiple outputs, we have to use.
// Functions that take no arguments #include using namespace std; void function1(); void function2( void ); int main() { function1(); function2(); return.
Computer Science 1620 Accumulators. Recall the solution to our financial program: #include using namespace std; int main() { double balance = ;
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
1 6/20/2015CS150 Introduction to Computer Science 1 Functions Chapter 6, 8.
Functions:Passing Parameters by Value Programming.
1 Lab Session-4 CSIT121 Fall 2004 Scope of Variables Top Down Design Problem The Solution Lab Exercise for Demo.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Computer Science 1620 Function Scope & Global Variables.
Computer Science 1620 Programming & Problem Solving.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 6: Functions by.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 9: Pointers.
1 Session-9 CSIT 121 Spring 2006 Lab Demo (first 20 minutes) The correct way to do the previous lab sheet Function calls Calling void functions Calling.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Chapter 6: Functions.
Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.
Call-by-Value vs. Call-by-Reference Call-by-value parameters are used for passing information from the calling function to the called function (input parameters).
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
Lecture 9m: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept.
1 Chapter 9 Scope, Lifetime, and More on Functions.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 실 습실 습 6 WEEK 1 - INTRODUCTION TO VOID FUNCTIONS (PROCEDURES)
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
Chapter 8 Friends and Overloaded Operators. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Friend Function (8.1) Overloading.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 6 Functions.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9: Pointers.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Chapter 4 Applications of the Derivative.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 1 Functions.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6: Functions Starting Out with C++ Early Objects Seventh Edition.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 15 - C++ As A "Better C" Outline 15.1Introduction 15.2C A Simple Program: Adding Two Integers.
 2003 Prentice Hall, Inc. All rights reserved. Outline 1 fig02_07.cpp (1 of 2) 1 // Fig. 2.7: fig02_07.cpp 2 // Class average program with counter-controlled.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 실 습실 습 3.
© Copyright 2013 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 6 Functions.
Objective: Students will be able to: Declare and use variables Input integers.
Input a number #include using namespace std; int main() { int num; cout num; return 0; }
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 실 습실 습 7 WEEK 1 – 구조체 (STRUCTURES)
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14: More About Classes.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6: Functions Starting Out with C++ Early Objects Eighth Edition.
Function 2. User-Defined Functions C++ programs usually have the following form: // include statements // function prototypes // main() function // function.
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Pointers and Dynamic Arrays.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
Functions BICSE-6A Mr. Naeem Khalid Lecturer, Dept. of Computing.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 14: More About Classes.
 2000 Prentice Hall, Inc. All rights reserved Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece.
CS1201: Programming Language 2 Function I By: Nouf Aljaffan Edited by : Nouf Almunyif.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 실 습실 습 4.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9-1 Pointer Variables Pointer variable : Often just called a pointer, it's.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
CS 1430: Programming in C++.
Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.
Functions Imran Rashid CTO at ManiWeber Technologies.
Presentation transcript:

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 실 습실 습 6-2 WEEK 2 - FUNCTIONS THAT RETURN A VALUE

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 2 학습목표 1. 유효범위 (scope) 의 개념 학습 2. 정적 변수 vs 지역 변수의 차이점 학습 3. 값을 반환하는 함수 개발 방법 학습 4. 함수의 과적 (overloading) 개념 학습 5. 스트브와 드라이버를 통한 검사와 디버깅

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 3 LAB ASSIGNMENTS( 실습과제 ) Lesson 6C Lab 6.5: 변수의 유효 범위 Lab 6.6: 정적 변수 vs 지역 변수 Lesson 6D Lab 6.7: 값의 반환, 함수의 과적 Lab 6.8: Student-Generated Code Assignments

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 4 Lab 6.5 변수의 유효 범위 에서 download “ scope.cpp” // This program demonstrates scope rules. // PLACE YOUR NAME HERE. Exercise 1: 유효 범위에 대한 scope.cpp 프로그램의 출력 결과를 먼저 예측하여 본 후 실행 결과와 비교하여 보라.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 5 #include using namespace std; // _____________ variable definitions int sum1 = 0, sum2 = 0; // Function prototype void studyScope(int); int main() { // ______________ variable declarations int number = 10; cout << "Starting in main, the value of number is " << number << endl; cout << "Starting in main, the value of sum1 is " << sum1 << endl; cout << "Starting in main, the value of sum2 is " << sum2 << endl << endl; studyScope(number); cout << "Back in main, the value of number is " << number << endl; cout << "Back in main, the value of sum1 is " << sum1 << endl; cout << "Back in main, the value of sum2 is " << sum2 << endl << endl; return 0; } scope.cpp

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 6 /********************************************************* * studyScope * * This function exists to illustrate scope rules. * *********************************************************/ void studyScope(int myParameter) { // ___________ variable definition studyScope's outer block int number = 5; {// ____________ variable defeinition in studyScope's inner block int number = 1; number++; cout << "In studyScope's inner block number is now " << number << endl; sum1 += myParameter; sum2 += number; } number++; cout << "In studyScope's outer block number is now " << number << endl << endl; sum2 += number; }

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 7 Lab 6.6 정적 변수 vs 지역 변수 에서 download “money.cpp” // This program illustrates the use of local variables vs. static local // variables. It also illustrates the use of a default parameter. Exercise 1: money.cpp 프로그램에서 함수에게 전달된 money 의 누산 합계를 유지하기 위해 지역 변수와 정적 변수를 사용한다. 주석에 지시한 대로 프로그램을 완성하라. ( 실행 예 ) Adding $2.50 The total of all amounts so far is: Regular Total: $2.50 Static Total: $2.50 Adding $1.25 The total of all amounts so far is: Regular Total: $1.25 Static Total: $3.75 Adding default amount of $1.00 The total of all amounts so far is: Regular Total: $1.00 Static Total: $4.75 The correct total should now be $4.75

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 8 #include using namespace std; // Function prototype void totalMoney(double amount __________); // Uses a default value of 1.00 if // no value is passed to the function int main() { cout << setprecision(2) << fixed << showpoint; cout << "\nAdding $2.50 \n"; // Fill in the code to call the totalMoney function and pass it cout << "\nAdding $1.25 \n"; // Fill in the code to call the totalMoney function and pass it cout << "\nAdding default amount of $1.00\n"; // Fill in the code to call the totalMoney function and use the // default argument value, rather than passing a value to the function. cout << "The correct total should now be $4.75 \n\n"; return 0; } money.cpp

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 9 /********************************************************************** * totalMoney * * This function is passed an amount of money, which it adds to two * * accumulators -- one is a local variable and the other is a static * * local variable. It then prints out the two totals to illustrate * * the difference in the two kinds of variables. * **********************************************************************/ void totalMoney(double amount) { double regularTotal = 0.0; // Define a regular local double variable ____________ staticTotal = 0.0; // Define a static double variable // Fill in the code to add the amount passed in to regularTotal. // Fill in the code to add the amount passed in to staticTotal. // Display the new totals cout << "\nThe total of all amounts so far is: \n"; cout << "Regular Total: $" << regularTotal << endl; cout << "Static Total: $" << staticTotal << endl; }

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Lab 6.7 값의 반환, 함수의 과적 에서 download “ convertmoney.cpp ” // This program will convert American dollars to euros, // pesos, and yen. Exercise 1: 한화에 대한 오늘의 환율표를 인터넷에서 찾아 convertToWon 함수를 추가한 후 실행해 보자.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide // This program will convert American dollars to euros, pesos, and yen. // PLACE YOUR NAME HERE. #include using namespace std; // Function prototypes void convertToEuros(double dollars, double& euros); void convertToPesos(double dollars, double& pesos); void convertToYen (double dollars, double& yen); // Global constant CONVERSION RATES const doubleNUM_EUROS =.8218, // Number of euros to the dollar NUM_PESOS = 10.8, // Number of pesos to the dollar NUM_YEN = 108.5; // Number of yen to the dollar convertmoney.cpp

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide int main () { double dollars, euros, pesos, yen; cout << "Input the amount of American Dollars \n" << "you want converted to foreign currency: "; cin >> dollars; // Perform the conversions convertToEuros(dollars, euros); convertToPesos(dollars, pesos); convertToYen (dollars, yen); // call Korean won // Display the results cout << fixed << showpoint << setprecision(2); cout << "\n$" << dollars << " = \n" << setw(17) << euros << " euros \n" << setw(17) << pesos << " pesos \n" << setw(17) << yen << " yen \n\n"; return 0; }

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide /******************************************************************** * convertToEuros * * This function converts dollars to euros and places the result in * * a reference parameter so the result will be known to main. * ********************************************************************/ void convertToEuros (double dollars, double& euros) { euros = dollars * NUM_EUROS; } /******************************************************************** * convertToPesos * * This function converts dollars to pesos and places the result in * * a reference parameter so the result will be known to main. * ********************************************************************/ void convertToPesos (double dollars, double& pesos) { pesos = dollars * NUM_PESOS; } /******************************************************************** * convertToYen * * This function converts dollars to yen and places the result in * * a reference parameter so the result will be known to main. * ********************************************************************/ void convertToYen (double dollars, double& yen) { yen = dollars * NUM_YEN; }

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Exercise 2: euros, pesos, yen 변수를 참조로 사용하는 대신에 각 함수에서 변환한 값을 세 변수 각각에 배정하도록 수정하라. Exercise 3: Exercise 2 를 수정하여 변수에 값을 반환받는 대신에 이 반환 받은 값을 cout 문에서 바로 출력하게 하라. 에서 download “overloaded.cpp ” Exercise 4: void multiConversion(double dollars, double& euros, double& pesos) void multiConversion(double dollars, double& euros, double& pesos, double& yen) 과적함수 multiConversion 의 stub 를 완성하라.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide // overloaded.cpp // This program will input American money and convert it to foreign // currency. It illustrates the use of overloaded functions. // PLACE YOUR NAME HERE. #include using namespace std; // Function prototypes void multiConversion (double dollars, double& euros, double& pesos); void multiConversion (double dollars, double& euros, double& pesos, double& yen); // Global constant CONVERSION RATES const double NUM_EUROS =.8218, // Number of euros to the dollar NUM_PESOS = 10.8, // Number of pesos to the dollar NUM_YEN = 108.5; // Number of yen to the dollar overloaded.cpp

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide int main () { double dollars, euros = 0, pesos = 0, yen = 0; cout << fixed << showpoint << setprecision(2); cout << "Input the amount in American Dollars to \n" << "convert to euros and pesos: $" ; cin >> dollars; // Fill in the code to call the multiConversion function that // converts dollars to euros and pesos. Note that it requires // 3 arguments. Be sure to place them in the correct order. cout << "\n$" << dollars << " equals " << euros << " euros and " << pesos << " pesos.\n\n"; cout << "Input the amount in American Dollars to \n" << "convert to euros, pesos, and yen: $" ; cin >> dollars; // Fill in the code to call the multiConversion function that // converts dollars to euros, pesos, and yen. Note that it requires // 4 arguments. Be sure to place them in the correct order. cout << "\n$" << dollars << " equals " << euros << " euros, " << pesos << " pesos, and " << yen << " yen.\n\n"; return 0; }

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide /******************************************************************** * multiConversion * * This version of the overloaded multiConversion function converts * * dollars to euros and pesos. It has 3 parameters. * ********************************************************************/ void multiConversion(double dollars, double& euros, double& pesos) { // Currently this function is just a stub. Remove the cout statement // below and replace it with the code needed to complete this function. cout << "\nThe 3-parameter multiConversion function was called \n" << "with the value " << dollars << " passed to it.\n"; } /******************************************************************** * multiConversion * * This version of the overloaded multiConversion function converts * * dollars to euros, pesos, and yen. It has 4 parameters. * ********************************************************************/ void multiConversion(double dollars, double& euros, double& pesos, double& yen) { // Currently this function is just a stub. Remove the cout statement // below and replace it with the code needed to complete this function. cout << "\nThe 4-parameter multiConversion function was called \n" << "with the value " << dollars << " passed to it.\n"; }

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Lab 6.8 독립적인 소형 프로그램 개발 (Stub & Driver) 도전 : 스타 선발 ( 교과서 p.373) 연예인 선발대회에 심사위원이 5 명 있으며, 이들은 각 참가자에 대해 0 에서 10 사이의 점수를 준다. 8.3 과 같이 소숫점을 가진 점수도 허용된다. 참가자의 최종 점수는 받은 점수 중 최고점과 최하점을 버리고 남은 세 점수의 평균으로 결정된다. 이와 같이 참가자의 점수를 계산하는 프로그램을 작성하라. 프로그램은 다음 함수를 사용하여야 한다.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide void getJudgeData() 는 사용자에게 한 심사위원의 점수를 요구하고 값을 참조 매개변수에 저장한 다음 그 값의 유효성을 검증한다. 이 함수는 심사위원의 점수가 모두 입력되기 위해 main 에 의해 5 번 호출된다. getJudgeData(score1);// 각 score 는 double getJudgeData(score2); getJudgeData(score3); getJudgeData(score4); getJudgeData(score5); void calcScore() 는 행위자가 받은 점수 중 최고점과 최하점을 버리고 남은 세 점수의 평균을 계산하고 출력한다. main 에 의해 한 번만 호출되며 다섯 개의 점수를 전달받는다. calcScore 는 다음 두 함수에 의해 반환된 정보를 사용하여 어떤 점수를 제외할지를 결정한다. int findLowest() 는 전달된 다섯 개의 점수 중 최하점을 찾아 반환한다. int findHigest() 는 전달된 다섯 개의 점수 중 최고점을 찾아 반환한다.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide // Function prototypes void getJudgeData(double &); void calcScore(double, double, double, double, double); double findLowest(double, double, double, double, double); double findHighest(double, double, double, double, double);

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Thanks!!!!!!!!