1 ICS103 Programming in C Ch3: Top-Down Design with Functions.

Slides:



Advertisements
Similar presentations
Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Advertisements

Modular Programming With Functions
Week 4 – Functions Introduction. Functions: Purpose Breaking a large problem into a series of smaller problems is a common problem- solving technique.
Chapter 3 Top-Down Design with Functions. 3-2 Outline 3.1 BUILDING PROGRAMS FROM EXISING INFORMATION –CASE STUDY: FINDING THE AREA AND CIRCUMFERENCE OF.
ICS103: Programming in C 3: Top-Down Design with Functions
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
1 ICS103 Programming in C Lecture 5: Introduction to Functions.
CS 201 Functions Debzani Deb.
Chapter 3 Top-Down Design with Functions Dr. J.-Y. Pan Dept. Comm. Eng. Nat. Chung Cheng Univ.
Chapter 6: User-Defined Functions I
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
 2007 Pearson Education, Inc. All rights reserved C Functions.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
ICS103 Programming in C Lecture 9: Functions I
CS 201 Functions Debzani Deb.
Top-Down Design with Functions 4 What do programmer’s (not programs!) use as input to the design of a program? –Documentation Problem definition Requirements.
Chapter 6: User-Defined Functions I
1 CSC 1401 S1 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
 2000 Prentice Hall, Inc. All rights reserved. Functions in C Outline 1Introduction 2Program Modules in C 3Math Library Functions 4Functions 5Function.
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
Lecture 5: Modular Programming (functions – part 1 BJ Furman 27FEB2012.
CP104 Introduction to Programming Top-down design with functions Lecture 6-8 __ 1 Top-Down Design with Functions C Library functions Case studies Top-down.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
Lecture 9m: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept.
1 Introduction to Computers II Lecture 4 Dr. Mehmet Demirer Dr. Seniha Esen Yuksel.
Chapter 6: Modularity Using Functions. In this chapter, you will learn about: – Function and parameter declarations – Returning a single value – Returning.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Functions in C Outline 1Introduction 2Program Modules in C 3Math Library Functions 4Functions 5Function Definitions 6Function Prototypes 7Header Files.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Chapter 6: User-Defined Functions
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
CHAPTER 5 FUNCTIONS I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
1 ICS103 Programming in C Lecture 7: Introduction to Functions.
Functions Top-down design Breaking a complex problem into smaller parts that we can understand is a common practice. The process of subdividing a problem.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 6 User-Defined Functions I. Objectives Standard (predefined) functions What are they, and How to use them User-Defined Functions Value returning.
chap3 Chapter 3 Top-Down Design with Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
KIC/Computer Programming & Problem Solving 1.  Introduction  Program Modules in C  Math Library Functions  Functions  Function Definitions  Function.
Chapter 3 Top-Down Design with Functions Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National.
Lecture 10: Modular Programming (functions) B Burlingame 13 April 2015.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 3 : Top Down Design with Functions By Suraya Alias.
1 ICS103 Programming in C Lecture 8: Functions I.
Chapter 3: User-Defined Functions I
CISC105 – General Computer Science Class 2 – 6/7/2006.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Programming Fundamentals Enumerations and Functions.
1 ICS103 Programming in C Lecture 9: Functions I.
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Chapter 6: User-Defined Functions I
Function Topic 4.
Functions, Part 2 of 2 Topics Functions That Return a Value
Chapter 6 Modular Programming Dr. J.-Y. Pan Dept. Comm. Eng.
CSCI 161: Introduction to Programming Function
User-Defined Functions
Chapter 5 - Functions Outline 5.1 Introduction
Lec8.
Chapter 6: User-Defined Functions I
6 Functions.
Top-Down Design with Functions
Top-Down Design with Functions
Presentation transcript:

1 ICS103 Programming in C Ch3: Top-Down Design with Functions

O UTLINE Introduction to Functions Predefined Functions and Code Reuse Functions without Arguments void Functions with Arguments Functions with Input Arguments and a Single Result Advantages of Using Function Subprograms 2

I NTRODUCTION TO F UNCTIONS So far, we have learnt how to use operators, +, -, *, / and % to form simple arithmetic expressions. However, we are not yet able to write many other mathematical expressions we are used to. For example, we cannot yet represent any of the following expressions in C: C does not have operators for “square root”, “absolute value”, sine, log, etc. Instead, C provides program units called functions to carry out these and other mathematical operations. 3

I NTRODUCTION TO F UNCTIONS … A function can be thought of as a black box that takes one or more input arguments and produces a single output value. For example, the following shows how to use the sqrt function that is available in the standard math library: y = sqrt (x); If x is 16.0, the function computes the square root of The result, 4.0, is then assigned to the variable y. The expression part of the assignment statement is called function call. Another example is: z = sqrt (w); If w = 9.0, z is assigned , which is

1-5 F IGURE 3.6 F UNCTION SQRT AS A “B LACK B OX ”

1-6 F IGURE 3.7 S QUARE R OOT P ROGRAM

1-7 F IGURE 3.7 S QUARE R OOT P ROGRAM ( CONT ’ D )

P REDEFINED F UNCTIONS AND C ODE R EUSE The primary goal of software engineering is to write error-free code. Reusing code that has already been written & tested is one way to achieve this. --- ”Why reinvent the wheel?” C promotes reuse by providing many predefined functions. e.g. Mathematical computations. Input/Output: e.g. printf, scanf 8

P REDEFINED F UNCTIONS AND C ODE R EUSE … The next slide lists some commonly used mathematical functions (Table 3.1 in the book) Appendix B gives more extensive lists of standard library functions. In order to use a function, you must use #include with the appropriate library. Example, to use function sqrt you must include math.h. If a function is called with a numeric argument that is not of the argument type listed, the argument value is converted to the required type before it is used. Conversion of type int to type double cause no problems Conversion of type double to type int leads to the loss of any fractional part. Make sure you look at documentation for the function so you use it correctly. 9

S OME M ATHEMATICAL L IBRARY F UNCTIONS 10 FunctionHeader File Purpose ArgumentsResult abs(x) fabs(x) Returns the absolute value of its integer argument x. Returns the absolute value of its double argument x. int double int double sin(x),cos(x), tan(x) Returns the sine, cosine, or tangent of angle x. double (in radians) double log(x) Returns the natural log of x. double (must be positive) double log10(x) Returns base 10 log of x double (positive)double pow(x, y) Returns x y double, doubledouble sqrt(x) double (must be positive) double

11

E XAMPLE We can use C functions pow and sqrt to compute the roots of a quadratic equation in x of the form: If the discriminant ( b 2 – 4 ac ) is greater than zero, the two roots are defined as: In C, these two roots are computed as: /* compute two roots, root_1 and root_2, for disc > 0.0 */ disc = pow(b, 2) - 4 * a * c; root_1 = (-b + sqrt(disc)) / (2 * a); root_2 = (-b - sqrt(disc)) / (2 * a); 12

1-13 F UNCTIONS WITHOUT A RGUMENTS F IGURE 3.14 P ROGRAM TO D RAW A S TICK F IGURE

1-14 F IGURE 3.14 P ROGRAM TO D RAW A S TICK F IGURE ( CONT ’ D )

1-15 F IGURE 3.14 P ROGRAM TO D RAW A S TICK F IGURE ( CONT ’ D )

F UNCTION P ROTOTYPES Like other identifiers in C, a function must be declared before it can be used in a program. To do this, you can add a function prototype before main to tell the compiler what functions you are planning to use. A function prototype tells the C compiler: 1. The data type the function will return For example, the sqrt function returns a type of double. 2. The function name 3. Information about the arguments that the function expects. The sqrt function expects a double argument. So the function prototype for sqrt would be: double sqrt(double); 16

F UNCTION P ROTOTYPES : VOID F UNCTIONS void draw_circle(void); is a void function void function - does not return a value The function just does something without communicating anything back to its caller. If the arguments are void as well, it means the function doesn’t take any arguments. Now, we can understand what our main function means: int main(void) This means that the function main takes no arguments, and returns an int 17

F UNCTION D EFINITION The prototype tells the compiler what arguments the function takes and what it returns, but not what it does. We define our own functions just like we do the main function Function Header – The same as the prototype, except it is not ended by the symbol ; Function Body – A code block enclosed by { }, containing variable declarations and executable statements. In the function body, we define what actually the function does In this case, we call printf 3 times. Because it is a void function, we can omit the return statement. Control returns to main after the instructions are displayed. 18

P LACEMENT OF F UNCTIONS IN A PROGRAM In general, we will declare all of our function prototypes at the beginning (after #include or #define ) This is followed by the main function After that, we define all of our functions. However, this is just a convention. As long as a function’s prototype appears before it is used, it doesn’t matter where in the file it is defined. The order we define them in does not have any impact on how they are executed 19

E XECUTION O RDER OF F UNCTIONS Execution order of functions is determined by the order of execution of the function call statements. Because the prototypes for the function subprograms appear before the main function, the compiler processes the function prototypes before it translates the main function. The information in each prototype enables the compiler to correctly translate a call to that function. After compiling the main function, the compiler translates each function subprogram. At the end of a function, control always returns to the point where it was called. 20

1-21 F IGURE 3.15 F LOW OF C ONTROL B ETWEEN THE MAIN F UNCTION AND A F UNCTION S UBPROGRAM

P ROGRAM S TYLE Each function should begin with a comment that describes its purpose. If the function subprograms were more complex, we would include comments on each major algorithm step just as we do in function main. It is recommended that you put prototypes for all functions at the top, and then define them all after main. 22

T YPES OF F UNCTIONS We use function arguments to communicate with the function. There are two types of function arguments: Input arguments – ones that are used to pass information from the caller (such as main function) to the function. Output arguments – ones that return results to the caller from the function. [we shall learn about these in chapter 6] Types of Functions No input arguments, no value returned – void functions without arguments Input arguments, no value returned - void functions with arguments. Input arguments, single value returned. Input arguments, multiple value returned [chapter 6] 23

VOID F UNCTIONS WITH I NPUT A RGUMENTS … A function may take one or more arguments as input but returns no result. Such functions should be declared as void, but each argument should be declared in the bracket following the function name An argument is declared in the same way as variables (its type followed by the name of the argument). Example: void print_rboxed(double rnum); If there are more than one argument, they should be separated by comma. Example: void draw_rectangle(int length, int width); The following function example displays its argument value in a rectangular box. 24

1-25 F IGURE 3.18 F UNCTION PRINT _ RBOXED AND S AMPLE R UN

1-26 F IGURE 3.18 F UNCTION PRINT _ RBOXED AND S AMPLE R UN ( CONT ’ D )

1-27 F IGURE 3.19 E FFECT OF E XECUTING PRINT _ RBOXED (135.68);

A CTUAL A RGUMENTS & F ORMAL P ARAMETERS Actual argument : an expression used inside the parentheses of a function call. Formal parameter : An identifier that represents a corresponding actual argument in a function definition. Actual argument can be any expression that evaluates to a value expected by the function: x, 125.5, x+y, etc. 28 When the function call is encountered at run-time, the expression for the actual argument is first evaluated, the resulting value is assigned to the formal parameter, then the function is executed. Arguments make functions more versatile because they enable a function to manipulate different data each time it is called.

F UNCTIONS WITH I NPUT A RGUMENTS AND A S INGLE R ESULT By far, the must common types of functions in C are those that takes one or more arguments and return a single result. 29 For example, virtually all the functions in the library, sqrt, log, abs, sin, cos, etc. are in this category. Unlike void functions, for which the function call is a statement on its own, functions that return a single result are often called as part of another expression. To declare these types of function, instead of void, the function name is preceded by the type of result the function returns (int, double, char, etc.).

1-30 F IGURE 3.21 F UNCTIONS FIND _ CIRCUM AND FIND _ AREA

1-31 F IGURE 3.22 E FFECT OF E XECUTING CIRCUM = FIND _ CIRCUM ( RADIUS );

F UNCTIONS WITH M ULTIPLE A RGUMENTS Below is a function that multiplies its first argument by 10 raised to the power of its second argument. Function call scale(2.5, 2) returns the value

1-33 F IGURE 3.24 T ESTING F UNCTION SCALE

A RGUMENT L IST C ORRESPONDENCE When using multiple-argument functions, the number of actual argument used in a function call must be the same as the number of formal parameters listed in the function prototype. The order of the actual arguments used in the function call must correspond to the order of the parameters listed in the function prototype. Each actual argument must be of a data type that can be assigned to the corresponding formal parameter with no unexpected loss of information. 34

T HE F UNCTION D ATA A REA Each time a function call is executed, an area of memory is allocated for storage of that function’s data. Included in the function data area are storage cells for its formal parameters and any local variables that may be declared in the function. Local Variables : variable declarations within a function body. Can only be used from within the function they are declared in – no other function can see them These variables are created only when the function has been activated and become undefined after the call. The function data area is always lost when the function terminates. It is recreated empty when the function is called again. So if you set a local variable value, that value will be reset again next time the function is called. 35

1-36 F IGURE 3.25 D ATA A REAS A FTER C ALL SCALE ( NUM _1, NUM _2);

T ESTING F UNCTIONS U SING D RIVERS A function is an independent program module As such, it can be tested separately from the program that uses it. To run such a test, you should write a short piece of code called driver that defines the function arguments, calls the functions, and displays the value returned. As long as you do not change the interface, your function can be reused. 37

W HY DO WE USE F UNCTIONS ? There are two major reasons: 1. A large problem can be solved easily by breaking it up into several small problems and giving the responsibility of a set of functions to a specific programmer. It is easer to write two 10 line functions than one 20 line function and two smaller functions will be easier to read than one long one. 2. They can simplify programming tasks because existing functions can be reused as the building blocks for new programs. Really useful functions can be bundled into libraries. 38

P ROCEDURAL A BSTRACTION Procedural Abstraction – A programming technique in which a main function consists of a sequence of function calls and each function is implemented separately. All of the details of the implementation to a particular subproblem is placed in a separate function. The main functions become a more abstract outline of what the program does. When you begin writing your program, just write out your algorithm in your main function. Take each step of the algorithm and write a function that performs it for you. Focusing on one function at a time is much easier than trying to write the complete program at once. 39

R EUSE OF F UNCTION S UBPROGRAMS Functions can be executed more than once in a program. Reduces the overall length of the program and the chance of error. Once you have written and tested a function, you can use it in other programs or functions. 40

C OMMON P ROGRAMMING E RRORS Remember to use a #include preprocessor directives for every standard library from which you are using functions. Place prototypes for your own function subprogram in the source file preceding the main function; place the actual function definitions after the main function. The acronym NOT summarizes the requirements for argument list correspondence. Provide the required N umber of arguments Make sure the O rder of arguments is correct Make sure each argument is the correct T ype or that conversion to the correct type will lose no information. Include a statement of purpose on every function you write. Also be careful in using functions that are undefined on some range of values. 41