Module 6 Working with Functions
@UMBC Training Centers 2013 Why Functions? Code Reuse Code Modularity Hiding Details www.umbctraining.com @UMBC Training Centers 2013
@UMBC Training Centers 2013 Defining a Function return-type name (parameters) { body of code } Parameters are optional, parentheses are not void return-type indicates no return value www.umbctraining.com @UMBC Training Centers 2013
@UMBC Training Centers 2013 Calling a Function void printMessage( ) { printf(“Programming is fun\n”); } int main( ) printMessage(); return 0; www.umbctraining.com @UMBC Training Centers 2013
Parameters, Arguments, Return Values #include <stdio.h> int twoNPlus1( int num ) { num = num * 2; int result = num + 1; return result; } int main( ) int x, y = 33; x = twoNPlus1(y); printf(“x = %d\n”, x); int z = 12 + twoNPlus1(y + 3); printf(“z = %d\n”, z); return 0; www.umbctraining.com @UMBC Training Centers 2013
@UMBC Training Centers 2013 Let’s take a look CB- TwoNPlus1 Function prototype Parameter list Local variables www.umbctraining.com @UMBC Training Centers 2013
An Alternative Program #include <stdio.h> int twoNPlus1( int num ); // function prototype first int main( ) { int x, y = 33; x = twoNPlus1(y); printf(“x = %d\n”, x); int z = 12 + twoNPlus1(x + 3); printf(“z = %d\n”, z); return 0; } int twoNPlus1( int num ) // function definition later num = num * 2; int result = num + 1; return result; www.umbctraining.com @UMBC Training Centers 2013
@UMBC Training Centers 2013 Let’s take a look CB-TwoNPlus1-2 www.umbctraining.com @UMBC Training Centers 2013
@UMBC Training Centers 2013 Predicate Functions A function that returns a Boolean value bool isEven( int num ) { return num % 2 == 0; } ___________________ if (isEven( x )== true) . . . www.umbctraining.com @UMBC Training Centers 2013
@UMBC Training Centers 2013 Exercises Pg 162 #3 – Modify 8.8 (squareroot) to accept “epsilon” as a parameter #7 -- implement and test x_to_the_n(int x, int n) #8 – implement function for quadratic formula #9 -- implement LCM using GCD (given) Give about 30 minutes, just to get started www.umbctraining.com @UMBC Training Centers 2013
Functions Calling Functions main is a function Functions may call other functions Top-Down Design Go over later www.umbctraining.com @UMBC Training Centers 2013
@UMBC Training Centers 2013 Let’s take a look CB – hailstone Let’s look at what happens without prototypes Compiler assumptions – all functions return an int UNLESS you’ve told the compiler otherwise Remove isEven prototype “rebuild” – first a warning about isEven, then an error Typical if you forget a standard header file www.umbctraining.com @UMBC Training Centers 2013
Function Documentation Brief description of what the function does Brief description of each parameter Precondition(s) What must be true for the function to correctly perform its task? Postcondition(s) What will be true after the function completes its task? www.umbctraining.com @UMBC Training Centers 2013
Function Documentation // hailstone // generates the next value in a “hailstone” sequence // Precondition // argument n > 0 // Postcondition // returns n/2 if n is even, 3 * n + 1 if n is odd int hailstone (int n); www.umbctraining.com @UMBC Training Centers 2013
@UMBC Training Centers 2013 Top-Down Design Break a complex problem into smaller parts Break the parts into smaller parts Repeat until parts are easy to do www.umbctraining.com @UMBC Training Centers 2013
@UMBC Training Centers 2013 Why Top-Down? Clarifies the problem Each part is less complex Parts may be reusable More than one person may work on the problem www.umbctraining.com @UMBC Training Centers 2013
@UMBC Training Centers 2013 Example Complex Problem We own a basement waterproofing company A section of town (zip code 12345) has recently had a flood We want to send pamphlets to those potential customers www.umbctraining.com @UMBC Training Centers 2013
@UMBC Training Centers 2013 Top-Level Get complete customer list from a file Sort the list according to zip code Extract customers from zip code 12345 and write them to new file Print an envelope for these customers Main Read Sort Select Print www.umbctraining.com @UMBC Training Centers 2013
@UMBC Training Centers 2013 Top-Down Design www.umbctraining.com @UMBC Training Centers 2013
@UMBC Training Centers 2013 More Levels? Should any of these steps be broken down further? Maybe. How do you know? Is it easy to write an algorithm for each step? If not, break it down again When you’re comfortable with the steps write the code for each one The code for each step is a function www.umbctraining.com @UMBC Training Centers 2013
@UMBC Training Centers 2013 Let’s take a look C::B Program8-8 Pg 132 Drawn what that program would look like in a Top-Down design www.umbctraining.com @UMBC Training Centers 2013
Done for Functions Part 1 Exercises on the Next Page www.umbctraining.com @UMBC Training Centers 2013
@UMBC Training Centers 2013 Exercises FunctionProblems.docx Ex1 – MathIsFun – 4 different easy math-related functions Ex2 – NumberTheory – predicate functions (square, perfect, prime) Ex3 – Combinations – C(n, k), n! Ex4 – Rectangles (area, perimeter, isSquare (rhombus) www.umbctraining.com @UMBC Training Centers 2013
@UMBC Training Centers 2013 Passing an Array Parameters Do not specify array size in brackets Pass array size as separate parameter Arguments Name of the array is passed to function Specifies the memory address of start of the array Passed by reference Changes to array parameter in the function’s code also changes the array argument in the calling code Size of array passed by value www.umbctraining.com @UMBC Training Centers 2013
Array Parameter Example int sumArray(int a[], int size){ int sum = 0; for(int k = 0; k < size; k++) sum += a[k]; return sum; } int main( ){ int arraySum; int ages[5] = {6, 4, 12, 11, 22}; int IQs[6] = {100, 93, 99, 120, 89, 103}; arraySum = sumArray(ages, 5); printf(“sum of ages = %d\n”, arraySum); arraySum = sumArray(IQs, 6); printf(“sum of IQs = %d\n”, arraySum); return 0; www.umbctraining.com @UMBC Training Centers 2013
@UMBC Training Centers 2013 Let’s take a look C::B - arrays2 Usually have to pass the size too, otherwise the function doesn’t know how big the array is – reusable with arrays of any size put size in array parameter and run again www.umbctraining.com @UMBC Training Centers 2013
@UMBC Training Centers 2013 Searching an Array Examine every element of the array to determine if it’s the one we want -- “Linear” Search bool linearSearch( int a[ ], int size, int target) { bool found = false; int j = 0; while (j < size && !found) { if (a[j] == target) found = true; ++j; } return found; www.umbctraining.com @UMBC Training Centers 2013
@UMBC Training Centers 2013 Sorting An Array Very common operation Many algorithms – some slow, some fast Exchange sort Compare first element with second If 2nd is smaller, swap them Compare first element with third If 3rd is smaller, swap them Continue comparing first element with all others When complete, first element will be smallest Repeat steps above for 2nd element, then 3rd, then 4th and so on. When complete, array will be sorted. www.umbctraining.com @UMBC Training Centers 2013
@UMBC Training Centers 2013 Binary Search Fast search for specified target element Requires sorted array Algorithm Look at the middle element If the middle element is the target, stop If the target > middle element, look at the middle element of the upper “subarray” If the target < middle element, look at the middle element of the lower“subarray” Continue until found or all elements examined www.umbctraining.com @UMBC Training Centers 2013
Variable Length Array Parameter Same as an “ordinary” array Array parameter does not specify size Size is separate parameter int sumElements(int a[ ], int nrElements); www.umbctraining.com @Copyright UMBC Training Centers 2012
Functions and Variables Automatic local variables “come to life” and reinitialized when function starts “disappear” when function ends Global variables Usable anywhere in the file NOT recommended Reduces function generality Prone to errors OK for constant variables and arrays www.umbctraining.com @UMBC Training Centers 2013
Functions and Variables Automatic local variables “come to life” and reinitialized when function starts “disappear” when function ends Static local variables Exist for the duration of your program Value retained between calls to the function Global variables Usable anywhere in the file NOT recommended Reduces function generality Prone to errors OK for constant variables and arrays www.umbctraining.com @UMBC Training Centers 2013
@UMBC Training Centers 2013 Recursive Problems A recursive problem is one that is written in terms itself The solution to the simplest problem is known Larger problems are redefined in terms of a smaller problem www.umbctraining.com @UMBC Training Centers 2013
@UMBC Training Centers 2013 Recursive Examples Sum from 0 to 5 Sum from 0 to 5 = 5 + sum from 0 to 4 Sum from 0 to 4 = 4 + sum from 0 to 3 Sum from 0 to 3 = 3 + sum from 0 to 2 Sum from 0 to 2 = 2 + sum from 0 to 1 Sum from 0 to 1 = 1 + sum from 0 to 0 Sum from 0 to 0 = 0 Sum from 0 to k Sum from 0 to k = k + sum from 0 to k - 1 www.umbctraining.com @UMBC Training Centers 2013
@UMBC Training Centers 2013 Recursive Examples The Nth Fibonacci Number Fib(0) = 1 Fib(1) = 1 Fib(N) = Fib( N – 1 ) + Fib( N – 2 ) if N > 1 The largest element in array a[ ] of size K a[0] if K = 1 Last element (a[k-1]) or largest of a[0]…a[k-2] www.umbctraining.com @UMBC Training Centers 2013
@UMBC Training Centers 2013 Recursive Functions A function that Can determine the answer of the smallest problem Finds the answer to the larger problem by calling itself to find the answer to smaller problems www.umbctraining.com @UMBC Training Centers 2013
@UMBC Training Centers 2013 Binary Search Requires sorted array Algorithm Compare target with middle element If found, we’re done If target less than middle element look in first half of the array Else target is greater than middle element, so look in second half of the array Got to 1. www.umbctraining.com @UMBC Training Centers 2013
@Copyright UMBC Training Centers 2012 Streams In C, all I/O is performed using streams A sequence of bytes that “flows” between your program and an I/O device A high level abstraction representing a channel to a file or I/O device Some I/O functions such as printf and scanf use the standard streams (stdout/stdin) by default opened when your program begins execution www.umbctraining.com @Copyright UMBC Training Centers 2012
@Copyright UMBC Training Centers 2012 File I/O Files must be opened to create a stream before I/O may be performed Functions that perform I/O with files are similar to those for stdout/stdin, but must specify the stream to which the I/O is performed Streams are designated as type FILE* www.umbctraining.com @Copyright UMBC Training Centers 2012
@Copyright UMBC Training Centers 2012 Opening a Stream FILE* fopen(char fileName[], char mode[]); fileName is the path to the file Windows: C:\folder\filename Unix: /directory/filename mode is a 1- or 2-character string Return value FILE* is the stream used as the argument to other functions Returns NULL if an error occurs www.umbctraining.com @Copyright UMBC Training Centers 2012
@Copyright UMBC Training Centers 2012 Closing a Stream fclose(FILE* stream); stream is FILE* returned from fopen( ) www.umbctraining.com @Copyright UMBC Training Centers 2012
Formatted Stream Output fprintf(FILE* stream, “formatString”, var1, var2,…); stream is FILE* returned from fopen( ) “formatString” is the same as in printf() www.umbctraining.com @Copyright UMBC Training Centers 2012
Formatted Stream Input fscanf(FILE* stream, “formatString”, &var1, &var2,…); stream is FILE* returned from fopen( ) “formatString” is the same as in scanf() Returns EOF if error or end-of-file www.umbctraining.com @Copyright UMBC Training Centers 2012
@UMBC Training Centers 2013 Exercises tracing.docx trace function calls and provide output Textbook Chapter 8 – pg 162 #11 – part of Ex0 #13 -- Modify 8.12 (ex sort) to have new parameter indicating direction of sort Ex0 – FunWithArrays – various functions with array parameter www.umbctraining.com @UMBC Training Centers 2013
@UMBC Training Centers 2013 If you have any comments about this video, please use the contact information in your registration materials to let us know. www.umbctraining.com @UMBC Training Centers 2013