INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from

Similar documents
Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction

CSE123. Program Design and Modular Programming Functions 1-1

ECET 264 C Programming Language with Applications

C Functions. 5.2 Program Modules in C

Functions. Systems Programming Concepts

C Programs: Simple Statements and Expressions

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Functions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa

Programming Fundamentals for Engineers Functions. Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. Modular programming.

Function. specific, well-defined task. whenever it is called or invoked. A function to add two numbers A function to find the largest of n numbers

C Functions Pearson Education, Inc. All rights reserved.

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

Lecture 2:- Functions. Introduction

Programming in C Quick Start! Biostatistics 615 Lecture 4

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

CS110: PROGRAMMING LANGUAGE I

To define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug,

Lecture 04 FUNCTIONS AND ARRAYS

Lecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Lecture 04 FUNCTIONS AND ARRAYS

Function Example. Function Definition. C Programming. Syntax. A small program(subroutine) that performs a particular task. Modular programming design

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Introduction to Programming

Chapter 3 - Functions

Introduction to C Language

COP3502 Programming Fundamentals for CIS Majors 1. Instructor: Parisa Rashidi

Preview from Notesale.co.uk Page 2 of 79

Chapter 5 Methods / Functions

Using Free Functions

Tutorial 5. PDS Lab Section 16 Autumn Functions The C language is termed as function-oriented programming

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1

Chapter 5 Methods. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Chapter 4 Functions By C.K. Liang

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

CS101 Introduction to computing Function, Scope Rules and Storage class

Benefits of Methods. Chapter 5 Methods

Computer Programming

Chapter 6 Methods. Dr. Hikmat Jaber

Chapter 5 C Functions

Lecture 5. Functions II. Functions with Arguments. CptS 121 Summer 2016 Armen Abnousi

JAVA Programming Concepts

Chapter 5 Methods. Modifier returnvaluetype methodname(list of parameters) { // method body; }

Chapter 5 Methods. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk

Computer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries

C Functions. CS 2060 Week 4. Prof. Jonathan Ventura

Functions and an Introduction to Recursion Pearson Education, Inc. All rights reserved.

DUBLIN CITY UNIVERSITY

Methods (Deitel chapter 6)

DUBLIN CITY UNIVERSITY

Methods (Deitel chapter 6)

1001ICT Introduction To Programming Lecture Notes

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions

Slide Set 3. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

Language Design COMS W4115. Prof. Stephen A. Edwards Spring 2003 Columbia University Department of Computer Science

Introduction to Computers II Lecture 4. Dr Ali Ziya Alkar Dr Mehmet Demirer

12. Numbers. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Calling Prewritten Functions in C

Assoc. Prof. Dr. Tansu FİLİK

Computer Programming 6th Week Functions (Function definition, function calls),

Methods: A Deeper Look

from Appendix B: Some C Essentials

CT 229 Java Syntax Continued

Expressions and operators

Chapter 6 - Notes User-Defined Functions I

Holtek C and ANSI C Feature Comparison User s Guide

C Functions. Object created and destroyed within its block auto: default for local variables

Visual Studio. Visual Studio is an extremely complex interactive development environment capable of handling many languages and tools.

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0)

(2-2) Functions I H&K Chapter 3. Instructor - Andrew S. O Fallon CptS 121 (January 18, 2019) Washington State University

C++ Programming Lecture 11 Functions Part I

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

Functions and Recursion

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

The Math Class (Outsource: Math Class Supplement) Random Numbers. Lab 06 Math Class

Primitive Data Types: Intro

Unit 7. Functions. Need of User Defined Functions

CS115 Principles of Computer Science

Slide Set 3. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng

UNIT III (PART-II) & UNIT IV(PART-I)

Function I/O. Function Input and Output. Input through actual parameters. Output through return value. Input/Output through side effects

LAB 7 FUNCTION PART 2

Function I/O. Last Updated 10/30/18

Computer Science & Engineering 150A Problem Solving Using Computers

Cloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example,

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 3. Existing Information. Notes. Notes. Notes. Lecture 03 - Functions

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

Programming in C. Part 1: Introduction

Subject: Fundamental of Computer Programming 2068

BBM 101 Introduc/on to Programming I Fall 2013, Lecture 6-7

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

Other C materials before pointer Common library functions [Appendix of K&R] 2D array, string manipulations. <stdlib.

ALGORITHM 2-1 Solution for Exercise 4

ECE 2400 Computer Systems Programming Fall 2017 Topic 12: Transition from C to C++

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

Transcription:

INTRODUCTION TO C++ FUNCTIONS Original slides are from http://sites.google.com/site/progntut/ Dept. of Electronic Engineering, NCHU

Outline 2 Functions: Program modules in C Function Definitions Function Prototypes Math Library Functions Header files Calling Functions: Call-by-value and Call-byreference Scope Rules Recursion

What is a function? 3 Top-down design: Divide and conquer Partition a problem into several small sub-problems Each sub-problem can be solved by a function (module) Function A module with a specific function name Given a set of inputs, return an output Two types of functions User-defined functions ANSI C standard library functions, such as print(), scanf(), pow()

Function call 4 Invoke functions Provide function name and arguments (inputs) Return results (output) Format: output = function_name(input1, input2, ) Example printf( There are 50 students\n ); Function name: printf Inputs: There are 50 students\n pow(5.0, 3.0) Function name: pow Inputs: 5.0, 3.0 Output: 125 (5 3 )

Advantages of functions 5 Reusability Readability Ease of maintenance Avoid code repetition Use ANCI C standard library to improve portability

Function Definition 6 return-data-type function-name (data-type arg1, data-type arg2, ) { declarations; statements; return output; Function-name Any valid identifier (follow the same rule with variables) Parameter list A set of inputs separated by comma (,) Specify a data type for each input argument

Function Definition 7 Return-data-type Data type of the result void: Indicate that the function returns nothing Need to return an output with the specified data type If return-data-type is void return; If something returned return output; // output needs to be the specified type Function body Declarations and statements Declarations: variables used inside the function block, which can not be used outside the function Functions can not be defined inside a function

Function Definition: example 8 double compute_avg(int a, int b, int c) { Starting point return (double) (a + b + c)/3; int main() { double avg; int a, b, c; scanf( %d %d %d, &a, &b, &c); avg = compute_avg(a, b, c); return 1; Function definition: Name: compute_avg Inputs: a, b, c (integer) Output: return a double value // call function A function needs to be defined before function call

Function Prototype 9 Declare function prototypes before function call if the function is defined after function call Put semicolon (;) at the end of function prototype Argument names can be omitted in function prototypes double compute_avg(int, int, int); // function prototype int main() { double avg; int a, b, c; scanf( %d %d %d, &a, &b, &c); avg = compute_avg(a, b, c); return 1; double compute_avg(int a, int b, int c) { return (double) (a + b + c)/3; // call function // function definition

Function Prototype 10 Parameter names are sometimes included in function prototypes for documentation purposes. The compiler ignores these names. double compute_avg(int a, int b, int c); int main() { double avg; int a, b, c; scanf( %d %d %d, &a, &b, &c); avg = compute_avg(a, b, c); return 1; double compute_avg(int a, int b, int c) { return (double) (a + b + c)/3; // function prototype // call function // function definition

Programming error 11 Variable name can not be the same with argument names void foo(int tmp) { /* tmp is the argument name, so it can not be used as a variable name */ int tmp = 1; return; int main() { foo(1); return 1; // call function

Programming error 12 Must return a result in any condition int foo(int tmp) { /* no returned value when tmp <= 0 */ if (tmp > 0) return tmp + 1; int main() { foo(-1); return 1; // call function

Programming error 13 The returned value can only be assigned to another variable with the same type double foo(int a, int b) { return (double) (a+b)/2; int main() { /* the returned data type of foo() is double, but the type of avg is int */ int avg; avg = foo(2, 3); // call function return 1; Can force it to transform the data type by avg = (int) foo(2, 3)

Programming error 14 A variable declared in the function can not be used outside the function double foo(int a, int b) { int sum = a + b; return (double) sum/2 int main() { /* assign the results of foo() to avg */ double avg = foo(2, 3); // call function /* sum is declared in foo(), so can not be used here */ printf( sum is %d, avg is %f\n, sum, avg); return 1;

Available usage 15 Function call A() can be the argument of another function call B() if the return type of A() is not void int max(int a, int b) { if (a > b) return a; else return b; int main() { int i, j; scanf( %d %d, &i, &j); /* print the output of max(i,j) use %d because max() returns an integer value */ printf( max is %d\n, max(i, j)); return 1;

Available usage 16 The output of function call can be used as a logical control /* return 1 if a > b; otherwise, 0 */ int test_larger (int a, int b) { if (a > b) return 1; else return 0; int main() { int i, j; for (i = 1; i <= 5; i++) { for (j = 1; j <= 5; j++) { if (test_larger(i, j)) printf( (%d,%d)\n, i, j); // print if i > j return 1; (2,1) (3,1) (3,2) (4,1) (4,2) (4,3) (5,1) (5,2) (5,3) (5,4) output

Available usage 17 Call another function in a function int square (int); int square_sum(int); int square (int num) { return num * num; int square_sum(int num) { int sum = 0; for(int i = 1; i <= num; i++) sum += square(i); return sum; Function definition of square () must be placed before that of square_sum() Otherwise, declare function prototypes in the beginning of the program int main() { printf( square sum = %d\n, square_sum(10)); return 1;

Math Library Functions 18 Math library functions perform common mathematical calculations #include <math.h> Reference http://www.cplusplus.com/reference/clibrary/cmath/ Function Function definition Description Example cos() double cos(double x) cosine of an angle of x sin(0.0)=0.0 sin() double sin(double x) sine of an angle of x cos(0.0)=1.0 tan() double tan(double x) tangent of an angle of x tan(0.0)=0.0 acos() double acos(double x) arc cosine of x asin() double asin(double x) arc sine of x atan() double atan(double x) arc tangent of x

Math Library Functions 19 Function Function definition Description Example sqrt() double sqrt(double x) square root of x sqrt(9.0)=3.0 exp() double exp(double x) exponential function e x exp(1.0)=2.718282 log() double log(double x) natural logarithm of x (base e) log10() double log10(double x) natural logarithm of x (base e) log(2.718282)=1.0 log10(100.0)=2.0 fabs() double fabs(double x) Absolute value of x abs(-2.3)=2.3 ceil() double ceil(double x) round x to the smallest integer not less than x floor() double floor(double x) round x to the largest integer not greater than x pow() double pow(double x, double y) x raised by power y (x y ) ceil(2.3)=3.0 ceil(-9.8)=-9.0 floor(2.7)=2.0 floor(-9.8)=-10 pow(2.0,3)=8.0 pow(4.0,0.5)=2.0

Outline 20 Functions: Program modules in C Function Definitions Function Prototypes Math Library Functions Headers Calling Functions: Call-by-value and Call-byreference Scope Rules Recursion

Headers 21 Standard library header files Contain function prototypes for library functions <stdlib.h>, <math.h>, etc Load with #include <filename> #include <math.h> Custom header files Create file with functions Save as filename.h Load in other files with #include "filename.h" Advantage: Reusability

Standard library header files 22 <assert.h> <ctype.h> Convert lowercase letters to uppercase letters and vice versa <errno.h> <float.h> <limits.h> <locale.h> <math.h> Math library functions <setjmp.h>

Standard library header files 23 <signal.h> <stdarg.h> <stddef.h> <stdio.h> Standard input/output library functions <stdlib.h> Convert number to text and text to number, memory allocation, random number, and other utility functions <string.h> String-processing functions <time.h> Time and date

Custom header files 24.c file #include myheader.h int main() { statements; void function1() { statements; return; myheader.h file #include <stdio.h> #include <stdlib.h> void function1(); int function2(int, int); int function2(int a, int b) { statements; return output;

Outline 25 Functions: Program modules in C Function Definitions Function Prototypes Math Library Functions Headers Calling Functions: Call-by-value and Call-byreference Scope Rules Recursion

Calling Functions 26 Call by value Passes copy of argument to function Changes in function do not effect original Use when function does not need to modify argument Avoids accidental changes Call by reference (or call by address) Passes original argument Changes in function effect original Only used with trusted functions

Example: Call by value 27 double foo (double); int main () { double area, r = 2.5; area = foo(r); printf( area: %f\n, area); return 0; double foo (double radius) { double a; a = 3.14159 * radius * radius; return a; Copy 2.5 to another memory block main() r 2.5 compute_area(r); foo() radius 2.5

Outline 28 Calling Functions: Call-by-value and Call-byreference Scope Rules Recursion

Scope Rules 29 Types of variables Local variable Can only be referenced inside a function body Global variable Identifier defined outside function, known in all functions Global variables, function definitions, function prototypes

Example: local variable 30 double foo (double); int main () { double area, r = 2.5; area = foo(r); printf( area: %f\n, area); return 0; double foo (double radius) { double a; a = 3.14159 * radius * radius; return a; Scope of area and r Scope of a and radius

Example: local variable 31 double foo (double); int main () { double area, r = 2.5; area = foo(r); printf( area: %f\n, area); return 0; double foo (double radius) { double a; a = 3.14159 * radius * radius; return a; main() area r 19.63 2.5 compute_area(r); Copy 19.63 Copy 2.5 foo() a radius 19.63 2.5

Example: local variable 32 double foo (double); int main () { double area, r = 2.5; area = foo(r); printf( area: %f r: %f\n, area, r); return 0; area: 7.07 r: 2.5 double foo (double r) { double area; r = 1.5; area = 3.14159 * r * r; return area; r in main() and foo() are two different variables occupying two memory blocks with the same name!! area 7.07 main() r 2.5 compute_area(r); Copy 7.07 area foo() r 7.07 2.5 1.5 Copy 2.5 Modifying the value of r in foo() does not affect the value of r in main()

Example: global variable 33 double foo (); double r; int main () { r = 2.5; double area; area = foo(); printf( area: %f\n, area); printf( r:%f\n,r_; return 0; double foo () { double area; r = 1.5; area = 3.14159 * r * r; return area; Scope of area in main() Scope of r Scope of area in foo()

Example: global variable 34 double foo (); double r; int main () { r = 2.5; double area; area = foo(); printf( area: %f\n, area); printf( r: %f\n, r); return 0; area: 7.07 r: 1.5 double foo () { double area; r = 1.5; area = 3.14159 * r * r; return area; r 2.5 1.5 main() area 7.07 compute_area(); Copy 7.07 foo() area 7.07

Example: global variable 35 double foo (); double r; int main () { r = 1; double area; area = foo(); printf( area: %f, r: %f\n, area, r); area = foo(); printf( area: %f, r: %f\n, area, r); return 0; double foo () { double area; area = 3.14159 * r * r; r++; return area; Copy 3.14 r 12 main() area 3.14 compute_area(); foo() area 3.14

Example: global variable 36 double foo (); double r; int main () { r = 1; double area; area = foo(); printf( area: %f, r: %f\n, area, r); area = foo(); printf( area: %f, r: %f\n, area, r); return 0; area: 3.14, r: 2 area: 12.57, r: 3 double foo () { double area; area = 3.14159 * r * r; r++; return area; r 32 main() area 12.57 3.14 compute_area(); Copy 12.57 foo() area 12.57

Calling Functions 37 Call by value Passes copy of argument to function Changes in function do not effect original Use when function does not need to modify argument Avoids accidental changes Call by reference Passes original argument Changes in function effect original Only used with trusted functions

Call by reference 38 The address of an argument is passed to a function Function definition function_name(data_type* arg_name) symbol *: pointer for getting the value stored in the specified address Calling function function_name(&variable_name); symbol &: get the address of a variable

Pointer 39 Address: 10008 *b 10 int a; b 10008 *b 10 10008 int *b; b = &a (assign the address of a to b) int main () { int a = 10; int * b = &a; printf( a: %d\n, a); printf( address of a: %d\n, b); printf( data pointed by b: %d\n, *b); return 0; output a: 10 address of a: 10008 data pointed by b: 10 *b (data pointed by b)

Example: Call by reference 40 double foo (double *); int main () { double area, r = 2.5; area = foo(&r); printf( area: %f r: %f\n, area, r); return 0; area main() r 2.5 compute_area(&r); Address 21220 Pass the address of r (&r = 21220) double foo (double * pr) { double area; *pr = 1.5; area = 3.14159 * (*pr) * (*pr); return area; area foo() pr 22110

Example: Call by reference 41 double foo (double); main() *pr r in main() is set to 1.5 int main () { double area, r = 2.5; area = foo(&r); printf( area: %f r: %f\n, area, r); return 0; area: 7.07 r: 1.5 double foo (double * pr) { double area; *pr = 1.5; area = 3.14159 * (*pr) * (*pr); return area; area 7.07 r 1.5 2.5 compute_area(&r); Assign 1.5 to *pr (=r) area foo() pr 7.07 22110 3.14 * (*pr) * (*pr) = 3.14 * 1.5 * 1.5 Address 21220

Sample-05-4: swap 42 Write a function to swap the values of two variables Why the following code does not work? void swap (int a, int b) { int tmp; tmp = a; a = b; b = tmp; printf( swap: a = %d; b = %d\n, a, b); int main() { int a = 10, b = 5; printf( main; a = %d; b = %d\n, a, b); swap (a, b); printf( main; a = %d; b = %d\n, a, b); return 0; Local variables in swap() a b 10 5 tmp 1 a b 10 3 10 5 5 2 a b 5 10 output main: a = 10; b = 5 swap: a = 5; b = 10 main: a = 10; b = 5

Sample-05-4: swap 43 *pa main() *pb void swap(int *, int *); int main() { int a = 10, b = 5; printf( main; a = %d; b = %d\n, a, b); swap (&a, &b); printf( main; a = %d; b = %d\n, a, b); return 0; void swap (int * pa, int * pb) { int tmp; tmp = *pa; *pa = *pb; *pb = tmp; 10000 a b 10004 10 5 10 5 swap(&a, &b) *pa *pb pa pb 10000 10004 tmp 10 swap()

Outline 44 Calling Functions: Call-by-value and Call-byreference Scope Rules Recursion

Recursion 45 Functions that call themselves Example void foo () { foo(); Termination condition is required to ensure that the function will eventually end and return

Example: factorials 46 void fac (int num) { //if (num <= 1) // return 1; //else Must have a termination condition return (num * fac(number - 1)); int main() { int a, result; scanf( %d, &a); result = fac(a); printf( %d!=%d\n, a, result); return 0; Recursive Call

Example: factorials 47 5! = 5 * 4 * 3 * 2 * 1 = 5 * 4! = 4 * 3 * 2 * 1 = 4 * 3! = 3 * 2 * 1 = 3 * 2! 5! = 120 = 5 * 24 = 24 = 4 * 6 = 6 = 3 * 2 return factorial(5) =120 return factorial(4) =24 return factorial(3) =6 return factorial(2) =2 void factorial (int num) { if (num <= 1) return 1; else return (num * fac(num - 1)); = 2 * 1 = 2 * 1! 1 = 2 = 2 * 1 1 return factorial(1) =1

Sample-05-5: Fibonacci series 48 0, 1, 1, 2, 3, 5, 8... Each number is the sum of the previous two fib( n ) = fib( n - 1 ) + fib( n 2 ) Terminate when n = 0 or n = 1 if(n == 0 n == 1) return n; + + fib(n) 0 n=0 1 1 2 3 5 8 n=1 n=2 n=3 n=4 n=5 n=6

Sample-05-5: Fibonacci series 49 fib(3) return fib(2) + fib(1) return fib(1) + fib(0) return 1 return 1 return 0