Presentation is loading. Please wait.

Presentation is loading. Please wait.

Module 6 Working with Functions

Similar presentations


Presentation on theme: "Module 6 Working with Functions"— Presentation transcript:

1 Module 6 Working with Functions

2 @UMBC Training Centers 2013
Why Functions? Code Reuse Code Modularity Hiding Details @UMBC Training Centers 2013

3 @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 @UMBC Training Centers 2013

4 @UMBC Training Centers 2013
Calling a Function void printMessage( ) { printf(“Programming is fun\n”); } int main( ) printMessage(); return 0; @UMBC Training Centers 2013

5 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; @UMBC Training Centers 2013

6 @UMBC Training Centers 2013
Let’s take a look CB- TwoNPlus1 Function prototype Parameter list Local variables @UMBC Training Centers 2013

7 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; @UMBC Training Centers 2013

8 @UMBC Training Centers 2013
Let’s take a look CB-TwoNPlus1-2 @UMBC Training Centers 2013

9 @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) . . . @UMBC Training Centers 2013

10 @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 @UMBC Training Centers 2013

11 Functions Calling Functions
main is a function Functions may call other functions Top-Down Design Go over later @UMBC Training Centers 2013

12 @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 @UMBC Training Centers 2013

13 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? @UMBC Training Centers 2013

14 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); @UMBC Training Centers 2013

15 @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 @UMBC Training Centers 2013

16 @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 @UMBC Training Centers 2013

17 @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 @UMBC Training Centers 2013

18 @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 and write them to new file Print an envelope for these customers Main Read Sort Select Print @UMBC Training Centers 2013

19 @UMBC Training Centers 2013
Top-Down Design @UMBC Training Centers 2013

20 @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 @UMBC Training Centers 2013

21 @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 @UMBC Training Centers 2013

22 Done for Functions Part 1
Exercises on the Next Page @UMBC Training Centers 2013

23 @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) @UMBC Training Centers 2013

24 @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 @UMBC Training Centers 2013

25 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; @UMBC Training Centers 2013

26 @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 @UMBC Training Centers 2013

27 @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; @UMBC Training Centers 2013

28 @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. @UMBC Training Centers 2013

29 @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 @UMBC Training Centers 2013

30 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); @Copyright UMBC Training Centers 2012

31 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 @UMBC Training Centers 2013

32 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 @UMBC Training Centers 2013

33 @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 @UMBC Training Centers 2013

34 @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 @UMBC Training Centers 2013

35 @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] @UMBC Training Centers 2013

36 @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 @UMBC Training Centers 2013

37 @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. @UMBC Training Centers 2013

38 @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 @Copyright UMBC Training Centers 2012

39 @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* @Copyright UMBC Training Centers 2012

40 @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 @Copyright UMBC Training Centers 2012

41 @Copyright UMBC Training Centers 2012
Closing a Stream fclose(FILE* stream); stream is FILE* returned from fopen( ) @Copyright UMBC Training Centers 2012

42 Formatted Stream Output
fprintf(FILE* stream, “formatString”, var1, var2,…); stream is FILE* returned from fopen( ) “formatString” is the same as in printf() @Copyright UMBC Training Centers 2012

43 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 @Copyright UMBC Training Centers 2012

44 @UMBC Training Centers 2013
Exercises tracing.docx trace function calls and provide output Textbook Chapter 8 – pg 162 #11 – part of Ex0 # Modify 8.12 (ex sort) to have new parameter indicating direction of sort Ex0 – FunWithArrays – various functions with array parameter @UMBC Training Centers 2013

45 @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. @UMBC Training Centers 2013


Download ppt "Module 6 Working with Functions"

Similar presentations


Ads by Google