Chapter 6: Function Introduction to function Standard functions User defined functions –function prototype –function definition Function call Storage classes.

Slides:



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

Introduction to C Programming
Modular Programming With Functions
Chapter 7: User-Defined Functions II
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Chapter 5 C Functions The best way to develop and maintain a large program is to divide it into several smaller program modules, each of which is more.
 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.
CS 201 Functions Debzani Deb.
FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
C Lecture Notes Functions (Cont...). C Lecture Notes 5.8Calling Functions: Call by Value and Call by Reference Used when invoking functions Call by value.
Overview scope - determines when an identifier can be referenced in a program storage class - determines the period of time during which that identifier.
Topic 4 – Programmer- Defined Functions. CISC 105 – Topic 4 Functions So far, we have only seen programs with one function, main. These programs begin.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
FunctionsFunctions Systems Programming Concepts. Functions   Simple Function Example   Function Prototype and Declaration   Math Library Functions.
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
Functions in C. Function Terminology Identifier scope Function declaration, definition, and use Parameters and arguments Parameter order, number, and.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
18-2 Understand “Scope” of an Identifier Know the Storage Classes of variables and functions Related Chapter: ABC 5.10, 5.11.
Principles of Programming Chapter 6: Function & Recursion  In this chapter, you will learn about  Introduction to function  User define function  Function.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
 2007 Pearson Education, Inc. All rights reserved C Functions.
Principles of Programming - NI Simple Recursion Recursion is where a function calls itself. Concept of recursive function: A recursive function is.
Variable Scope Storage Class Recursion
Principles of Programming Chapter 11: Recursive Function  In this chapter, you will learn about  Recursion function 1 NI S1 2009/10.
Functions Kernighan/Ritchie: Kelley/Pohl: Chapter 4 Chapter 5.
 2007 Pearson Education, Inc. All rights reserved C Functions -Continue…-
Fundamentals of C and C++ Programming. EEL 3801 – Lotzi Bölöni Sub-Topics  Basic Program Structure  Variables - Types and Declarations  Basic Program.
CPS120: Introduction to Computer Science Functions.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions 5.5Function Definitions 5.6Function Prototypes.
Dale Roberts CSCI 230 Functions Scope, Parameter Passing, Storage Specifiers Department of Computer and Information Science, School of Science, IUPUI Dale.
Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
FUNCTIONS. Funtions  The heart of effective problem solving is problem decomposition.  breaking a problem into small, manageable pieces  In C, the.
Principles of Programming - NI Chapter 6: Function In this chapter, you will learn about Introduction to function User define function Function prototype.
KIC/Computer Programming & Problem Solving 1.  Header Files  Storage Classes  Scope Rules  Recursion Outline KIC/Computer Programming & Problem Solving.
Principles of Programming - NI Simple Recursion Recursion is where a function calls itself. Concept of recursive function: A recursive function is.
1 CHAPTER 2 FUNCTION AND PROGRAM STRUCTURE. 2 Functions and Program Structure  Introduction to top-down methodology  Introduction to function  Standard.
Senem Kumova Metin // CS115 // FUNCTIONS CHAPTER 5.
Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
A First Book of ANSI C Fourth Edition
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Functions Course conducted by: Md.Raihan ul Masood
User-Written Functions
C Functions -Continue…-.
Lesson #6 Modular Programming and Functions.
Lesson #6 Modular Programming and Functions.
Chapter 5 Conclusion CIS 61.
Quiz 2.
C-language Lecture By B.S.S.Tejesh, S.Neeraja Asst.Prof.
CSC113: Computer Programming (Theory = 03, Lab = 01)
©2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 5 - Functions Outline 5.1 Introduction
User-Defined Functions
Chapter 5 - Functions Outline 5.1 Introduction
Lesson #6 Modular Programming and Functions.
Scope, Parameter Passing, Storage Specifiers
Chapter 6 - Functions Outline 5.1 Introduction
Function In this lesson, you will learn about Introduction to Function
Lesson #6 Modular Programming and Functions.
In C Programming Language
1-6 Midterm Review.
Presentation transcript:

Chapter 6: Function Introduction to function Standard functions User defined functions –function prototype –function definition Function call Storage classes Variable scope Simple recursion

Top Down Design Methodology When we want to design a very large program, it is not practical to write all the gory details from the beginning. A more practical approach would be to first write down all the major steps that we need to do in the program. After writing all the major steps, only then we start refining each of the major steps and write down the details.

Top Down Design: Example Write a program that will read the velocity of a moving object and calculate the increase in mass, the shortening of length and the time dilation of the object according to Lorentz transformations. Then, decide whether it is still okay to use classical physics (as opposed to relativistic physics) to describe the behavior of the object.

Introduction to Functions A function is a block of code which is used to perform a specific task. It can be written in one program and used by another program without having to rewrite that piece of code. Functions can be put in a library. If another program would like to use them, it will just need to include the appropriate header file at the beginning of the program and link to the correct library while compiling. A function is used by calling the name of the function.

#include int GetScore(void); void CalculateTotal(int); void PrintTotal(void); int total = 0; void main(void) { int score, count = 0; for (; count < 10; count++) { score = GetScore(); CalculateTotal(score);’ } PrintTotal(); } Consider this example: File header } Function prototypes } Function calls The use of functions resembles a pseudocode. Therefore we can easily convert steps in a pseudocode into function calls. Our code looks a lot neater and more readable by using functions.

Standard Functions Standard functions are functions that have been pre-defined by C and put into standard C libraries. –Example: printf(), scanf(), pow(), ceil(), rand(), etc. What we need to do to use them is to include the appropriate header files. –Example: #include, #include What contained in the header files are the prototypes of the standard functions. The function definitions (the body of the functions) has been compiled and put into a standard C library which will be linked by the compiler during compilation.

Used Defined Functions A programmer can create his/her own function(s). It is easier to plan and write our program if we divide it into several functions instead of writing a long piece of code inside the main function. A function is reusable and therefore prevents us (programmers) from having to unnecessarily rewrite what we have written before. In order to write and and use our own function, we need to do these: –create a function prototype –define the function somewhere in the program –call the function whenever it needs to be used

Function Prototype A function prototype will tell the compiler that there exist a function with this name defined somewhere in the program and therefore it can be used even though the function has not yet been defined at that point. Function prototypes need to be written at the beginning of the program. If the function receives some arguments, the variable names for the arguments are not needed. State only the data types.

Examples of function prototypes: void Function1(void); void Function2(int); char Function3(char, int, int); Function prototypes can also be put in a header file. Header files are files that have a.h extension. The header file can then be included at the beginning of our program. To include a user defined header file, type: #include “header_file.h” Notice that instead of using as in the case of standard header files, we need to use “”. This will tell the compiler to search for the header file in the same directory as the program file instead of searching it in the directory where the standard library header files are stored.

Function Definitions A function definition is where the actual code for the function is written. This code will determine what the function will do when it is called. A function definition has this format: return_value FunctionName(function arguments) { variable declarations; statements; } The return value is a data that will be returned by the functions. There can be only one return value. The function arguments is a list of data to be passed to the function. The number of arguments that can be passed is infinite.

In the example that we have seen earlier, 3 function prototypes has been declared. Below are their definitions: int GetScore(void) { int temp; printf(“Enter the score: “); scanf(“%d”, temp); return temp; } void CalculateTotal(int score) { total = total + score; } void PrintTotal(void) { printf(“Total score is: %d\n”, total); } If the function has a return value, it needs to have a return statement at the end. Make sure the data type is the same. Give a name to the argument(s) that are passed to the function.

In the CalculateTotal() function, the function takes only one argument. In the case where a function takes more than one argument, each arguments need to be separated by a coma. Make sure the data type for each arguments is stated. For example: void Calc(int a, int b, double c, char d) { statements; } If the data type is not stated, for example: void Calc(a, b, c, d) {} each of them by default will be an int. But, for the sake of good programming style, please state the data type even though it is an int. Use the keyword void if no arguments will be passed to or returned from the function (even though it is perfectly okay not to write anything).

Function Call A function is called by typing the name of the function. If the function requires some arguments to be passed along, then the arguments need to be listed in the bracket () according to the specified order. For example: void Calc(int, double, char, int); void main(void) { int a, b; double c; char d; … Calc(a, c, d, b); }

If the function returns a value, then the returned value need to be assigned to a variable so that it can be stored. For example: int GetUserInput(void); void main(void) { int input; input = GetUserInput(); } However, it is perfectly okay (syntax wise) to just call the function without assigning it to any variable if we want to ignore the returned value. We can also call a function inside another function. For example: printf(“User input is: %d”, GetUserInput());

There are 2 ways to call a function: –Call by value In this method, only the value of the variable is passed to the function. Any modification to the passed value inside the function will not affect the actual value. In all the examples that we have seen so far, this is the method that has been used. –Call by reference In this method, the reference (memory address) of the variable is passed to the function. Any modification passed done to the variable inside the function will affect the actual value. To do this, we need to have knowledge about pointers, which will be discussed in the next topic.

Storage Classes Each indentifier in a program has attributes such as storage class, storage duration, variable scope and linkage. C provides 4 storage classes indicated by the storage class specifiers: auto, register, extern and static. The 4 storage classes can be split into 2 storage durations: –automatic storage duration auto and register –static storage duration static and extern

Variables with automatic storage duration are created when the block in which they are declared is entered, exist when the block is active and destroyed when the block is exited. The keyword auto explicitly declares variables of automatic storage duration. It is rarely used because when we declare a local variable, by default it has class storage of type auto. –“int a, b;” is the same as “auto int a, b;” The keyword register is used to suggest to the compiler to keep the variable in one of the computer’s high speed hardware register. However, it is also rarely used since compilers nowadays are smart enough detect frequently used variables to be put in a register.

Identifiers with static storage duration exist from the point at which the program begin execution. The static keyword is applied to a local variable so that the variable still exist even though the program has gone out of the function. As a result, whenever the program enters the function again, the value in the static variable still holds. The keyword extern is used to make an identifier global. Global variables and function names are of storage class extern by default.

Variable Scope The scope of a variable is the portion of the program in which the identifier can be referenced. A local variable can only be referenced in the block in which it is declared (a block is indicated by curly bracers { } ). A global variable can be referenced from any functions in the program. If there exist a local variable and a global variable with the same name, the compiler will reference the local variable.

Simple Recursion Recursion is where a function calls itself. Concept of recursive function: –A recursive function is called to solve a problem –The function only knows how to solve the simplest case of the problem. When the simplest case is given as an input, the function will immediately return with an answer. –However, if a more complex input is given, a recursive function will divide the problem into 2 pieces: a part that it knows how to solve and another part that it does not know how to solve.

–The part that it does not know how to solve resembles the original problem, but of a slightly simpler version. –Therefore, the function calls itself to solve this simpler piece of problem that it does now know how to solve. This is what called the recursion step. –The recursion step is done until the problem converges to become the simplest case. –This simplest case will be solved by the function which will then return the answer to the previous copy of the function. –The sequence of returns will then go all the way up until the original call of the function finally return the result.

Recursive factorial function: #include long factorial(long); void main(void) { int i; for (i = 1; i <= 10; i++) printf(“%2d! = %1d\n”, i, factorial(i)); } long factorial(long number) { if (number <= 1) return 1; else return (number * factorial(number-1)); } Calls itself with a simpler version of the problem.

Output: 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = ! = ! = ! = Any problem that can be solved recursively can also be solved iteratively (using loop). Recursive functions are slow and takes a lot of memory space compared to iterative functions. So why bother with recursion? There are 2 reasons: Recursion approach more naturally resembles the problem and therefore the program is easier to understand and debug. Iterative solution might not be apparent.