Today’s Lecture Predefined Functions
Introduction to Functions Reuse Issue Building Blocks of Programs Two types of functions Predefined Programmer defined
Predefined Functions Predefined in the libraries Example: Calculate the square root of a number double sqrt(double) is defined in library Three parts: Return type Function name Argument list
The Function Call To use: Must "#include" the library that defines the function Provide required arguments Example: double root; root = sqrt (9.0); The argument in a function call (9.0) can be a literal, a variable, or an expression
A Larger Example: Display 3.1 A Predefined Function That Returns a Value (1 of 2)
A Larger Example: Display 3.1 A Predefined Function That Returns a Value (2 of 2)
Predefined Functions Libraries full of functions for our use! Two types: Those that return a value Those that do not (void) Must "#include" appropriate library e.g., , (Original "C" libraries) (for cout, cin)
More Predefined Functions #include abs()// Returns absolute value of an int pow(x, y) Returns x to the power y Notice this function receives two arguments A function can have any number of arguments, of varying data types
Even More Math Functions: Display 3.2 Some Predefined Functions (1 of 2)
Even More Math Functions: Display 3.2 Some Predefined Functions (2 of 2)
Predefined Void Functions No returned value Performs an action, but sends no "answer" All aspects same as functions that "return a value" They just don’t return a value! Example exit(int)
Random Number Generator Return "randomly chosen" number Used for simulations, games rand() Takes no arguments Returns value between 0 & RAND_MAX Scaling Squeezes random number into smaller range rand() % 6 Returns random value between 0 & 5 Shifting rand() % Shifts range between 1 & 6 (e.g., die roll)
Random Examples Random double between 0.0 & 1.0: rand()/(double)(RAND_MAX) Type cast used to force double-precision division Random int between 1 & 6: rand() % "%" is modulus operator (remainder) Random int between 10 & 20: rand() %
Pseudorandom Numbers The function rand() takes no arguments and returns a integer in the rage of [0, RAND_MAX] Numbers appears to be random, but really not. It is called pseudorandom numbers The sequence of the random is determined by seed
Pseudorandom Numbers If you start rand with the same seed, you will produce the same sequence random number To get true random number, use function srand to reset seed. void srand(int)
Character Functions Include bool isdigit(char) bool isalpha(cha) bool isspace(char) bool islower(char) bool isupper(char) int tolower(char) int toupper(char)