User-Written Functions

Slides:



Advertisements
Similar presentations
Spring Semester 2013 Lecture 5
Advertisements

Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 12P. 1Winter Quarter User-Written Functions.
C Structures and Memory Allocation There is no class in C, but we may still want non- homogenous structures –So, we use the struct construct struct for.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Lecture 2 Introduction to C Programming
Introduction to C Programming
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
CS1061 C Programming Lecture 2: A Few Simple Programs A. O’Riordan, 2004.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
Guide To UNIX Using Linux Third Edition
Introduction to C Programming
Functions in C. Function Terminology Identifier scope Function declaration, definition, and use Parameters and arguments Parameter order, number, and.
Chapter 4:Functions| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2005 Slide 1 Functions Lecture 4 by Jumail Bin.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
/* Documentations */ Pre process / Linking statements Global declarations; main( ) { Local Declarations; Program statements / Executable statements; }
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.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 12P. 1Winter Quarter User-Written Functions Lecture 12.
Pointers *, &, array similarities, functions, sizeof.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
1 CSC103: Introduction to Computer and Programming Lecture No 16.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Programming Fundamentals Enumerations and Functions.
Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
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.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Introduction to C Topics Compilation Using the gcc Compiler
Chapter 1.2 Introduction to C++ Programming
Chapter 9: Value-Returning Functions
Chapter 1.2 Introduction to C++ Programming
Chapter 6 - Functions modular programming general function format
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Lesson #6 Modular Programming and Functions.
Chapter 2 - Introduction to C Programming
Lesson #6 Modular Programming and Functions.
Chapter 2, Part I Introduction to C Programming
Algorithms Problem: Write pseudocode for a program that keeps asking the user to input integers until the user enters zero, and then determines and outputs.
Module 4 Functions – function definition and function prototype.
Chapter 2 - Introduction to C Programming
Programmazione I a.a. 2017/2018.
Lesson #6 Modular Programming and Functions.
Functions Inputs Output
User Defined Functions
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
Chapter 4 void Functions
Chapter 2 - Introduction to C Programming
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
Introduction to C Topics Compilation Using the gcc Compiler
Chapter 2 - Introduction to C Programming
A First Book of ANSI C Fourth Edition
Chapter 6: User-Defined Functions I
Chapter 9: Value-Returning Functions
Lesson #6 Modular Programming and Functions.
Introduction to C Topics Compilation Using the gcc Compiler
Chapter 2 - Introduction to C Programming
Functions Imran Rashid CTO at ManiWeber Technologies.
Introduction to C Topics Compilation Using the gcc Compiler
Introduction to C Programming
CPS125.
Switch Case Structures
Presentation transcript:

User-Written Functions Lecture 12 Narrator: Lecture 12: User-Written Functions. Winter Quarter

User-Written Functions So far, we have written only one function ourselves. That is function is called "main ( )". The syntax used has been as follows: void main ( ) { /* Declarations */ /* Statements */ } The word void means that the function is not expected to return any values to another function. Instructor: Some operating systems prefer instead of void main () to use int main () and the value returned gives a specific message to the operating system (or the user) to act upon. These numbers can correspond to messages such as the program terminated normally, a memory error occurred, the program was terminated by another signal, etc. Narrator: So far, we have only written one function for ourselves in our program. This is the main function. The syntax has always been as shown on the this slide. We haven’t really talked about the word void formally until now. Void means that the function doesn’t return any values to any other function. Some operating systems prefer instead of void main () to use int main () and the value returned gives a specific message to the operating system (or the user) to act upon. These numbers can correspond to messages such as the program terminated normally, a memory error occurred, the program was terminated by another signal, etc. Winter Quarter

User-Written Functions The parentheses, ( ), both indicate that main is a function, AND provide a place for any variable names (arguments) that could be sent as values from another function. Since main is the main program function, it will normally not have a parameter list. (Who calls the main function anyway?) Most, but not all, other functions have parameter lists. Some such, as rand ( ), do not since they need no data or values from the calling function. Instructor: The user (or operating system in some cases) calls the main function of a program whenever it is run. It is possible to pass arguments to the main() function, but for the case of this class we normally do not. An example of passing variables to the main program is when the user adds options to a command prompt command such as ls –al where –al would be an option telling the program ls to list files in a special format. Narrator: The parentheses indicate that main is a function and provide a place for any variable names, or arguments as we have been calling them that could be sent as values from another function. Since main is the main program function, it will normally not have a parameter list in our case. The user (or operating system in some cases) calls the main function of a program whenever it is run. It is possible to pass arguments to the main() function, but for the case of this class we normally do not. An example of passing variables to the main program is when the user adds options to a command prompt command such as ls –al where –al would be an option telling the program ls to list files in a special format. Most, but not all, other functions have parameter lists, but some such as rand() don’t since they don’t need any data or values to complete their task. Winter Quarter

Writing User-Written Functions There are typically three different types of statements needed to properly set-up and make use of a user-written function. They are: 1. The function prototype statement. 2. The first line of the function definition. 3. The calling statement. Instructor: These statements are described in the following slides. Narrator: Regarding user-written functions in general, there are typically three different types of statements needed to properly set-up and make use of a user-written function. These are: The function prototype statement, the first line of the function definition, and one or more calling statements. Winter Quarter

1. The Function Prototype Statement. The function prototype's format is (note semicolon): return-value-type function-name (parameter-list) ;   The return-value-type may be any legal data type such as int, long, float, double, char, or it may be void. The parameter list is a list of data-types for the arguments and, optionally, the names of arguments. Example: float sum ( int , int , int ) ; /* OR */ float sum ( int a, int b, int c ) ; Instructor/Narrator: User-written functions are typically added after the main() function in a program for readability. The compiler then requires the function prototype since it parses the code from top to bottom. The compiler must know what functions exist before they are used, or else it will produce an error that it doesn’t know how to handle that function. The compiler basically cares about the function name and the input and output types since it only has to know what size and number of variables it will have to pass to the function (it cares about where they actually go later when it parses the function itself. Thus it is optional for the user to place the actual variable names in the function prototype’s arguments. Notice the function prototype looks identical to the first line of a function, with the addition of the semicolon at the end. Function prototypes are not needed if the entire function is placed before any other function the given function is called within. Thus placing all user-written functions before the main() function would eliminate the need of function prototypes. Winter Quarter

2. The First Line of the Function Definition. The first line of the function definition is the same as the examples of the function prototype except that the SEMICOLON IS ELIMINATED and variable or argument NAMES ARE REQUIRED.  Example: float sum ( int a, int b, int c ) Here, the function sum is of type float and has three calling parameters, all of which are of type int. The variables a, b, and c take on the values of the variables or constants used in the calling statement. Instructor: The entire function is given on the next slide. Narrator: The first line of the function definition is nearly the same as the function prototype except the semicolon is removed and the rest of the function follows in braces. Also the argument names are required at this point. Winter Quarter

The Body of the Function A complete function consists of the the function definition and the body of the function in the { }. Example: float sum ( int a, int b, int c) { float total; total = a + b + c ; return total; } Note: The function has return statement because it has a return type. Instructor: The return statement is required in any function which as a return type other than void. The return statement effectively quits execution of the function and returns whatever value the programmer tells it to, typically the value of a variable. Notice that inside the function only the total must be declared. The variables a, b, and c are already declared in the function’s first line and are initialized to the values passed to the function when it is called. Narrator: As stated previously, the body of the function then follows the function definition. An example of an entire function with the function definition and body is shown. In this function simply adds the three integers input and returns a floating point sum. The return statement is required in any function which as a return type other than void. The return statement effectively quits execution of the function and returns whatever value the programmer tells it to, typically the value of a variable. Winter Quarter

The Body of the Function float sum ( int a, int b, int c) { int total; total = a + b + c ; return total; } The names a, b, and c are known only inside sum. Likewise, any variables, like total, declared within the function are local variables, and they are known only inside the function in which they are defined. Instructor: Emphasize that total is not known to the main() function, and that any changes made to a, b, and c in this case would only be known in the function (since only the value is passed to the function, not the original variable). This is explained more later. Narrator: The names declared in this function are only known WITHIN the function, likewise the variables normally declared in the function like total are called local variables and also known only within the function they are defined. All variables passed to a function are passed as copies of the original. Winter Quarter

3. The Calling Statement. The function call (or invocation) is like the first line of the function definition except NO DATA TYPES are shown and constants may be used instead of variable names. The valued returned by a function is normally assigned to a variable in the calling function. Example: value = sum ( i, j, k ) ; or value = sum ( 5, 6.73, 2 ) ; Instructor: This line is called inside another function (main() for example). This actually calls the function like one would call rand() or printf() or any other function with the arguments as shown. Since this function returns a number the value is used as the result of the function, and in this case placed in a variable called value. Narrator: The calling statement is where the function is actually used in the program. It is used the same as any other function, with the values passed as arguments, and if a value is returned, the function can be set equal to another variable. Some examples are shown here, and could be included as statements in a main() function for example. Winter Quarter

Factorial Function Main Program #include <stdio.h> long factorial ( int x ) ; void main ( ) { int k; for ( k=0 ; k<=10 ; k++ ) printf ("%2d factorial is %ld\n", k , factorial (k) ) ; } Instructor: This program contains a user-written function which computes factorials and a main function which calls the factorial function for numbers 0 to 10. Notice the function prototype before the main () with the appended semicolon, and its similarity to the actual function on the next slide. Also point out where the function is used in the printf() function as a value, since the factorial function returns a type long value. Narrator: This program contains a user-written function which computes factorials and a main function which calls the factorial function for numbers 0 to 10. Notice the function prototype before the main () with the appended semicolon, and its similarity to the actual function on the next slide. Also notice where the function is used in the printf() function as a value, since the factorial function returns a type long value. Winter Quarter

Factorial Function long factorial ( int x ) { long fact = 1; int k; if ( x < 0 ) return 0; else if ( x==0 || x==1 ) return 1; else for ( k = 2 ; k <= x ; k++ ) fact = fact * k ; return fact ; } Instructor: This function calculates a factorial for any number passed to it. The number passed to the function is stored in “x”, and the value returned is calculated and stored in “fact”. Narrator: This function calculates a factorial for any number passed to it. The number passed to the function is stored in “x”, and the value returned is calculated and stored in “fact”. Notice how the function declaration looks much like the function prototype, and a value is returned in this case. Winter Quarter

Factorial Program Output 0 factorial is 1 1 factorial is 1 2 factorial is 2 3 factorial is 6 4 factorial is 24 5 factorial is 120 6 factorial is 720 7 factorial is 5040 8 factorial is 40320 9 factorial is 362880 10 factorial is 3628800 Instructor: The result of the factorial program. This may be compared to a calculator’s output. Narrator: This is the output of the factorial program. The factorial function is called multiple times and produces results comparable to a calculator. One can see how the use of a function in this case is useful since a programmer can re-use common code to complete the same task multiple times. Winter Quarter

User-Written Functions (example): #include <stdio.h> void swap ( int a, int b ) ; void main ( ) { int a = 5, b = 6; printf ("a=%d b=%d\n",a,b); swap (a, b); } void swap ( int a, int b ) { int temp; temp = a; a = b; b = temp; printf ("a=%d b=%d\n", a, b ); }   a=5 b=6 a=6 b=5 Instructor/Narrator: This program is actually two columns of code. The main() function is given on the left and the user-written function on the right. The output of the program is given in the bottom right. This program demonstrates that values passed to a function are actually passed as copies of the values, and not the original values themselves. The first line of output is from the main function where the values are initialized. The values are passed to a swap function which swaps the values and displays them inside the function, but DOES NOT pass them back to the main function. After this the main function completes execution and displays the values it knows for a and b, which remain unchanged. When functions are called, ALL of their variables are given their own unique memory space, and copies of the values passed to the function are automatically stored in the function’s memory. In this case the only way to get values out of the function are to return them. Another way is to pass the original location of the variables in memory to the function as variables, which will be discussed later. Winter Quarter

Call By Value vs. Call By Reference Two ways in which variables are passed: Call by value Call by reference "Call by value" means function only gets a copy of the value of the calling argument. The called function can not change the value back in the calling routine. This is normally how it is in C. "Call by reference" means the function gets the original argument, and thus the called function can change the value of the variable back in the calling routine. Must use pointers in C to do this. Instructor: Call by value is what occurs in this lecture. Call by reference will be described in detail when pointers are introduced. For now students only need to know another method exists that will solve this problem. Narrator: There are two ways we can pass variables to functions. The way we have been passing them is known as call by value, where we pass the value of variables themselves. In this manner the function gets a copy of the value and can’t change the original variable that is known by the calling function. Another method is known as call by reference, which passes the address of the original variable as an argument. Pointers are required for this to occur, which will be discussed in Lecture 14. Winter Quarter