User Defined Functions 1 Outline

Similar documents
User Defined Functions 2 Outline

1. User-Defined Functions & Subroutines Part 1 Outline

Array Lesson 1 Outline

1. User-Defined Functions & Subroutines Part 2 Outline

Array Lesson 2 Outline

CS Spring 2018 Homework #11 Quiz to be held in class 9:30-9:45am Mon Apr

1. Idiotproofing Outline. Idiotproofing Lesson CS1313 Fall

while Loop Example #1

for Loop Lesson 3 Outline

for Loop Lesson 1 Outline

Arithmetic Expressions Lesson #1 Outline

Absolute Value. if Lesson 1 CS1313 Spring

for Loop Lesson 2 Outline

while Loop Outline while Loop Lesson CS1313 Spring

Nested if Lesson Outline

CS : Programming for Non-Majors, Fall 2018 Programming Project #5: Big Statistics Due by 10:20am Wednesday November

Character Strings Lesson Outline

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

CS Fall 2007 Homework #5

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3

Constants Lesson Outline

Arithmetic Expressions in C

Numeric Data Types Outline

printf( Please enter another number: ); scanf( %d, &num2);

A Pointer Experiment. Take out a sheet of scrap paper. Tear it in half. Tear it in half again.

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

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

CS Spring 2018 Homework #5

Software Lesson 1 Outline

BSM540 Basics of C Language

C introduction: part 1

Boolean Data Outline

Computer Science & Engineering 150A Problem Solving Using Computers

Fundamentals of Programming Session 8

Boolean Data Lesson #2 Outline

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

CS113: Lecture 4. Topics: Functions. Function Activation Records

CSE 2421: Systems I Low-Level Programming and Computer Organization. Functions. Presentation C. Predefined Functions

Computer Programming: Skills & Concepts (CP) arithmetic, if and booleans (cont)

Lecture 04 FUNCTIONS AND ARRAYS

User Defined Functions

C: How to Program. Week /Apr/23

Procedural programming with C

Engineering program development 7. Edited by Péter Vass

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

Unit 7. Functions. Need of User Defined Functions

2. Numbers In, Numbers Out

CS : Programming for Non-majors, Summer 2007 Programming Project #2: Census Due by 12:00pm (noon) Wednesday June

Slide Set 2. for ENCM 335 in Fall Steve Norman, PhD, PEng

Lecture 9 - C Functions

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

Chapter 11 Introduction to Programming in C

COP 3275: Chapter 09. Jonathan C.L. Liu, Ph.D. CISE Department University of Florida, USA

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

Chapter 3. Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus. Existing Information.

C-Programming. CSC209: Software Tools and Systems Programming. Paul Vrbik. University of Toronto Mississauga

Chapter 4 Defining Classes I

CpSc 1011 Lab 4 Formatting and Flow Control Windchill Temps

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

OBJECTIVE QUESTIONS: Choose the correct alternative:

Standard Library Functions Outline

CS3157: Advanced Programming. Outline

Engineering 12 - Spring, 1999

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 12, FALL 2012

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

CSc Introduction to Computing

Technical Questions. Q 1) What are the key features in C programming language?

Fundamental of Programming (C)

2. Numbers In, Numbers Out

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Krste Asanović & Randy Katz

Agenda. Components of a Computer. Computer Memory Type Name Addr Value. Pointer Type. Pointers. CS 61C: Great Ideas in Computer Architecture

Chapter 11 Introduction to Programming in C

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

Dynamic memory allocation

Arithmetic Expressions Lesson #2 Outline

C Pointers. Indirection Indirection = referencing a value through a pointer. Creating Pointers. Pointer Declarations. Pointer Declarations

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

CS : Programming for Non-majors, Fall 2017 Commenting if Blocks

Pointer Lesson 2 Outline

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

EL2310 Scientific Programming

Learning to Program with Haiku

CS : Programming for Non-majors, Fall 2018 Programming Project #2: Census Due by 10:20am Wednesday September

Basic Types and Formatted I/O

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

Programming & Data Structure: CS Section - 1/A DO NOT POWER ON THE MACHINE

Chapter 7 Functions. Now consider a more advanced example:

LESSON 5 FUNDAMENTAL DATA TYPES. char short int long unsigned char unsigned short unsigned unsigned long

COMP s1 Lecture 1

Functions. Systems Programming Concepts

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

What we have learned so far

CSE 230 Intermediate Programming in C and C++ Functions

File I/O Lesson Outline

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting

C Functions. 5.2 Program Modules in C

Lab 5 Pointers and Arrays

Programming and Data Structure

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

Transcription:

User Defined Functions 1 Outline 1. User Defined Functions 1 Outline 2. Standard Library Not Enough #1 3. Standard Library Not Enough #2 4. Calling a Function Instead 5. Why User-Defined Functions? 6. User-Defined taxicab_norm 7. User-Defined Function Properties 8. Declarations Valid in Own Function #1 9. Declarations Valid in Own Function #2 10. Return Type 11. List of Arguments 12. Names of Arguments 13. Array Arguments 14. Local Variables & Named Constants #1 15. Local Variables & Named Constants #2 16. Returning the Return Value #1 17. Returning the Return Value #2 18. Declarations Inside Functions #1 19. Declarations Inside Functions #2 20. Declarations Inside Functions #3 22. General Form of Function Definitions 23. User-Defined Function Example #1 24. User-Defined Function Example #2 25. User-Defined Function Example #3 26. User-Defined Function Example #4 27. User-Defined Function Example #5 28. Another Used-Defined Function #1 29. Another Used-Defined Function #2 30. Another Used-Defined Function #3 31. Another Function Example #1 32. Another Function Example #2 33. Another Function Example #3 34. Function Prototype Declarations #1 35. Function Prototype Declarations #2 36. Actual Arguments & Formal Arguments 37. Actual Arguments 38. Formal Arguments 39. Yet Another Function Example #1 40. Yet Another Function Example #2 41. Yet Another Function Example #3 CS1313 Fall 2017 1

Standard Library Not Enough #1 Often, we have a particular kind of value that we need to calculate over and over again, under a variety of circumstances. For example, in PP#5, we have to calculate the taxicab norm of the elements of each array. taxicab_norm1 = initial_sum; for (element = first_element; element < number_of_elements; element++) { taxicab_norm1 += fabs(input_value1[element]); } /* for element */ CS1313 Fall 2017 2

Standard Library Not Enough #2 We know that the algorithm for calculating the taxicab norm of the elements of an array is always the same. So why should we have to write the same piece of code over and over and over and over and over? Wouldn t it be better if we could write that piece of code just once and then reuse it in many applications? CS1313 Fall 2017 3

Calling a Function Instead So, it d be nice to replace this code: taxicab_norm1 = initial_sum; for (element = first_element; element < number_of_elements; element++) { taxicab_norm1 += input_value1[element]; } /* for element */ with calls to a function that would calculate the taxicab norm for any array: taxicab_norm1 = taxicab_norm(input_value1, number_of_elements); CS1313 Fall 2017 4

Why User-Defined Functions? taxicab_norm1 = taxicab_norm(input_value1, number_of_elements);... taxicab_norm2 = taxicab_norm(input_value2, number_of_elements); Obviously, the designers of C weren t able to anticipate the zillion things that we might need functions to do such as calculate the taxicab norm of the elements of an array. So there are no standard library functions to calculate something that is application-specific. Instead, we as C programmers are going to have to define our own function to do it. CS1313 Fall 2017 5

User-Defined taxicab_norm float taxicab_norm(float* array, int number_of_elements) { /* taxicab_norm */ const float initial_sum = 0.0; const int minimum_number_of_elements = 1; const int first_element = 0; const int program_failure_code = -1; float sum; int element; if (number_of_elements < minimum_number_of_elements) { printf("error: can't have an array of length %d:\n", number_of_elements); printf(" it must have at least %d element.\n", minimum_number_of_elements); exit(program_failure_code); } /* if (number_of_elements <...) */ if (array == (float*)null) { printf("error: can't calculate the taxicab norm of "); printf("a nonexistent array.\n"); exit(program_failure_code); } /* if (array == (float*)null) */ sum = initial_sum; for (element = first_element; element < number_of_elements; element++) { sum = sum + fabs(array[element]); } /* for element */ return sum; } /* taxicab_norm */ CS1313 Fall 2017 6

User-Defined Function Properties In general, the definition of a user-defined function looks a lot like a program, except for the following things: 1. The function header begins with a return type that is appropriate for that function (for example, int, float, char). 2. The function has a name that is chosen by the programmer. 3. At the end of the function header is a list of arguments, enclosed in parentheses and separated by commas, each argument preceded by its data type. 4. The function may declare local named constants and local variables. 5. In the body of the function, the return statement tells the function what value to return to the statement that called the function. CS1313 Fall 2017 7

Declarations Valid in Own Function #1 float taxicab_norm (float* array, int number_of_elements) { /* taxicab_norm */ const float initial_sum = 0.0; const int minimum_number_of_elements = 1; const int first_element = 0; const int program_failure_code = -1; float sum; int element;... } /* taxicab_norm */ The compiler treats each function completely independently of the others. Most importantly, the declarations inside a function including the declarations of its arguments apply only to that function, not to any others. CS1313 Fall 2017 8

Declarations Valid in Own Function #2 float taxicab_norm (float* array, int number_of_elements) { /* taxicab_norm */ const float initial_sum = 0.0; const int minimum_number_of_elements = 1; const int first_element = 0; const int program_failure_code = -1; float sum; int element;... } /* taxicab_norm */ For example: The declaration of initial_sum in the function taxicab_norm is visible only to the function taxicab_norm but not to the main function, nor to any other function. If another function wants to have the same named constant, it has to have its own declaration of that named constant. CS1313 Fall 2017 9

Return Type float taxicab_norm (float* array, int number_of_elements) { /* taxicab_norm */... } /* taxicab_norm */ In the function header, immediately before the function name is a data type. This data type specifies the return type, which is the data type of the value that the function will return. The return type (for now) must be a basic scalar type (for example, int, float, char). Notice that the return type of the function is declared, but in a weird way (in the function header, before the function name). CS1313 Fall 2017 10

List of Arguments float taxicab_norm (float* array, int number_of_elements) { /* taxicab_norm */... } /* taxicab_norm */ At the end of the function header, immediately after the function name, is a list of arguments, enclosed in parentheses and separated by commas, each argument preceded by its data type. Thus, the function s arguments are declared, but not in the function s declaration section. CS1313 Fall 2017 11

Names of Arguments float taxicab_norm (float* array, int number_of_elements) { /* taxicab_norm */... } /* taxicab_norm */ The names of the arguments in the function definition DON T have to match the names of the arguments that are passed into the function by the main function (or by whatever other function) that calls the function. They should be meaningful with respect to the function in which they occur, NOT with respect to the function(s) that call(s) that function. CS1313 Fall 2017 12

Array Arguments float taxicab_norm (float* array, int number_of_elements) When passing an array argument, you must also pass an argument that represents the length of the array. Not surprisingly, this length argument should be of type int. Also, when passing an array argument, you have two choices about how to express the argument s data type. The first is above; the second is below: float taxicab_norm (float array[], int number_of_elements) In CS1313, we prefer * notation to [] notation. CS1313 Fall 2017 13

Local Variables & Named Constants #1 float taxicab_norm (float* array, int number_of_elements) { /* taxicab_norm */ const float initial_sum = 0.0; const int minimum_number_of_elements = 1; const int first_element = 0; const int program_failure_code = -1; float sum; int element;... } /* taxicab_norm */ The function s declaration section may contain declarations of local named constants and local variables. These names that are valid ONLY within the function that is being defined. On the other hand, these same names can be used with totally different meanings by other functions (and by the calling function). CS1313 Fall 2017 14

Local Variables & Named Constants #2 float taxicab_norm (float* array, int number_of_elements) { /* taxicab_norm */ const float initial_sum = 0.0; const int minimum_number_of_elements = 1; const int first_element = 0; const int program_failure_code = -1; float sum; int element;... } /* taxicab_norm */ Good programming style requires declaring: 1. local named constants, followed by 2. local variables inside the function definition. Note that these declarations should occur in the usual order. CS1313 Fall 2017 15

Returning the Return Value #1 float taxicab_norm (float* array, int number_of_elements) { /* taxicab_norm */... sum = initial_sum; for (element = first_element; element < number_of_elements; element++) { sum = sum + fabs(array[element]); } /* for element */ return sum; } /* taxicab_norm */ In the body of the function, the return statement tells the function to return the return value. If the function does not return a value, then the compiler may get upset. The return value is returned to the statement that called the function, and in some sense replaces the function call in the expression where the function call appears. CS1313 Fall 2017 16

Returning the Return Value #2 float taxicab_norm (float* array, int number_of_elements) { /* taxicab_norm */... sum = initial_sum; for (element = first_element; element < number_of_elements; element++) { sum = sum + fabs(array[element]); } /* for element */ return sum; } /* taxicab_norm */ The return value is returned to the statement that called the function, and in some sense replaces the function call in the expression where the function call appears. taxicab_norm1 = taxicab_norm(input_value1, number_of_elements);... taxicab_norm2 = taxicab_norm(input_value2, number_of_elements); CS1313 Fall 2017 17

Declarations Inside Functions #1 The following point is EXTREMELY important: For our purposes, the only user-defined identifiers that a given function is aware of whether it s the main function or otherwise are those that are explicitly declared in the function s declaration section, or in the function s argument list. (The above statement isn t literally true, but is true enough for our purposes.) CS1313 Fall 2017 18

Declarations Inside Functions #2 Thus, a function is aware of: 1. its arguments, if any; 2. its local named constants, if any; 3. its local variables, if any; 4. other functions that it has declared prototypes for, if any (described later). CS1313 Fall 2017 19

Declarations Inside Functions #3 The function knows NOTHING AT ALL about variables or named constants declared inside any other function. It isn t aware that they exist and cannot use them. Therefore, the ONLY way to send information from one function to another is by passing arguments from the calling function to the called function. CS1313 Fall 2017 20

General Form of Function Definitions returntype funcname ( datatype1 arg1, datatype2 arg2,... ) { /* funcname */ const localconst1type localconst1 = localvalue1; const localconst2type localconst2 = localvalue2;... localvar1type localvar1; localvar2type localvar2;... [ function body: does stuff ] return returnvalue; } /* funcname */ CS1313 Fall 2017 21

#include <stdio.h> #include <stdlib.h> #include <math.h> User-Defined Function Example #1 int main () { /* main */ const int first_element = 0; const int program_failure_code = -1; const int program_success_code = 0; const int minimum_number_of_elements = 1; float* input_value1 = (float*)null; float taxicab_norm1; int number_of_elements, element; float taxicab_norm(float* array, int number_of_elements); Function prototype CS1313 Fall 2017 22

User-Defined Function Example #2 printf("how many elements are in the array\n"); printf(" (at least %d)?\n", minimum_number_of_elements); scanf("%d", &number_of_elements); if (number_of_elements < minimum_number_of_elements) { printf( "ERROR: There must be at least %d elements\n", minimum_number_of_elements); exit(program_failure_code); } /* if (number_of_elements <...) */ Idiotproof as soon as you input! CS1313 Fall 2017 23

User-Defined Function Example #3 input_value1 = (float*)malloc(sizeof(float) * number_of_elements); if (input_value1 == (float*)null) { printf("error: can't allocate a float array"); printf(" of %d elements.\n", number_of_elements); exit(program_failure_code); } /* if (input_value1 == (float*)null) */ Once you know the array length, you can dynamically allocate the array. IMMEDIATELY after dynamically allocating the array, check that the allocation succeeded. CS1313 Fall 2017 24

User-Defined Function Example #4 printf("what are the %d elements?\n", number_of_elements); for (element = first_element; element < number_of_elements; element++) { scanf("%f", &input_value1[element]); } /* for element */ taxicab_norm1 = taxicab_norm(input_value1, number_of_elements); printf("the taxicab norm of "); printf("the %d elements is %f.\n", number_of_elements, taxicab_norm1); free(input_value1); input_value1 = (float*)null; return program_success_code; } /* main */ Function call CS1313 Fall 2017 25

User-Defined Function Example #5 % gcc -o taxicab_norm_func_test_all \ taxicab_norm_func_test_all.c taxicab_norm.c % taxicab_norm_func_test_all How many elements are in the array (at least 1)? 5 What are the 5 elements? 1.5 2.5 3.5 4.5 5.5 The taxicab norm of the 5 elements is 17.500000. CS1313 Fall 2017 26

Another Used-Defined Function #1 float cube_root (float base) { /* cube_root */ const float cube_root_power = 1.0 / 3.0; return pow(base, cube_root_power); } /* cube_root */ What can we say about this user-defined function? 1. Its name is cube_root. 2. Its return type is float. 3. It has one argument, base, whose type is float. 4. It has one local named constant, cube_root_power. 5. It has no local variables. 6. It calculates and returns the cube root of the incoming argument. CS1313 Fall 2017 27

Another Used-Defined Function #2 float cube_root (float base) { /* cube_root */ const float cube_root_power = 1.0 / 3.0; return pow(base, cube_root_power); } /* cube_root */ So, cube_root calculates the cube root of a float argument and returns a float result whose value is the cube root of the argument. Notice that cube_root simply calls the C standard library function pow, using a specific named constant for the exponent. We say that cube_root is a wrapper around pow, or more formally that cube_root encapsulates pow. CS1313 Fall 2017 28

Another Used-Defined Function #3 float cube_root (float base) { /* cube_root */ const float cube_root_power = 1.0 / 3.0; return pow(base, cube_root_power); } /* cube_root */ Does the name of a user-defined function have to be meaningful? From the compiler s perspective, absolutely not; you could easily have a function named square_root that always returns 12. But from the perspective of programmers, that d be a REALLY REALLY BAD IDEA, and you d get a VERY BAD GRADE. CS1313 Fall 2017 29

Another Function Example #1 #include <stdio.h> #include <stdlib.h> #include <math.h> int main () { /* main */ const int number_of_elements = 3; const int program_success_code = 0; float input_value1, cube_root_value1; float input_value2, cube_root_value2; float input_value3, cube_root_value3; float cube_root(float base); Function prototype printf("what %d real numbers would you\n", number_of_elements); printf(" like the cube roots of?\n"); scanf("%f %f %f", &input_value1, &input_value2, &input_value3); CS1313 Fall 2017 30

Another Function Example #2 cube_root_value1 = cube_root(input_value1); cube_root_value2 = cube_root(input_value2); cube_root_value3 = cube_root(input_value3); printf("the cube root of %f is %f.\n", input_value1, cube_root_value1); printf("the cube root of %f is %f.\n", input_value2, cube_root_value2); printf("the cube root of %f is %f.\n", input_value3, cube_root_value3); return program_success_code; } /* main */ Function calls CS1313 Fall 2017 31

Another Function Example #3 % gcc -o cube_root_scalar \ cube_root_scalar.c cube_root.c -lm % cube_root_scalar What 3 real numbers would you like the cube roots of? 1 8 25 The cube root of 1.000000 is 1.000000. The cube root of 8.000000 is 2.000000. The cube root of 25.000000 is 2.924018. CS1313 Fall 2017 32

Function Prototype Declarations #1 #include <stdio.h> #include <stdlib.h> #include <math.h> int main () { /* main */ const int number_of_elements = 3; const int program_success_code = 0; float input_value1, cube_root_value1; float input_value2, cube_root_value2; float input_value3, cube_root_value3; float cube_root(float base);... } /* main */ Notice this declaration: float cube_root(float base); This declaration is a function prototype declaration. CS1313 Fall 2017 33

Function Prototype Declarations #2 float cube_root(float base); This declaration is a function prototype declaration. The function prototype declaration tells the compiler that there s a function named cube_root with a return type of float, and that it s declared external to (outside of) the function that s calling the cube_root function. You MUST declare prototypes for the functions that you re calling. Otherwise, the compiler will assume that, by default, the function returns an int and has no arguments. If that turns out not to be the case (that is, most of the time), then the compiler will become ANGRY. CS1313 Fall 2017 34

Actual Arguments & Formal Arguments #include <stdio.h> #include <stdlib.h> #include <math.h> int main () { /* main */... cube_root_value1 = cube_root(input_value1); cube_root_value2 = cube_root(input_value2); cube_root_value3 = cube_root(input_value3);... } /* main */ float cube_root (float base) { /* cube_root */... } /* cube_root */ When we talk about the arguments of a function, we re actually talking about two very different kinds of arguments: actual arguments and formal arguments. CS1313 Fall 2017 35

Actual Arguments #include <stdio.h> #include <math.h> int main () { /* main */... cube_root_value1 = cube_root(input_value1); cube_root_value2 = cube_root(input_value2); cube_root_value3 = cube_root(input_value3);... } /* main */ The arguments that appear in the call to the function for example, input_value1, input_value2 and input_value3 in the program fragment above are known as actual arguments, because they re the values that actually get passed to the function. Mnemonic: The actual arguments are in the function Call. CS1313 Fall 2017 36

Formal Arguments float cube_root (float base) { /* cube_root */... } /* cube_root */ The arguments that appear in the definition of the function for example, base, in the function fragment above are known as formal arguments, because they re the names that are used in the formal definition of the function. Jargon: Formal arguments are also known as dummy arguments. Mnemonic: The Formal arguments are in the function definition. CS1313 Fall 2017 37

Yet Another Function Example #1 #include <stdio.h> #include <math.h> int main () { /* main */ const int first_element = 0; const int number_of_elements = 5; const int program_success_code = 0; float input_value[number_of_elements]; float cube_root_value[number_of_elements]; int element; float cube_root(float base); printf("what %d real numbers would you\n", number_of_elements); printf(" like the cube roots of?\n"); for (element = first_element; element < number_of_elements; element++) { scanf("%f", &input_value[element]); } /* for element */ CS1313 Fall 2017 38

Yet Another Function Example #2 for (element = first_element; element < number_of_elements; element++) { cube_root_value[element] = cube_root(input_value[element]); } /* for element */ for (element = first_element; element < number_of_elements; element++) { printf("the cube root of %f is %f.\n", input_value[element], cube_root_value[element]); } /* for element */ return program_success_code; } /* main */ CS1313 Fall 2017 39

Yet Another Function Example #3 % gcc -o cube_root_array \ cube_root_array.c cube_root.c -lm % cube_root_array What 5 real numbers would you like the cube roots of? 1 8 25 27 32 The cube root of 1.000000 is 1.000000. The cube root of 8.000000 is 2.000000. The cube root of 25.000000 is 2.924018. The cube root of 27.000000 is 3.000000. The cube root of 32.000000 is 3.174802. CS1313 Fall 2017 40