Chapter Five Functions

Slides:



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

User-Defined Functions Like short programs Can operate on their own data Can receive data from callers and return data to callers.
User Defined Functions
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
C Functions. What are they? In general, functions are blocks of code that perform a number of pre-defined commands to accomplish something productive.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 12P. 1Winter Quarter User-Written Functions.
Modular Programming With Functions
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
1 Engineering Problem Solving With C++ An Object Based Approach Chapter 5 Functions.
16/11/2015 9:05 AM6/11/2015 9:05 AM6/11/2015 9:05 AMFunctions Functions A function consists of: Name Name Arguments (also called parameters) Arguments.
Software Development Method. Assignments Due – Homework 0, Warmup Reading – Chapter 2 –
Chapter 6: User-Defined Functions I
1 Modularity In “C”. 2 What is Modularity?  Modularity, is the heart of the high level, structured languages.  Means breaking down a big problem into.
Function (L16) * Mathematical Library Functions * Program Components in C++ * Motivations for Functionalizing a Program * Function Prototype * Function.
CS 201 Functions Debzani Deb.
Chapter 6: User-Defined Functions I
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
CMSC 1041 Functions II Functions that return a value.
Programming in C++ Language ( ) Lecture 5: Functions-Part1 Dr. Lubna Badri.
CPS120: Introduction to Computer Science Functions.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
FUNCTIONS IN C++. DEFINITION OF A FUNCTION A function is a group of statements that together perform a task. Every C++ program has at least one function,
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 5.3Math Library Functions Math library functions –perform.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Functions Outline 5.1Introduction 5.2Program Modules.
Sudeshna Sarkar, IIT Kharagpur 1 Functions Lecture
1 10/18/04CS150 Introduction to Computer Science 1 Functions Divide and Conquer.
KIC/Computer Programming & Problem Solving 1.  Introduction  Program Modules in C  Math Library Functions  Functions  Function Definitions  Function.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 12P. 1Winter Quarter User-Written Functions Lecture 12.
User defined functions
FUNCTIONS A function is a set of instructions that can perform a specific task accordingly. A function is a program that performs a specific task according.
Introduction to Functions.  A complex problem is often easier to solve by dividing it into several smaller parts, each of which can be solved by itself.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
Functions  A Function is a self contained block of one or more statements or a sub program which is designed for a particular task is called functions.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students Functions (2)
1 ICS103 Programming in C Lecture 8: Functions I.
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 
Dale Roberts CSCI N305 Functions Declarations Department of Computer and Information Science, School of Science, IUPUI.
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.
Announcements. Practice questions, with and without solutions will be uploaded by Friday 5 th November, make sure to check them before the weekend \\netstorage\Subjects\ITCA-b\Exam.
Chapter 7: Function.
Functions, Part 2 of 2 Topics Functions That Return a Value
Chapter 4 Procedural Abstraction and Functions That Return a Value 1
Object Oriented Systems Lecture 03 Method
Deitel- C:How to Program (5ed)
Functions in C Mrs. Chitra M. Gaikwad.
CSCI 161: Introduction to Programming Function
Functions.
User-Defined Functions
2011/11/20: Lecture 15 CMSC 104, Section 4 Richard Chang
2008/11/05: Lecture 15 CMSC 104, Section 0101 John Y. Park
Functions Declarations CSCI 230
User Defined Functions
Functions I Creating a programming with small logical units of code.
Functions, Part 1 of 3 Topics Using Predefined Functions
بنام خدا زبان برنامه نویسی C (21814( Lecture 4 Chapter 5
Chapter 9: Value-Returning Functions
Functions Divide and Conquer
Functions, Part 1 of 3 Topics Using Predefined Functions
Introduction to C++ Programming Language
Predefined Functions Revisited
Introduction to Functions
Functions, Part 1 of 3 Topics Using Predefined Functions
2008/11/05: Lecture 15 CMSC 104, Section 0101 John Y. Park
Functions I Creating a programming with small logical units of code.
Chapter 4 Procedural Abstraction and Functions That Return a Value 1
CPS125.
Presentation transcript:

Chapter Five Functions

Functions Functions can be either library functions or user-defined functions A function may call other functions to help it perform one of its subtasks Functions allow us to reuse pieces of code easily Library functions are the most commonly used functions

Library Functions stdio.h stdlib.h math.h printf, scanf abs sqrt, pow, sin, fabs

Function Declarations All functions must be declared before they are used A function declaration specifies the prototype of a function result-type func-name (argument-specifiers) ; func-name is the name of the function argument-specifiers specifies the type of each argument to the function and a (optional) descriptive name for the argument result-type specifies the type of the value returned by the function

Examples stdio.h stdlib.h math.h void printf(char * format, …); int scanf(char * format, …); stdlib.h int abs(int n); math.h double sqrt(double x); double pow(double x); double sin(double theta); double fabs(double x);

User-defined Functions Programmers can define their own functions if the required functions are not provided in the library A piece of code can be considered to be written as a function if it will be used multiple times in the program or it will be used by other programs (i.e., build your own library)

Compute the combination function An Example Compute the combination function C(n, k) = n! / ( k!  (n – k)! )

Function Definitions Head Body A function definition specifies the implementation details of a function A function definition has this form: result-type func-name (parameter-specifiers) { declarations statements } Head Body

An Example int fact(int m) { int product, i; product = 1; declarations for (i = 1; i <= m; i++) { product *= i; } return product; declarations statements

Introduction to Computer Science Return Statements Most functions will evaluate to a value. This value is passed back to the calling function via return statements A return statement has the form return expression; the value of expression is passed back as the value evaluated by the function Arithmetic Expressions and Assignment Statements

Return Statements If a function does not evaluate to a value, its result-type is void If a function’s result-type is void, its return statement has the form return; and this statement can be omitted If a function’s result-type is int, its result-type can be omitted

Examples void printf(char * format, …); int fact(int m); fact(int m);

An Example int fact(int m); int comb(int n, int k) { return fact(n) / (fact(k) * fact(n – k)); } main( ) { int n, k; scanf(“%d %d”, &n, &k); printf(“C(%d, %d) = %d\n”, n, k, comb(n, k));

Flow of Control fact 2 3 1 4 main comb fact 5 8 6 fact 7

Parameter Passing The values of each argument are evaluated The values of arguments are assigned to the parameters in order. If necessary, automatic type conversion are performed

An Example m = n; return n! fact m = k; return k! comb fact m = n - k; return (n-k)! fact

Local Variables Variables declared within a function are called local variables or automatic variables The scope of a local variable declaration is restricted within the function body; therefore, different functions may use local variables with the same name int fact(int n); int comb(int n, int k)

An Example nfact = ncomb; return n! fact nfact = k; return k! comb nfact = ncomb - k; return (n-k)! fact

Local Variables Each local variable in a function comes to existence only when the function is called, and disappears when the function is exited The allocation and deallocation of memory for local variables are performed automatically Local variables must be explicitly set upon each entry

An Example nfact1 fact nfact2 comb fact nfact3 fact

Predicate Functions A function is called a predicate function if it returns a value of Boolean type int isEven(int n) { return (n % 2 == 0); }

Symbolic Constants Symbolic constants facilitate the understanding and maintenance of programs #define symbol value #define pi 3.14159

Defining New Type Names The keyword typedef introduces a new type name for an old type typedef old-type new-type; typedef int bool;

An Example typedef int bool; #define TRUE 1 #define FALSE 0 bool isLeapYear(int year) { return ( (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0) ); }

Macros Functions incur overheads for passing arguments, managing memory for local variables, returning values, and so on Macros allow us to use text substitution to avoid such overheads for short functions #define name value

An Example #define isEven(n) ((n) % 2 == 0) if (isEven(i)) { … }

Macros Avoid arguments that have side effects when the corresponding parameter occurs multiple times in the body #define isLeapYear(year) \ ( ((year) % 4 == 0) && \ ((year) % 100 != 0) || \ ((year) % 400 == 0) )

Stepwise Refinement Functions enable us to divide a large programming problem into smaller pieces that are individually easy to understand Stepwise refinement (or top-down design) allows us to start with the main function, and then refine step-by-step its subtasks by dividing it into gradually smaller functions

An Example Print calendar December 2001 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 17 18 19 20 21 22 24 25 26 27 28 29 30 31

An Example main( ) { int year; giveInstructions( ); year = getYearFromUser( ); printCalendar(year); }

An Example void giveInstructions(void) { printf(“This program displays a calendar for a full\n”); printf(“year. The year must not be before 1990.\n”); }

An Example int getYearFromUser(void) { int year; while (TRUE) { printf(“Which year? ”); scanf(“%d”, &year); if (year >= 1900) return year; printf(“The year must be at least 1900.\n”); }

An Example void printCalendar(int year) { int month; for (month = 1; month <= 12; month++) { printCalendarMonth(month, year); printf(“\n”); }

An Example void printCalendarMonth(int month, int year) { int weekday, nDays, day; printf(“ %s %d\n”, monthName(month), year); printf(“ Su Mo Tu We Th Fr Sa\n”); nDays = monthDays(month, year); weekday = firstDayOfMonth(month, year); indentFirstLine(weekday); for (day = 1; day <= nDays; day++) { printf(“ %2d”, day); if (weekday == Saturday) printf(“\n”); weekday = (weekday + 1) % 7; } if (weekday != Sunday) printf(“\n”);

An Example #define Sunday 0 #define Monday 1 #define Tuesday 2 #define Wednesday 3 #define Thursday 4 #define Friday 5 #define Saturday 6

An Example char *monthName(int month) { switch(month) { case 1: return “January”; case 2: return “Febryary”; case 3: return “March”; … case 11: return “November”; case 12: return “December”; default: return “Illegal month”; }

An Example int monthDays(int month, int year) { switch (month) { case 2: if (isLeapYear(year)) return 29; return 28; case 4: case 6: case 9: case 11: return 30; default: return 31; }

An Example int firstDayOfMonth (int month, int year) { int weekday, i; weekday = Monday; for (i = 1900; i < year; i++) { weekday = (weekday + 365) % 7; if (isLeapYear(i)) weekday = (weekday + 1) % 7; } for (i = 1; i < month; i++) { weekday = (weekday + monthDays(i, year)) % 7; return weekday;

An Example void indentFirstLine(int weekday) { int i; for (i = 0; i < weekday; i++) { printf(“ ”); }

An Example main getYearFromUser giveInstructions printCalendar printCalendarMonth monthDays monthDays firstDayOfMonth indentFirstLine isLeapYear