Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Introduction to C Programming
Spring Semester 2013 Lecture 5
Ch. 8 Functions.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
1 Chapter 7: Runtime Environments. int * larger (int a, int b) { if (a > b) return &a; //wrong else return &b; //wrong } int * larger (int *a, int *b)
Chapter 6: User-Defined Functions I
Computer Programming 1 Functions. Computer Programming 2 Objectives Take a first look at building functions Study how a function is called Investigate.
Run time vs. Compile time
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
Assembly תרגול 8 פונקציות והתקפת buffer.. Procedures (Functions) A procedure call involves passing both data and control from one part of the code to.
Chapter 6: User-Defined Functions I
Recursion A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
C++ for Engineers and Scientists Third Edition
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
Chapter 6: Modularity Using Functions. In this chapter, you will learn about: – Function and parameter declarations – Returning a single value – Returning.
Runtime Environments Compiler Construction Chapter 7.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Today’s topics Parameter passing on the system stack Parameter passing on the system stack Register indirect and base-indexed addressing modes Register.
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
USER-DEFINED FUNCTIONS. STANDARD (PREDEFINED) FUNCTIONS  In college algebra a function is defined as a rule or correspondence between values called the.
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
Computer programming Outline Functions [chap 8 – Kochan] –Defining a Function –Arguments and Local Variables Automatic Local.
CCSA 221 Programming in C CHAPTER 8 – PART 1 WORKING WITH FUNCTIONS 1.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
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.
1 MORE ON MODULAR DESIGN: MODULE COMMUNICATIONS. 2 WHEN A FUNCTION IS INVOKED, MEMORY IS ALLOCATED LOCALLY FOR THE FORMAL PARAMETERS AND THE VALUE OF.
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
FUNCTIONS. Midterm questions (1-10) review 1. Every line in a C program should end with a semicolon. 2. In C language lowercase letters are significant.
1 UMBC CMSC 104, Section Fall 2002 Functions, Part 1 of 3 Topics Top-down Design The Function Concept Using Predefined Functions Programmer-Defined.
Functions, Part 1 of 3 Topics  Using Predefined Functions  Programmer-Defined Functions  Using Input Parameters  Function Header Comments Reading 
Programming Fundamentals Enumerations and Functions.
Functions Chapter 5. Function A set of instructions that are designed to perform specific task. A complete and independent program. It is executed by.
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
ECE 103 Engineering Programming Chapter 30 C Functions Herbert G. Mayer, PSU CS Status 8/9/2014 Initial content copied verbatim from ECE 103 material developed.
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
Chapter 6: User-Defined Functions I
Chapter 7: User-Defined Functions II
Lesson #6 Modular Programming and Functions.
Lesson #6 Modular Programming and Functions.
Programming Fundamentals Lecture #7 Functions
C-language Lecture By B.S.S.Tejesh, S.Neeraja Asst.Prof.
User-Defined Functions
2011/11/20: Lecture 15 CMSC 104, Section 4 Richard Chang
Lesson #6 Modular Programming and Functions.
C Arrays.
Recursion Chapter 11.
Lecture 18 Arrays and Pointer Arithmetic
Chapter 7: User-Defined Functions II
Lesson #6 Modular Programming and Functions.
CPS125.
Presentation transcript:

Functions

Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used many functions printf() is a function that causes data to be printed on the screen. scanf() read data from a keyboard Math functions sqrt() exp() sin() cos() tan()

Motivation Why should you use functions? Function save you from repetitious programming (save time and space) Using a function is worthwhile because it makes a program more modular, hence easier to read and easier to change or fix. 3 Main program Function AFunction BFunction C F1F2

Example Suppose, for example, that you want to write a program that does the following: Read in a list of numbers such as [5, 6, 1, 7, 2, 4, 3] Sort the numbers [1, 2, 3, 4, 5, 6,7] Find their average 4 Print a bar graph A function can be thought as a "black box" defined in terms of the information that goes in (its input) and the value or action it produces (its output).

What do we need to know about functions? 5 How to define functions properly How to call functions up for use. How to set up communication between functions.

Example: starbar() function 6

%s is used to print strings String constants Many nested function class are possible

Definition of functions Function definition include six elements grouped in two parts function type; function name; list of parameters; local variable declarations function statements a return statement Body Header function_type function_name ( parameter list ) { local variable declaration; executable statment1; executable statement2; … return statement; } Body Header

Function names and usage rules Both function names and variables are considered identifies and therefore they must adhere to the rules for identifiers. Variables Functions OK WRONG

Function types and arguments Similar as variables have types, functions also have types A function may or may not have parameter. Type of each parameter have to by specified. Functions also can return values or

Function types and arguments 11 The following function header indicates that a defined function takes two type int arguments but that returns a type double value. If function does not return any value, use type void.

Function prototypes For functions the declaration needs to be before the first call of the function. A full declaration (prototype) includes the return type and the number and type of the arguments. The function prototype is function header with semicolon at the end. Function prototypes are usually combined in to a header file.h math. h …

Function prototypes With function prototype Without function prototype Having the prototype available before the first use of the function allows the compiler to check that the correct number and type of arguments are used in the function call and that the returned value, if any, is being used reasonably.

Passing arguments to function example * Function strlen() returns number of characters in a string Example: int n = strlen(“Hello”); // n will be 5

Calling a Function with Arguments We can omit variable names in the prototype: Declaration on an ANSI function prototype: We give ch and num values by using actual arguments in the function call. Consider the first use of show_n_char (). The actual argument can be a constant, a variable, or an even more elaborate expression

Calling a Function with Arguments 16 copy 25 to variable number

Returning a Value from a Function with return Functions can be used as a part of an expression How can we simplify this program?

The Black-Box Viewpoint Taking a black-box viewpoint of show_n_char (char ch, int num), the input is the character to be displayed and the number of times to be repeated. The input is communicated to the function via arguments. This information is enough to tell you how to use the function in main(). The fact that ch, num, and count are local variables private to the show_n_char() function is an essential aspect of the black box approach. If you were to use variables with the same names in main (), they would be separate, independent variables. show_n_char() internal variables ch, num, count show_n_char() internal variables ch, num, count (char c, int n) return result

CPU implementation of function calls: Stack To understand how processor treats function calls, we need to introduce stack memory. A stack is a data structure that stores data values contiguously in memory. 19 An access (read or write) data is performed only at the "top" of the stack. To read from the stack is said "to pop" and to write to the stack is said "to push". A stack is also known as a LIFO queue (Last In First Out). Recall that eax is a 32 bit register (small and fast memory inside CPU)

CPU implementation of function calls: push and pop 20 The current top of the stack is pointed to by the esp register. Stack grows from the location where esp is pointing to. ebp ebp is pointing to the base of the stack

CPU implementation of function calls: Data allocation There are two areas in the computer memory where a program can store data. The stack: linear LIFO buffer that allows fast allocations and deallocations, but has a limited size. Stacks are used to pass variables to function or store local variables (variable declare inside functions). The heap: typically a non-linear data storage area, where allocations/deallocations are performed more slowly. The heap is used to allocate large chunks of memory. 21

CPU implementation of function calls: Stack Frames The idea behind a stack frame is that each function can act independently of its location on the stack, and each function can act as if it is the top of the stack. When a function is called, a new stack frame is created at the current esp location in the memory. 22 This will create the following assembly code Consider the following function definition Similar to jmp It turns out that the function arguments are all passed on the stack! _MyFunction2: | 2 | [ebp + 16] (3rd function argument) | 5 | [ebp + 12] (2nd argument) | 10 | [ebp + 8] (1st argument) | RA | [ebp + 4] (return address) | FP | [ebp] (old ebp value) oversimplified copied to stack and a function call

C permits a function to call itself. This process is termed recursion. Recursion often can be used where loops can be used. It's vital that a recursive function contain something to halt the sequence of recursive calls Recursion

24 Note that each level of recursion uses its own private n variable

Tail Recursion Tail recursion acts like a loop. The recursive call is at the end of the function, just before the return statement. n! = n x (n-1)! Although the recursive call to rfact() is not the last line in the function, it is the last statement executed when n > 0, so it is tail recursion.

Recursion and Reversal The function prints the binary equivalent of a decimal integer. putchar( r ? '1' : '0');

Recursion Pros and Cons + recursion offers the simplest solution to some programming problems. - some recursive algorithms can rapidly exhaust a computer's memory The Fibonacci function allocates a variable called n and evokes itself twice, creating two more variables called n at the second level of recursion. Each of those two calls generates two more calls, requiring four more variables called n at the third level of recursion, for a total of seven variables. This processes results in a enormous number of allocated variables. Fibonacci(40) Fibonacci(38)Fibonacci(39) Fibo (36)Fibo (37) Fibo (38) F(34)F(35) F(36) F(35)F(36) F(37)