Value returning function

Value returning function

CS1430: Programming in C++ Section 2 Instructor: Qi Yang 213 Ullrich [email protected] 1 Scope of Variables The region of code where it is legal to reference (use) an identifier. Local Scope Global Scope Class Scope 2 Code Block Between a pair of matching braces. For example, the body of a function

int main() { int alpha = 10; // A block for if statement if (alpha > 3) { int n; cin >> n; alpha += 3; } return 0; } 3 Local Scope The scope of an identifier declared inside a block extends from the point of declaration

to the end of that block. int main() { int alpha = 10; // A code block if (alpha > 3) { int num; cin >> num; alpha += num; } cout << alpha; // OK? cout << num; // OK? // Run time error! return 0; }

4 Global Scope The scope of an identifier declared outside all functions (and classes) extends from the point of declaration to the end of the entire source file. Programming Rules No global variables! 5 Class Scope Later this semester! 6 Scope of Function Parameters Formal parameters Local scope

Same as local variable Cannot reference it outside the function Receive values on function call Actual parameters (no global variables) Local scope Cannot reference it inside the called function 7 Example float DoIt(int num, char op); int main() { int base; float result; char choice; cout << Enter a number: ; cin >> base; cout << C for Cube and S for Square Root: ; cin >> choice;

// ---------------------------// Precondition: op is C or S // Postcondition: the cube of // num is computed when op is // C, and square root of num // is computed when op is S. // -----------------------------float DoIt(int num, char op) { if (op == C) result = pow(num, 3); else result = sqrt(num); while (choice != C && choice != S) { cout << C for Cube and S for Square Root: ; cin >> choice; } return result;

result = DoIt(base, choice); cout << The result: << result; return 0; } } // What is wrong? // Result not declared in the // function! 8 Precondition and Postcondition int DoIt(int num, char op); int main() { int base; float result; char choice; cout << Enter a number: ;

cin >> base; cout << C for Cube and S for Square: ; cin >> choice; while (choice != C && choice != S) { cout << C for Cube and S for Square: ; cin >> choice; } // -----------------------------// Precondition: op is C or S // Postcondition: the cube of // num is computed when op is // C, and square root of num // is computed when op is S. // -----------------------------int DoIt(int num, char op) { float result; if (op == C) result = pow(num, 3); else

result = sqrt(num); return result; result = DoIt(base, choice); cout << The result: << result; return 0; } } // The two variables // result have the same // name, but different! 9 Parameter Names Meaningful names Formal and actual parameters can have the same name They are different variables in different

scopes Normally they have different names 10 Lifetime of a Variable Lifetime The period of time during program execution when an identifier has memory allocated to it. Automatic variables A variable for which memory is allocated and deallocated when control enters and exits the block it is declared. Static variables A variable for which memory remains allocated throughout the execution of the entire program. 11 C++ Functions

12 // The function computes and returns the gross pay // based on the pay rate and hours. Hours over // 40 will be paid 1.5 times the regular pay rate. float GrossPay(float payRate, float hours) { float total; if (hours > REG_HOURS) total = (hours - REG_HOURS)* OVER_TIME * payRate + REG_HOURS * payRate; else total = hours * payRate; return total; } // No input for payRate and hours // Parameters receive values on function call!

13 Passing Parameters main() GrossPay() const float REG_HOURS = 40.0; const float OVER_TIME = 1.5; float GrossPay(float payRate, float hours) { float total; Function call if (hours > REG_HOURS) cin >> rate >> hours; Passing parameters total = (hours - REG_HOURS) // rate: 12.5 * OVER_TIME * payRate 12.5 50

+ REG_HOURS * payRate; // hours: 50 else gross = GrossPay(rate, total = hours * payRate; hours); Returning to main() return total; With return value // display result } int main() { float hours, rate, gross; return 0; } 14

IN Parameter The value of the actual parameter is passed into the function and assigned to the formal parameters. float GrossPay(float payRate, float hours); int main() { ... cin >> rate >> hours; // rate: 12.5 // hours: 45.5 gross = GrossPay(rate, hours); ... } 15 IN Parameters int Largest(int num1, int num2, int num3); cin >> score1 >> score2 >> score3;

max = Largest(score1, score2, score3); void DisplayResult(float avg, float max, float min); // Input scores and compute the highest, // lowest and average DisplayResult(avg, highest, lowest); // The function does output, but IN parameters! float sqrt(float x); 16 Function Parameters In The value of the actual parameter is passed into the function and assigned to the formal parameter. Out The value of formal parameter is passed out of the function and

assigned to the actual parameter. InOut Both In and Out. 17 float GrossPay(float payRate, float hours); int main() { float hours, rate, gross; // Input values in main() cin >> rate >> hours; gross = GrossPay(rate, hours); // display result return 0; } // Q: Can we use a function to input rate and hours? 18 Write a function to input rate and hours

Function Prototype Name: GetInput Type: void Cannot pass two values using the return statement Parameters: rate (payRate), hours (hoursWorked) type: float (Passing values back to calling function) (OUT parameters!) (&) void GetInput(float& payRate, float& hoursWorked); 19 float GrossPay(float payRate, float hours); void GetInput(float& payRate, float& hoursWorked); int main() {

float hours, rate, gross; // Call function GetInput() to get two values GetInput(rate, hours); // Call function GrossPay to get one value gross = GrossPay(rate, hours); // display result return 0; } 20 Function Definition // ------------------------------------------------// The function inputs payRate and hoursWorked and // pass both values back to the calling function. // Parameters: (out, out) // ------------------------------------------------void GetInput(float& payRate, float& hoursWorked) { cout << "Enter pay rate: ";

cin >> payRate; cout << "Enter hours: "; cin >> hoursWorked; return; } // // // // The function does input with prompt, but OUT parameters! How can it pass two values back? Out Parameters: & Statement return can pass only one value back! 21 // ------------------------------------------------// The function computes and returns the gross pay // based on the pay rate and hours. Hours over //

40 will be paid 1.5 times the regular pay rate. // Parameters: (in, in) // ------------------------------------------------float GrossPay(float payRate, float hours) { if (hours > REG_HOURS) payRate = (hours - REG_HOURS) * OVER_TIME * payRate + REG_HOURS * payRate; else payRate = hours * payRate; return payRate; } // No local variable // payRate is used to store the result 22 Reference and Value Parameters float GrossPay(float payRate, float hours); void GetInput(float& payRate, float& hoursWorked);

Value parameter: No & The value of actual parameter is passed to the formal parameter Reference Parameter: & The address of actual parameter is passed to the formal parameter Does the actual parameter change its value when the corresponding formal parameter changes its value? Value parameter (no &): NO Reference parameter (&): YES 23 Value and Reference Parameters GetInput() void GetInput(float& payRate, float& hoursWorked) { cout << "Enter pay rate: "; const float REG_HOURS = 40.0; cin >> payRate; const float OVER_TIME = 1.5; cout << "Enter hours: ";

Passing parameters cin >> hoursWorked; int main() Addresses of rate and hours { return; float hours, rate, gross; } Return control main() GetInput(rate, hours); gross = GrossPay(rate, hours); // display result return 0; } GrossPay()

Passing parameters float GrossPay(float payRate, float hours) { if (hours > REG_HOURS) payRate = (hours - REG_HOURS) * OVER_TIME * payRate + REG_HOURS * payRate; Return control else With value payRate = hours * payRate; 12.5 50 return payRate; 24 } Tracing Functions

Input: 10 45 GetInput(rate, hours); // Reference parameters gross = GrossPay(rate, hours);// Value parameters main() hours rate gross ? ? ? GetInput() & payRate & hoursWorked ? ? Addr of Addr of rate hours

GrossPay() hours payRate ? ? 10.0 45.0 45.0 10.0 475.0 475.0 25 Schedule Program 2 Grace Time: 10 PM, Friday

Style! Name conversion Quiz 4-2 Due 10 pm Thursday (Lab5: next week) Program 3 Optional groups Two students each group Sign group by Friday 26

Recently Viewed Presentations

  • Optimal Resume - Arizona State University

    Optimal Resume - Arizona State University

    On this page, scroll down, you will see Optimal Resume website link. New user-> Register yourself. Else click on-> Existing Users to login. Where to find optimal resume website link? ... MyASU>Campus Services>Jobs & Careers>Sun Devil CareerLink.
  • FLOW OF ENERGY AND NUTRIENTS - Wilson&#x27;s Web Page

    FLOW OF ENERGY AND NUTRIENTS - Wilson's Web Page

    Toxic substances become increasingly concentrated at subsequent trophic levels. ... In humans they can suppress the immune system, disrupt hormones and cause cancers. PCBs and Orcas. Because Orcas live for so long, they accumulate a lot of PCBs.
  • 2019 JOINT AUSTRALASIAN SEXUAL HEALTH AND HIV&AIDS CONFERENCE

    2019 JOINT AUSTRALASIAN SEXUAL HEALTH AND HIV&AIDS CONFERENCE

    XX is a consultant/advisor for and has received research grants from XXX, XXX, XXX, and XXX. Join the Conversation @ASHMMEDIA . #HIVAUS19 #SH19. BACKGROUND/AIMS & METHODS: What is known about this area? Why is this study important? What is the...
  • Diapositiva 1 - milnumb.com

    Diapositiva 1 - milnumb.com

    Entre 1522 y 1810, hay documentadas 77 reales cédulas protegiendo la invención de novedades o su importación desde el extranjero. Muchas versaban sobre aparatos para el beneficio de metales preciosos en las minas americanas, aunque también eran abundantes las referidas...
  • Religions in Germany

    Religions in Germany

    The most important religions in Germany celebrate that. Easter A very important and old festival The Christians celebrate that every year on another day Christmas Also very old and important It´s celebrated on the 24th of December The most popular...
  • English national cuisine: traditions and cultural identity

    English national cuisine: traditions and cultural identity

    The day of a typical Englishman in the course of centuries began with scrambled eggs with bacon, tomatoes, mushrooms and the blood sausage. Traditions. Full English breakfast. To this day, the popular snacks and sandwiches - triangular sandwiches have become...
  • W5 of Computer Engineering (Why, What, When, Where, How)

    W5 of Computer Engineering (Why, What, When, Where, How)

    Draw the circuit in AOI logic. If NAND hardware is chosen, add a circle at the output of each AND gate and at the inputs to all the OR gates. ... Darshan Institute of Engineering & Technology. Converting AND/OR/Invert Logic...
  • CHAPTER 3. AGE AND ACQUISITION - IHMC Public Cmaps

    CHAPTER 3. AGE AND ACQUISITION - IHMC Public Cmaps

    The native language of the learner is not just an interfering factor- it can facilitate learning a second language. The written form of the language could be beneficial. Students could be overwhelmed by language spoken at its "natural speed", and...