Module 6 Working with Functions

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 6 Functions.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 6: Functions by.
Guide To UNIX Using Linux Third Edition
 2007 Pearson Education, Inc. All rights reserved C Arrays.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 6 Functions.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Chapter 6: Functions Starting Out with C++ Early Objects
Chapter 13 Recursion. Learning Objectives Recursive void Functions – Tracing recursive calls – Infinite recursion, overflows Recursive Functions that.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6: Functions Starting Out with C++ Early Objects Seventh Edition.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
CMSC 104, Version 8/061L17Top-DownDesign.ppt Top-Down Design Topics Top-Down Design Top-Down Design Examples The Function Concept Reading Sections 3.1.
Basic I/O in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Stream Model of I/O header file: A stream provides a connection.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
1 Brief Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6: Functions Starting Out with C++ Early Objects Eighth Edition.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
1 UMBC CMSC 104, Section Fall 2002 Functions, Part 1 of 3 Topics Top-down Design The Function Concept Using Predefined Functions Programmer-Defined.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
Functions, Part 1 of 3 Topics  Using Predefined Functions  Programmer-Defined Functions  Using Input Parameters  Function Header Comments Reading 
Chapter 6 Functions. 6-2 Topics 6.1 Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
CS314 – Section 5 Recitation 9
Searching and Sorting Arrays
Chapter 13 Recursion Copyright © 2016 Pearson, Inc. All rights reserved.
Programming Logic and Design Seventh Edition
Functions Course conducted by: Md.Raihan ul Masood
Recursion: The Mirrors
Algorithms IV Top-Down Design.
Bill Tucker Austin Community College COSC 1315
Chapter 9: Searching, Sorting, and Algorithm Analysis
Algorithms Problem: Write pseudocode for a program that keeps asking the user to input integers until the user enters zero, and then determines and outputs.
Functions Separate Compilation
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Chapter 5 - Functions Outline 5.1 Introduction
Data Structures Recursion CIS265/506: Chapter 06 - Recursion.
Chapter 5 - Functions Outline 5.1 Introduction
2011/11/20: Lecture 15 CMSC 104, Section 4 Richard Chang
Chapter 5 - Functions Outline 5.1 Introduction
2008/11/05: Lecture 15 CMSC 104, Section 0101 John Y. Park
Algorithm design and Analysis
C Arrays.
Chapter 6 - Functions Outline 5.1 Introduction
6 Chapter Functions.
Functions, Part 1 of 3 Topics Using Predefined Functions
Searching and Sorting Arrays
File Input and Output.
Algorithms IV Top-Down Design.
Functions, Part 1 of 3 Topics Using Predefined Functions
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Searching and Sorting Arrays
IPC144 Introduction to Programming Using C Week 4 – Lesson 2
Module 12 Input and Output
Algorithms, Part 3 of 3 Topics Top down-design Structure charts
Functions, Part 1 of 3 Topics Using Predefined Functions
2008/11/05: Lecture 15 CMSC 104, Section 0101 John Y. Park
Standard Version of Starting Out with C++, 4th Edition
Algorithms, Part 3 of 3 Topics Top down-design Reading
Module 5 Working with Arrays
Module 8 – Searching & Sorting Algorithms
Presentation transcript:

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