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.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Spring Semester 2013 Lecture 5
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
ECE 103 Engineering Programming Chapter 11 One Minute Synopsis Herbert G. Mayer, PSU CS Status 7/1/2014.
1 CS 161 Introduction to Programming and Problem Solving Chapter 9 C++ Program Components Herbert G. Mayer, PSU Status 10/20/2014.
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.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
FunctionsFunctions Systems Programming. Systems Programming: Functions 2 Functions   Simple Function Example   Function Prototype and Declaration.
 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.
 2007 Pearson Education, Inc. All rights reserved C Functions.
Chapter 6: User-Defined Functions I
1 CSC 1401 S1 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
FunctionsFunctions Systems Programming Concepts. Functions   Simple Function Example   Function Prototype and Declaration   Math Library Functions.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
 Introduction Introduction  Types of Function Types of Function  Library function Library function  User defined function User defined function 
Chapter 4:Functions| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2005 Slide 1 Functions Lecture 4 by Jumail Bin.
1 CS 162 Introduction to Computer Science Chapter 4 Function Calls Herbert G. Mayer, PSU Status 11/9/2014.
© 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.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Chapter 6: User-Defined Functions
Learners Support Publications Classes and Objects.
Functions Modules in C++ are called functions and classes Functions are block of code separated from main() which do a certain task every C++ program must.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
CPS120: Introduction to Computer Science 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.
Chapter 8: Arrays and Functions Department of Computer Science Foundation Year Program Umm Alqura University, Makkah Computer Programming Skills
Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions 5.5Function Definitions 5.6Function Prototypes.
CS 161 Introduction to Programming and Problem Solving Chapter 19 Single-Dimensional Arrays Herbert G. Mayer, PSU Status 10/8/2014 Initial content copied.
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
ECE 103 Engineering Programming Chapter 18 Iteration Herbert G. Mayer, PSU CS Status 7/19/2015 Initial content copied verbatim from ECE 103 material developed.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
ECE 103 Engineering Programming Chapter 36 C Storage Classes Herbert G. Mayer, PSU CS Status 8/4/2014 Initial content copied verbatim from ECE 103 material.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Functions Outline 5.1Introduction 5.2Program Modules.
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.
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.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
ECE 103 Engineering Programming Chapter 31 C Scopes Herbert G. Mayer, PSU CS Status 8/1/2015 Initial content copied verbatim from ECE 103 material developed.
ECE 103 Engineering Programming Chapter 4 Operators Herbert G. Mayer, PSU CS Status 6/19/2015 Initial content copied verbatim from ECE 103 material developed.
CS 161 Introduction to Programming and Problem Solving Chapter 17 Nested Loops Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.
ECE 103 Engineering Programming Chapter 41 C Pointers, Part 3 Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103 material.
Programming Fundamentals Enumerations and Functions.
Dale Roberts CSCI N305 Functions Declarations Department of Computer and Information Science, School of Science, IUPUI.
CS 161 Introduction to Programming and Problem Solving Chapter 12 C++ Statements Herbert G. Mayer, PSU Status 10/8/2014 Initial content copied verbatim.
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.
User-Written Functions
Lesson #6 Modular Programming and Functions.
Lesson #6 Modular Programming and Functions.
Deitel- C:How to Program (5ed)
CS1061 C Prgramming Lecture 11: Functions
Programmazione I a.a. 2017/2018.
Functions.
User-Defined Functions
Chapter 5 - Functions Outline 5.1 Introduction
Lesson #6 Modular Programming and Functions.
Functions Declarations CSCI 230
Chapter 6 - Functions Outline 5.1 Introduction
Lesson #6 Modular Programming and Functions.
Function.
ECE 103 Engineering Programming Chapter 12 More C Statements
ECE 103 Engineering Programming Chapter 18 Iteration
ENERGY 211 / CME 211 Lecture 8 October 8, 2008.
Function.
CPS125.
Functions that return a value
Presentation transcript:

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 by Professor Phillip PSU ECE

Syllabus Introduction Function Definition Parameter List Function Body Function Declaration Examples Recursion

2 Introduction A program can be divided into multiple parts Logical partitions are named: modules Physical partitions are named: C functions Each function has a name; when listed in a C program, the respective function is “called” or “invoked” to do its logical task at that code location Why are functions useful?  Organization – divides tasks into subtasks  Encapsulation – hides design and implementation details from view of the rest of the program  Simplification – reduces unnecessary code repetition  Modularity – creates reusable code libraries

3 Arguments, AKA actual parameters, contain data that the caller passes to the function  Arguments can be literal constants, variables, data structures, or expressions  Some functions require multiple arguments, while others may need no arguments at all The Return Value returns data back to the caller  A function can return a single value or no value at all, in which case it is a void function C Function Arguments Return Value

4 Example: Sample function calls: fun1();// no input arg, no ret val fun2( n );// 1 input arg, AKA 1 actual fun3( 1.25, "xm” );// 2 input args: 2 actuals R = rand();/* no arg, 1 return value */ y = sin( x );/* 1 arg, 1 return value */ w = pow( 2.5, 3 );/* 2 args, 1 return value */ /* 5 input args, 1 return value */ val = myfun( "PSU", 'x', 3.5, ivar, 2*cos( A ) );

5 Defining a Function return_type function_name ( parameter_list ) { // function_name local variable declarations code statements } //end function_name Function definition consists of:  header – defines required function inputs/outputs  body – defines the function code  Body includes return operation, even default fall-thru Function names follow variable naming rules Function body {between braces} Header

6 Parameter List: The formal parameter list defines expected data to be passed to function  Formal Parameters are local function variables, generally initialized at place of call via actuals  Names and data types of parameter are declared  Multiple parameters are separated by commas  During a call, the actual parameters are bound to the formal parameters  If no parameters are needed, the list is declared as type void

7 Are arguments (actuals) and parameters (formals) the same? → No. Arguments are the values passed to the function. Parameters are the function’s internal variables that hold copies of the passed values. Example: int x = 3, y = 5, k; char c = '#'; k = fun( x, y, 42, c );... int fun( int x, int y, int z, char c ) {... } The contents of variables x, y, c, along with the constant 42, are passed to the function. These are called arguments. These variables x, y, z, c receive the values passed to the function. They are called parameters.

8 Must an argument variable have the same name as its corresponding parameter variable? → No. They independent of one another Example: int a = 3, b = 5, k; char m = '#'; k = fun( a, b, 42, m );... int fun( int x, int y, int z, char c ) {... } Function callFunction definition '#' 42 53

9 Example: /* Function definition */ void display( int xval, char ch, double * ptr ) { // display printf( "%d %c %p\n", xval, ch, ptr ); } //end display int xval = 3, cat = 3; char ch = 'T', z = 'T'; double * ptr = & xval, * q = & xval; // careful!!! // Some function calls: display( 3, 'T', & xval ); // careful!!! display( xval, ch, ptr ); display( cat, z, q ); /* In each case, the value of the argument * is stored in the corresponding parameter */

10 If possible, an argument's type will be promoted or demoted to match its parameter's type Example: /* Function definition */ void fun( int u, double v ) {... } int x = 2; double y = ; /* Some function calls */ fun( x, y ); /* u contains 2, v contains */ fun( y, x ); /* u contains 3, v contains 2.0 */ Incompatible arguments can cause programs to fail at runtime! Be very carful!!

11 Return type: Return type can be:  Variant of char, int, float, double, struct  Pointer (i.e., memory address)  void (if no value is to be returned) If the function returns a value, then a return statement is needed in the function body. Example: double Compute_Vx (double V, double angle) { return V * sin( angle ); }

12 Function Body: Function body contains:  Local variable declarations  Local prototype declarations  Code that defines what the function does  Including code to specify return value Braces { } mark the beginning and end of the function body There is no semicolon after the final brace In C, a function definition cannot be nested inside another function definition! Note: gcc extension!

13 Example: /* Program #1 Compute areas of triangles - without separate function */ #include int main( void ) { // main float b, h; /* base and height */ float A1, A2; /* area */ A1 = ( 3.0 * 1.5 ) / 2.0; printf( "Area1 = %f\n", A1 ); b = 2.5; h = 15.4; A2 = ( b * h ) / 2.0; printf( "Area2 = %f\n", A2 ); b = 0.33; h = 5.7; printf( "Area3 = %f\n", ( b * h ) / 2.0 ); return 0; } //end main

14 Example: /* Program #2 Compute areas of triangles – with function */ #include float triangle_area( float base, float height ) { // triangle_area return ( base * height ) / 2.0f; } //end triangle_area int main( void ) { // main float b, h; /* base and height */ float A1, A2; /* area */ A1 = triangle_area( 3.0f, 1.5f ); printf( "Area1 = %f\n", A1); b = 2.5f; h = 15.4f; A2 = triangle_area( b, h ); printf( "Area2 = %f\n", A2); b = 0.33f; h = 5.7f; printf( "Area3 = %f\n", triangle_area( b, h ) ); return 0; } //end main

15 Declaring a Function Functions must be defined before they are first used Does this imply that functions must be placed in the source file in a specific order?  It depends For functions, C has two approaches to meet the "define-before-use" rule:  Define functions in order within the source file  Use function prototypes

16 Approach #1: Ordered Definitions Within the source file, function definitions that are used first are placed before functions that call them Example: Suppose A, B, C, D are functions. B calls C, D calls C, and A calls D: CBDACBDA Top of source file

17 Example: void fun1( void ) { // fun1 int x;... x = 3; } //end fun1 void fun2( void ) { // fun2 int x;... x = 5; fun1(); } //end fun2 int main( void ) { // main int x; x = 7; fun1(); fun2(); return 0; } //end main fun1 defined 1 st since both fun2 and main call it. fun2 defined 2 nd since main calls it (but not fun1 ). main defined last

18 Approach #2: Prototypes A function can be declared before being defined A function declaration is just the function header by itself followed by a semicolon (no body) These declarations are called prototypes Prototypes are usually placed at the top of the source file before the actual function definitions Prototypes allow the compiler to determine the basic input/output characteristics of functions without needing to know the internal details By the end of the compilations, bodies for the prototypes must be available

19 Example 1, with formal parameter names: #include /* Function prototypes */ void display( char ch, int xval ); float calculate( int x ); int main( void ) { // main display( 'G', 8 ); return 0; } //end main /* Function definitions */ void display( char ch, int xval ) { // display printf( "%c %d %f\n", ch, xval, calculate( xval ) ); } //end display float calculate( int x ) { // calculate return x*x / 3.0; } //end calculate Once the prototypes are declared, the order in which the functions are defined does not matter NOTE: The main() function does not need to be declared.

20 Example 2 without formal parameter names: #include /* Function prototypes */ void display( char, int ); float calculate( int ); int main( void ) { // main display( 'G', 8 ); return 0; } //end main /* Function definitions */ void display( char ch, int xval ) { // display printf( "%c %d %f\n", ch, xval, calculate( xval ) ); } //end display float calculate( int x ) { // calculate return x*x / 3.0; } //end calculate

21 Example 3 function min( int, int ) with 3-4 args? #include int min( int arg1, int arg2 ) { // min return arg1 < arg2 ? arg1 : arg2; } //end min int main( void ) { // main printf( “min of 2, -3 = %d\n”, min( 2, -3 ) ); printf( “min of 2, 12, 3 = %d\n”, min( 2, min( 12, 3 ) ) ); printf( “min of -9, 2, 12, 3 = %d\n”, min( min( -9, 2 ), min( 12, 3 ) ) ); return 0; } //end main

22 No parametersSingle parameterMultiple parameters (e.g., 2) No return value Declaration void fun (void); Declaration void fun (dtype a); Declaration void fun (dtype a, dtype b); Definition void fun (void) { /* return not needed */ } Definition void fun (dtype a) { /* return not needed */ } Definition void fun (dtype a, dtype b) { /* return not needed */ } Call fun(); Call fun(x); Call fun(x, y); Single return value Declaration dtype fun (void); Declaration dtype fun (dtype a); Declaration dtype fun (dtype a, dtype b); Definition dtype fun (void) { return expr; } Definition dtype fun (dtype a) { return expr; } Definition dtype fun (dtype a, dtype b) { return expr; } Call z = fun(); Call z = fun(x); Call z = fun(x, y);

23 Recursive Functions A function f() may call itself! Either directly, i.e. from inside its own body of f() Or indirectly, from inside another function g(), which was in turn called by f() The former is referred to as “directly recursive calls” The latter a “indirect recursive calls” Recursion is a powerful programming tool, so strong, it can replace almost all other tools; though that is not a recommended approach

24 Recursive Function Definition A function f() is recursive, if it is partly defined by simpler versions of f() itself The partly is important, providing for a base case, a case where the result is known and no further calls are made at all The simpler version is also important, else there would be no recursion at all, but instead infinite regress instead; that is as bad as an infinite loop Let’s see an example:

25 Simple Recursive Function: fact() #include // compute the unsigned factorial of an unsigned argument unsigned fact( unsigned arg ) { // fact if ( 0 == arg ) { return 1; }else{ return fact( arg – 1 ) * arg; } //end if } //end fact int main( void ) { // main int i; for ( i = 0; i < 10; i++ ) { printf( “fact(%d) = %d\n”, i, fact( i ) ); } //end for } //end main

26 Recursive Functions A But we shall not discuss recursion in more detail in a beginning course such as ECE 103