Download presentation
Presentation is loading. Please wait.
1
Single-Result Functions Section 5.1 02/25/11
2
Programming Assignment On website.
3
Reading For Today: Sec. 5.1, pp. 157-165 For Monday: Sec. 4.1 & 4.2, pp. 109-122
4
Functions Have discussed math library functions Can create your own functions
5
Example ch5/circle.cpp – Has a function to find the area of a circle. prototype – declares return-type, name, and parameters function call – name and arguments definition – describes how function computes the value it returns
6
Single-Result Function Definition // Comment w/ purpose and preconditions resultType functionName( parameter list) // header { // function body Declarations of local variables Statements to find a result Return statement to send back result }
7
#include //maximum finds the maximum of //three integers, x, y, z //Pre: x, y, and z must be set int maximum(int x, int y, int z); //prototype w/ 3 parameters int main(){ int a,b,c; cout "; cin >> a >> b >> c; cout << "Max is " << maximum(a,b,c)//call with <<endl; //3 arguments return 0; }
8
//FUNCTION DEFINITION- follows main int maximum(int x, int y, int z)//HEADER { //BODY int max = x; if (y > max) max = y; if (z > max) max = z; return max; }
9
Arguments and Parameters Arguments are values sent to function Parameters (formal parameters) are dummy variables that receive the information
10
Arguments and Parameters Must match in type and number – a,b,c & x,y,z – three ints Paired in the order that they appear
11
Local variables double circleArea(double r) { double a; a = PI * pow(r,2.0); return a; } a is a local variable invisible to main program
12
return statement double circleArea(double r) { double a; a = PI * pow(r,2.0); return a; } return a Sends value back to call
13
Boolean Function Returns a bool Can be used in an if statement example – ch5/factor.cpp
14
Function Write a function that takes a date of birth (mo, da, yr) and today's date(mo, da, yr) and returns a person's age in years. Disregard extra months and days. birthday.cpp has program. We need to add the function.
15
Question Write an algorithm for a function that takes an exam score and returns a letter grade. Write the function definition Write a main program to test the function. – Called a driver
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.