Presentation is loading. Please wait.

Presentation is loading. Please wait.

Functions that return a value

Similar presentations


Presentation on theme: "Functions that return a value"— Presentation transcript:

1 Functions that return a value
Functions II Functions that return a value

2 The Purpose of a Function
To perform some encapsulated task. A task “delegated” from the main program. To isolate the main program from complex details. To break details into manageable units.

3 Functions in Everyday Life
Changing the oil in your car Bounded task Isolate complexity (and mess). Often delegated (British-American Motors) Grocery shopping

4 Returned Values and Side Effects
Two types of functions Those that return a value Those that produce side effects. A “side effect” is an effect on something external to the program and its data, e.g. printer, CRT, sound card. printf() is called for its side effects. getchar() is called for its return value.

5 A function that returns a value
/*************************************************** ** AverageTwo ** calculates and returns the average of num1 and num2 ****************************************************/ float AverageTwo (int num1, int num2) { float average; average = (num1 + num2) / 2.0; return average; }

6 Using AverageTwo #include <stdio.h>
float AverageTwo (int num1, int num2); main ( ) { float average; int num1 = 5, num2 = 8; average = AverageTwo (num1, num2); printf (“The average of %d and %d is %f\n”, num1, num2, average); } float AverageTwo (int num1, int num2) average = (num1 + num2) / 2.0; return average;

7 Function as Data Transformation
Arguments Result A function is a method to transform arguments into results

8 Functions as Local Environments
Functions have their own scope Variables defined within a function are “local” to the function. They are not defined outside the function. They are usually re-initialized each time the function is executed.

9 Arguments Arguments are passed “by value”
The function gets the value of the argument, not its name or storage location. Functions can’t change the value of their arguments. The argument values are matched to the formal parameters in the order they are passed The parameters are declarations of variables known only inside the function. The values passed are assigned to those variables.

10 Arguments #include <stdio.h> int foo(int arg, int new); main() {
int res, arg=3; /* a demonstration value*/ res = demo(arg, 7); printf(“arg: %d, res: %d\n”, arg, res); return(); } int foo(int arg, int new) arg = new; return (arg);

11 Okay, I Lied There are ways to pass values back through parameters, but they require “pointers”, a topic for a later lecture.

12 Local Variables Generally, functions “see” only their own local variables. This includes main ( ) The parameters of a function are declarations of local variables. Other local variables can be declared within the function

13 Local Variables The variables a,b,c,x,y are known only in foo.
/* this is a function */ int foo(int a, int b) { int c; float x, y; ...<lots of stuff>... return(result); } a,b,c,x,y undefined out here The variables a,b,c,x,y are known only in foo.

14 Local Variables #include <stdio.h> float AverageTwo (int a, int b) float AverageTwo (int num1, int num2); { main ( ) float average; { float average; average = (a + b) / 2.0; int num1 = 5, num2 = 8; return average; } average = AverageTwo (num1, num2); printf (“The average of “); printf (“%d and %d is %f\n”, num1, num2, average); num num2 average a b average int int float int int float

15 More about Local Variables
#include <stdio.h> void AddOne (int num1); main () { int num1 = 5; printf (“num1 = %d\n”, num1); AddOne (num1); printf (“In main: “); exit(); } void AddOne(int num) { int num1; num1 = num++; printf(“In AddOne: num1 = %d\n”, num1); return; } In main: num1 = ? In AddOne: num1 = ?

16 Data Types and Conversion Specifiers
Data Type printf scanf conversion conversion float %f %f double %f %lf long double %Lf %Lf int %d %d long int %ld %ld unsigned int %u %u unsigned long int %lu %lu short int %hd %hd char %c %c

17 Header Files Header files contain function prototypes for all of the functions found in the corresponding library It also contains definitions of constants and data types used in that library

18 int gradeSmasher(int Midt, int Proj, int HW, int Final);
Prototype An example function call telling the compiler the number and type of arguments to expect int gradeSmasher(int Midt, int Proj, int HW, int Final);

19 Commonly Used Header Files
header file Contains function prototypes for <stdio.h> the standard input/output library functions & information used by them <math.h> the math library functions (sin, cos, etc) <stdlib.h> the conversion of number to text, text to number, memory allocation, random numbers and other utility functions <time.h> manipulating time and date <ctype.h> functions that test characters for certain properties and that can convert case others see page 159 of text

20 Math Library double sqrt (double x); returns the square root of x
double pow (double x, double y) x raised to the y power pow (3.0, 2.0) is 9.0 pow (8.0, 0.33) is 2.0 double sin (double x) trigonometric sine of x (x in radians) All math library functions take doubles as arguments and return doubles others on page 151 of text Remember these functions don’t compute actual values, but rational approximations. Usually very close, but ...

21 Common stdlib functions
void exit (int x); prematurely ends program execution void srand (unsigned int x); “seeds” the random number generator with an unsigned integer that is used to start the calculations that generate the pseudo-random number srand (200); int rand (void); returns an unsigned pseudo-random integer in the range of 0 to or 0 to depending on the size of an integer on the system your on num = rand();

22 Computers Don’t Generate Random Numbers
Anyone who attempts to generate random numbers by deterministic means is, of course, living in a state of sin. -- Jon von Neuman

23 Manipulating what rand() returns
Since rand() returns unsigned integers in a large range, we often have to manipulate the return value to suit our purposes Suppose we want only random numbers in the range from 0 to 5 num = rand () % 6 How about 1 to 6? num = 1 + rand( ) % 6; How about 5 to 20? num = 5 + rand ( ) % 16;

24 srand ( ) and rand ( ) The pseudo-random number generator needs an unsigned int as it’s seed Although it produces what appear to be random numbers, if we use the same seed, we get the same sequence of random numbers To get different random numbers each time we run our program, we have to give a different seed each time

25 srand ( ) and rand ( ) The pseudo-random number generator needs an unsigned int as its seed Although it produces what appear to be random numbers, if we use the same seed, we get the same sequence of random numbers To get different random numbers each time we run our program, we have to give a different seed each time

26 srand ( ) and rand ( ) #include <stdio.h>
#include <stdlib.h> #define SEED 67 main ( ) { int i, num; srand (SEED); for (i = 0; i < 5; i++) num = rand ( ); num = 1 + num % 6; printf (“%d\n”, num); } Since we are always using the value 67 as the seed for our pseudo-random number generator, the same sequence of numbers will be produced whenever we run our program.

27 <time.h> One of the most useful functions in the time library is the time() function It returns the time of day as seconds Since this number is different every time we call it, it’s greatest use is as a seed for the random number generator Each time we run our program, a different sequence of random numbers will be produced srand (time ( NULL) );

28 The Joys and Uses of Pseudo-Randomness
Modeling and simulation Cryptography Randomness is bad in: debugging: set a constant seed so you can trace constant errors. repetitive simulation: testing the same model with slightly different parameters.


Download ppt "Functions that return a value"

Similar presentations


Ads by Google