Introduction to Computing Lecture 08: Functions (Part I)

Slides:



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

Modular Programming With Functions
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
CS 201 Functions Debzani Deb.
Chapter 6: User-Defined Functions I
Introduction to Methods
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
Functions Lecture 4 – Section 2: 9/21/05 Section 4: 9/22/05.
More with Methods (parameters, reference vs. value, array processing) Corresponds with Chapters 5 and 6.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Procedures and Functions Computing Module 1. What is modular programming? Most programs written for companies will have thousands of lines of code. Most.
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.
1 CSE1301 Computer Programming Lecture 12 Functions (Part 1)
FUNCTIONS AND STRUCTURED PROGRAMMING CHAPTER 10. Introduction A c program is composed of at least one function definition, that is the main() function.
CPS120: Introduction to Computer Science Lecture 14 Functions.
1 CS161 Introduction to Computer Science Topic #9.
Function. Outline Intro. Functions Examples of Functions Prototypes of a Functions Local and Global Variables.
User defined functions
Computer Programming Rattapoom Waranusast Department of Electrical and Computer Engineering Faculty of Engineering, Naresuan University.
1 Structure of a C Program (continued) Presentation original from Dr. Turner’s class USF - COP C for Engineers Summer 2008.
1 CSE1301 Computer Programming Lecture 13 Functions (Part 1)
Algorithms and Programming Functions Lecture 28. Summary of Previous Lecture while statement for statement break statement Nested loops.
Chapter 3 Top-Down Design with Functions Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
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.
1 ICS103 Programming in C Lecture 8: Functions I.
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Functions Programming Applications. Functions every C program must have a function called main program execution always begins with function main any.
1 UMBC CMSC 104, Section Fall 2002 Functions, Part 1 of 3 Topics Top-down Design The Function Concept Using Predefined Functions Programmer-Defined.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
Functions, Part 1 of 3 Topics  Using Predefined Functions  Programmer-Defined Functions  Using Input Parameters  Function Header Comments Reading 
1 CSE1301 Computer Programming Lecture 12 Functions (Part 1)
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
UMBC CMSC 104 – Section 01, Fall 2016
User-Written Functions
Chapter 6: User-Defined Functions I
Lesson #6 Modular Programming and Functions.
Lesson #6 Modular Programming and Functions.
Functions and Structured Programming
Topic: Functions – Part 2
Functions Dr. Sajib Datta
2011/11/20: Lecture 15 CMSC 104, Section 4 Richard Chang
11/10/2018.
Lesson #6 Modular Programming and Functions.
2008/11/05: Lecture 15 CMSC 104, Section 0101 John Y. Park
2008/11/24: Lecture 19 CMSC 104, Section 0101 John Y. Park
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
2008/11/24: Lecture 19 CMSC 104, Section 0101 John Y. Park
Functions I Creating a programming with small logical units of code.
CSI 121 Structured Programming Language Lecture 13 Functions (Part 1)
Functions, Part 1 of 3 Topics Using Predefined Functions
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Assist.Prof.Dr. Nükhet ÖZBEK Ege University
Lesson #6 Modular Programming and Functions.
Functions, Part 1 of 3 Topics Using Predefined Functions
CS149D Elements of Computer Science
In C Programming Language
Introduction to Computing Lecture 09: Functions (Part II)
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.
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Functions, Part 2 of 42 Topics Functions That Return a Value
CPS125.
Presentation transcript:

Introduction to Computing Lecture 08: Functions (Part I) Assist.Prof.Dr. Nükhet ÖZBEK Ege University Department of Electrical & Electronics Engineering nukhet.ozbek@ege.edu.tr

Topics Uses of functions Functions Parameters Return values

Uses of functions Top-Down design or divide-and-conquer It is easier to solve multiple smaller problems instead of one big problem

Top-down design Suppose, we want to list parts of an automobile Automobile self starter Bench seat Brakes Bumper Buzzer Car battery Car doors Stop lamp Clutch Dashboard Exhaust pipe Fuel pump Grille Headlight Muffler Odometer …

Top-down design It is easier to first divide the problem into sub problems: Chassis Motor parts Electronic parts … and then, list the parts under sub categories

Uses of functions Top-Down design or divide-and-conquer It is easier to solve multiple smaller problems instead of one big problem It is easier to debug sub problems In case of an error, it is easy to isolate the problem to a specific section of code (a specific function)

Uses of functions Top-Down design or divide-and-conquer It is easier to solve multiple smaller problems instead of one big problem It is easier to debug sub problems A team of programmers can work on different sub problems and join sub problems later to form the solution

Uses of functions Top-Down design or divide-and-conquer Code reuse It is easier to solve multiple smaller problems instead of one big problem It is easier to debug sub problems A team of programmers can work on different sub problems and join sub problems later to form the solution Code reuse

Code reuse Suppose we want to find ab and cd power1 = 1; for (count = b ; count > 0 ; count--) power1 *= a; power2 = 1; for (count = d ; count > 0 ; count--) power2 *= c;

Code reuse Suppose we want to find ab and cd power1 = power(a,b); power2 = power(c,d); No need to write the same code each time if we use functions We can also use this function in another program, either simply by copy-paste or adding it to a user defined library as we will see later

User-Defined Functions Can create your own functions, similar to printf() or sqrt() Implements the subroutine/ procedure/ module/ function definitions of an algorithm

Writing User-defined Functions Need to specify: the name of the function its parameters (input arguments) what it returns (output arguments) block of statements to be carried out when the function is called The block of statements is called the “function body”

Writing User-defined Functions type-specifier function_name(parameter list) { body of function } type-specifier is the type of value the function returns using the return statement Can be any valid type If no type specified, assumes int Can be void -> does not return anything

Example: hello1.c Prints a simple greeting. procedure sayHello { output “Hello World!” } Main Program do procedure sayHello

Example: hello1.c #include <stdio.h> /* * Print a simple greeting. */ void sayHello ( void ) { printf(“Hello World!\n”); } * Call a function which prints a * simple greeting. int main() sayHello(); return 0; Prints a simple greeting. procedure sayHello { output “Hello World!” } Main Program do procedure sayHello

Function definition Function call Example: hello1.c #include <stdio.h> /* * Print a simple greeting. */ void sayHello ( void ) { printf(“Hello World!\n”); } * Call a function which prints a * simple greeting. int main() sayHello(); return 0; Function definition Function call

Function name Function body Example: hello1.c #include <stdio.h> /* * Print a simple greeting. */ void sayHello ( void ) { printf(“Hello World!\n”); } * Call a function which prints a * simple greeting. int main() sayHello(); return 0; Function name Function body

Return type Formal Parameter List Example: hello1.c #include <stdio.h> /* * Print a simple greeting. */ void sayHello ( void ) { printf(“Hello World!\n”); } * Call a function which prints a * simple greeting. int main() sayHello(); return 0; Return type Formal Parameter List

Parameters Information passed to a function “Formal” parameters are local variables declared in the function declaration “Actual” parameters are variables or values passed to the function when it is called

Parameters (aka Arguments) Example: badsort.c /* Print two numbers in order. */ void badSort ( int a, int b ) { if ( a > b ) printf("%d %d\n", b, a); } else printf("%d %d\n", a, b); Parameters (aka Arguments)

Old style. Example: badsort2.c /* Print two numbers in order. */ void badSort ( a, b ) int a; int b; { if ( a > b ) printf("%d %d\n", b, a); } else printf("%d %d\n", a, b); Old style.

Example: badsort.c /* Print two numbers in order. */ void badSort ( int a, int b ) { if ( a > b ) printf("%d %d\n", b, a); } else printf("%d %d\n", a, b);

Formal parameters Actual parameters Example: badsort.c Formal parameters /* Print two numbers in order. */ void badSort ( int a, int b ) { if ( a > b ) printf("%d %d\n", b, a); } else printf("%d %d\n", a, b); Actual parameters int main() { int x = 3, y = 5; badSort ( 10, 9 ); badSort ( y, x + 4 ); return 0; }

Parameters (cont.) Parameters are passed by copying the value of the actual parameters to the formal parameters Changes to formal parameters do not affect the value of the actual parameters This type of function call is called call-by-value

Example: badswap.c int main() { int a = 3, b = 5; /* Swap the values of two variables. */ void badSwap ( int a, int b ) { int temp; temp = a; a = b; b = temp; printf("%d %d\n", a, b); } int main() { int a = 3, b = 5; printf("%d %d\n", a, b); badSwap ( a, b ); return 0; }

Example: badswap.c Output: 3 5 int main() { int a = 3, b = 5; /* Swap the values of two variables. */ void badSwap ( int a, int b ) { int temp; temp = a; a = b; b = temp; printf("%d %d\n", a, b); } int main() { int a = 3, b = 5; printf("%d %d\n", a, b); badSwap ( a, b ); return 0; } Output: 3 5

Example: badswap.c Output: 3 5 5 3 int main() { int a = 3, b = 5; /* Swap the values of two variables. */ void badSwap ( int a, int b ) { int temp; temp = a; a = b; b = temp; printf("%d %d\n", a, b); } int main() { int a = 3, b = 5; printf("%d %d\n", a, b); badSwap ( a, b ); return 0; } Output: 3 5 5 3

Example: badswap.c Output: 3 5 5 3 int main() { int a = 3, b = 5; /* Swap the values of two variables. */ void badSwap ( int a, int b ) { int temp; temp = a; a = b; b = temp; printf("%d %d\n", a, b); } int main() { int a = 3, b = 5; printf("%d %d\n", a, b); badSwap ( a, b ); return 0; } Output: 3 5 5 3

Called function’s environment: Calling function’s environment: Example: badswap.c /* Swap the values of two variables. */ void badSwap ( int a, int b ) { int temp; temp = a; a = b; b = temp; printf("%d %d\n", a, b); } int main() { int a = 3, b = 5; printf("%d %d\n", a, b); badSwap ( a, b ); return 0; } Called function’s environment: Calling function’s environment: a: 5 b: 3 a: 3 b: 5

Parameters (cont.) If a function does not take parameters, declare its formal argument list void or do not write anything. void sayHello ( void ) { printf(“Hello World!\n”); } Declaration: void sayHello () { printf(“Hello World!\n”); } Also valid: Function call: sayHello();

Parameters (cont.) The number of actual arguments used in a call to a function must be the same as the number of formal parameters listed in the function definition The order of arguments in the lists determines correspondence. The first actual argument corresponds to the first formal parameter, and so on.

Parameters (cont.) Each actual argument must be of a data type that can be assigned to the corresponding formal parameter

Functions – “Do”s and “Don’t”s DO use a function name that describes the purpose of the function DON'T pass values to a function that it doesn't need DON'T try to pass fewer (or more) arguments to a function than there are parameters. In C programs, the number of arguments passed must match the number of parameters

Notice there can be multiple return statements Return from a Function When the last statement is executed void sayHello ( void ) { printf(“Hello World!\n”); } When a return statement is encountered int max (int a, int b) if(a>b) return a; return b; Notice there can be multiple return statements

Return Values Values are returned by copying a value specified after the return keyword All functions, except those of type void, return a value

Example: maxmin.c Return type int max (int a, int b) { int result; /* Returns the larger of two numbers. */ int max (int a, int b) { int result; if (a > b) result = a; } else result = b; return result;

The value of the expression max(7,5) is the integer 7. Example: maxmin.c /* Returns the larger of two numbers. */ int max (int a, int b) { int result; if (a > b) result = a; } else result = b; return result; For example: The value of the expression max(7,5) is the integer 7.

Example: maxmin.c This style okay. int max (int a, int b) { /* Returns the larger of two numbers. */ int max (int a, int b) { int result; if (a > b) result = a; } else result = b; return result;

Example: maxmin.c Version 2: int max (int a, int b) { if (a > b) /* Returns the larger of two numbers. */ int max (int a, int b) { if (a > b) return a; } else return b; Version 2:

Example: maxmin.c Version 3: Note: /* Returns the larger of two numbers. */ int max (int a, int b) { if (a > b) b = a; } return b; Version 3: Note: Changing the value of b does not affect the actual parameter in the function call.

Example: maxmin.c Or you can write #include <stdio.h> /* Returns the larger of two numbers. */ int max (int a, int b) { if (a > b) return a; } else return b; /* Returns the smaller of two numbers. */ int min (int a, int b) { if (a < b) return a; } else return b; int main() { int maxOfMins = max(min(1,2), min(3,4)); printf("%d\n", maxOfMins); return 0; } Or you can write printf("%d\n", max(min(1,2), min(3,4)));

Return Values (cont.) If a function does not return a value, declare its return type as void Declaration: void sayHello ( void ) { printf(“Hello World!\n”); } Function call: sayHello();

Return Values (cont.) As long as a function is not declared as void, it can be used as an operand in any valid C expression x = power(y); if(max(x,y) > 100) printf(“greater”);

Return Values (cont.) However, a function can not be the target of an assignment swap(x,y) = 100; /* incorrect statement */ A function declared as void can not be used in any expression void f(); ... t = f(); /* incorrect */

Return Values (cont.) If you do not assign the return value of a function it is lost int multiply(int a, int b); int main() { x = multiply(5,4); printf(“%d”, multiply(2,3)); multiply(8,3); /* lost */ }

Functions – “Do”s and “Don’t”s DON'T try to return a value that has a type different from the function's type DON'T let functions get too long. If a function starts getting long, try to break it into separate, smaller tasks DO limit each function to a single task DON'T have multiple return statements if they aren't needed. You should try to have one return when possible; however, sometimes having multiple return statements is easier and clearer