Functions Week 10 & 11. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or.

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.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 6 Functions.
Chapter 6: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
CS 201 Functions Debzani Deb.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 6: Functions by.
Chapter 6: User-Defined Functions I
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
Introduction to Methods
FunctionsFunctions Systems Programming Concepts. Functions   Simple Function Example   Function Prototype and Declaration   Math Library Functions.
Chapter 6: Functions.
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
Chapter 4:Functions| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2005 Slide 1 Functions Lecture 4 by Jumail Bin.
Introduction to Function
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 6 Functions.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Chapter 6: Functions Starting Out with C++ Early Objects
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Chapter 6: User-Defined Functions
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6: Functions Starting Out with C++ Early Objects Seventh Edition.
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.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Section 4 - Functions. All of the programs that we have studied so far have consisted of a single function, main(). However, having more than one function.
Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter 5: Methods.
1 Methods Introduction to Methods Passing Arguments to a Method More About Local Variables Returning a Value from a Method Problem Solving with Methods.
Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Lecture 10: Modular Programming (functions) B Burlingame 13 April 2015.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
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.
1 Brief Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6: Functions Starting Out with C++ Early Objects Eighth Edition.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Functions Chapter 6. Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules Function: a collection.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
Lecture 12: Functions Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-1 Why Write Methods? Methods are commonly used to break a problem down.
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
Chapter 6 Functions. 6-2 Topics 6.1 Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
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.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
C-language Lecture By B.S.S.Tejesh, S.Neeraja Asst.Prof.
CSCI 161: Introduction to Programming Function
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
User-Defined Functions
Chapter 6: Functions Starting Out with C++ Early Objects
Functions.
6 Chapter Functions.
Chapter 6: Functions Starting Out with C++ Early Objects Ninth Edition
Lesson #6 Modular Programming and Functions.
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Instructor: Hidayah Elias Course: COMPUTER PROGRAMMING (BFC 2042)
Standard Version of Starting Out with C++, 4th Edition
Presentation transcript:

Functions Week 10 & 11

Modular Programming 6.1

Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules Function: a collection of statements to perform a task Motivation for modular programming: –Improves maintainability of programs –Simplifies the process of writing programs

Modular programming In simpler terms: big programs get complicated. Small programs are simpler Key idea: Decomposition –Break big complicated sets of instructions into smaller, simpler modules

Modular Programming

Example: program without functions #include void main (void) { /*Farenheit-to-Celcius*/ double degF, degC; printf(“Enter degrees F: “); scanf(“%f”, &degF;) /* F-to-C conversion:*/ ratio = 5.0 / 9.0;/* We will unify this*/ degC = (degF-32)*ratio;/* set of statements to*/ /* make a new function.*/ printf(“%f degrees F are %f degrees C\n”, degF, degC); } What if we need this conversion step in many different places in our program?

Example: program with functions #include double F_to_C (double degreesF); void main (void) { /*Farenheit-to-Celcius*/ double degF, degC; printf(“Enter degrees F: “); scanf(“%lf”, &degF;) degC = F_to_C (degF); printf(“%lf degrees F are %lf degrees C\n”, degF, degC); } double F_to_C (double degreesF) { const double ratio = 5.0 / 9.0; return (degreesF-32)*ratio; } Declare the function (“Function prototype”) Call the function when you need it Define the function

Function A collection of statements that performs a specific task. Commonly used to break a problem down into small manageable pieces. In C, there are 2 types of function: –Library functions –User-defined functions

Library Functions “Built-in" functions that come with the compiler. The source code (definition) for library functions does NOT appear in your program. To use a library function, you simply need to include the proper header file and know the name of the function that you wish to use. –#include compiler directive

Library Functions (cont.) Libraries under discussion at this time: Compiler directivePurpose Character classification and conversion Math functions Data conversion Time functions

Library Functions: Math Functions Required header: #include Example functions FunctionPurpose abs(x)returns the absolute value of an integer. pow(x,y)calculates x to the power of y. If x is negative, y must be an integer. If x is zero, y must be a positive integer. pow10(x)calculates 10 to the power of x. sqrt(x)calculates the positive square root of x. (x is >=0)

Library Functions: Example 1 1.#include 2.#include 3.#include 4.int main() 5.{ 6.double area, radius; 7. printf("This program calculates the area of a circle.\n”); 8. printf("What is the radius of the circle? ”); 9. scanf (“%lf”, &radius); 10. area= * pow(radius,2.0); 11. printf("The area is %lf \n.”, area); 12. getch(); 13. return 0; 14.}

Library Function: Example 2 1.#include 2.#include 3.#include 4.main(){ 5.int nom1,nom2, result; 6. printf("Enter two numbers”); 7.scanf (“%d %d”, &nom, &nom2); 8.if ((nom1<0)||(nom2<0)) 9.printf(“negative number/s”); else 12. { 13. result= sqrt(nom1 + nom2); 14. printf("The square root of %d + %d is %d”, nom1, nom2, result);} 15. }

Library Functions (cont.) A collection of specialized functions. C promotes code reuse with predefined classes and functions in the standard library The functions work as a black box: sqrt(x) x=4 2

More Mathematical Library Functions 3.11

More Mathematical Library Functions Require math.h header file Take double as input, return a double Commonly used functions: sin Sine cos Cosine tan Tangent sqrt Square root log Natural (e) log abs Absolute value (takes and returns an int)

More Mathematical Library Functions These require stdlib.h header file rand() : returns a random number ( int ) between 0 and the largest int the compute holds. Yields same sequence of numbers each time program is run. srand(x) : initializes random number generator with unsigned int x

Exercise Week 10_1 Easy access of function explanation Refer to Lab 10, Exe. 2, No. 2in pg. 92. Trace the output

User-Defined Functions User-defined functions are created by you, the programmer. Commonly used to break a problem down into small manageable pieces. You are already familiar with the one function that every C program possesses: int main() –Ideally, your main( ) function should be very short and should consist primarily of function calls. Main Program Function 1Function 3Function 2

User defined function – function called

Functions – whats, hows Defining and Calling Functions 6.2

Functions Function is a “black-box”, a mini program with –A set of inputs –An output –A body of statements It performs one well-defined task (e.g. printf only do the printing process) We can also use functions in a menu-driven program

Function concepts & example Calculate the average of four numbers (a, b, c and d)

Three steps in using functions 1.Declare the function –Known as function declaration or function prototyping –Write a function prototype that specifies: The name of the function The type of its return value Its list of arguments and their types 2.Define the function –Known as the function definition or function implementation –Write the block of statements (body) of the function to define processes should be done by the function 3.Call the function –Known as the function call or function invocation –Call the name of the function in order to execute it

Three steps in using functions

Defining and Calling Functions (2 nd and 3 rd steps) Function definition: statements that make up a function Function call: statement causes a function to execute We’ll get back to step #1 soon! – function prototype

Function Definition Definition includes: –return type: data type of the value that function returns to the part of the program that calls it –name: name of the function. Function names follow same rules as variables –parameter list: variables containing values passed to the function –body: statements that perform the function’s task, enclosed in {}

Function Definition

Function Return Type If a function returns a value, the type of the value must be indicated: int main() If a function does not return a value, its return type is void : void printHeading() { printf("Monthly Sales\n”); }

Function Return Type void function cannot be used in an expression because it does not return any value. It can only be used as a statement. Example: If given function definition as below: void greeting (void) { printf (“Hello”); return; } Function call below would be an error: result = greeting();//Error! greeting() is a void //function

Function Return Type Formal parameters are variables that are declared in the header of the function definition Actual parameters are the expressions in the calling statement When making a function call, the formal and actual parameters must match exactly in type, order and number The parentheses is compulsory, even when no parameters present. This is the way, how the compilier knows an identifier either it is a function or a variable –Example: greeting;//Error, greeting is a function. So, it //must have the () even though no parameter //is present

Calling a Function To call a function, use the function name followed by () and ; printHeading(); When called, program executes the body of the called function After the function terminates, execution resumes in the calling function at point of call.

Calling a Function - example Function definition Function call Any of the three function calls above are valid *Functions that return a value can be used in an expression or as a statement

Flow of Control- void function with parameters

Flow of Control- function that returns a value

Calling Functions main can call any number of functions Functions can call other functions Compiler must know the following about a function before it is called: –name –return type –number of parameters –data type of each parameter

Function Prototypes – step #1 6.3

Function Prototypes (or, declaration) Ways to notify the compiler about a function before a call to the function: –Place function definition before calling function’s definition –Use a function prototype (function declaration) – like the function definition without the body Header: void printHeading() Prototype: void printHeading();

(Program Continues) Function Prototypes - example Function prototypes /*This program 6.5 has three functions: main, First and Second*/ #include /*Function Prototype*/ void first (); void second (); int main() { printf ("I am starting in function main.\n"); first();/*Call function first*/ second(); /*Call function second*/ printf ("Back in function main again.\n"); getch(): return 0; }

Program (Continued) Function definition Function Prototypes - example /************************************* * Definition of function first. * * This function displays a message. * *************************************/ void first() { printf("I am now inside the function first.\n”); } /************************************* * Definition of function second. * * This function displays a message. * *************************************/ void second() { printf("I am now inside the function second.\n”); }

Prototype Notes Place prototypes near top of program Program must include either prototype or full function definition before any call to the function – compiler error otherwise When using prototypes, can place function definitions in any order in source file

Exercise Week 10_2 Draw a structure diagram for Program 6-5 from slide Refer to Lab 11, Exe. 1, No. 1(i) and 1(i)i in pg Solve the problem

Sending Data into a Function 6.4

Sending Data into a Function Can pass values into a function at time of call: c = pow(a, b); Values passed to function are arguments Variables in a function that hold the values passed as arguments are parameters Giving information to a function call is also known as parameter passing

A Function with a Parameter Variable void displayValue(int num) { printf ("The value is %d\n”, num); } The integer variable num is a parameter. It accepts any integer value passed to the function.

(Program Continues) A Function with a Parameter Variable - example /*This program demonstrates a function with a parameter*/ #include /*Function Prototype*/ void displayValue (int); int main() { printf ("I am passing 5 to displayValue.\n"); displayValue(5); /*Call displayValue with argument 5*/ printf ("Now I am back in main.\n"); getch(); return 0; }

A Function with a Parameter Variable - example /********************************************************* * Definition of fucntion displayValue. * * It uses an integer parameter whose value is displayed. * **********************************************************/ void displayValue (int num) { printf("The value is %d\n", num); } (continued)

The function call passes the value 5 as an argument to the function. A Function with a Parameter Variable (cont..) printf("The value is %d\n", num);

Other Parameter Terminology – recap! A parameter can also be called a formal parameter or a formal argument An argument can also be called an actual parameter or an actual argument

Parameters, Prototypes, and Function Headers For each function argument, –the prototype must include the data type of each parameter inside its parentheses –the header must include a declaration for each parameter in its () void evenOrOdd(int); //prototype void evenOrOdd(int num) //header evenOrOdd(val); //call

Function Call Notes Value of argument is copied into parameter when the function is called A parameter’s scope is the function which uses it Function can have multiple parameters There must be a data type listed in the prototype () and an argument declaration in the function header () for each parameter Arguments will be promoted/demoted as necessary to match parameters

Exercise Week 10_3 Refer to Lab 11, Exe. 4, No. 2 in pg Solve the problem What is the output of this program? #include /* Function prototype */ void showDouble(int); int main(){ int num; for (num = 0; num < 10; num++) showDouble(num); getch();; return 0; } /*Definition of function*/ void showDouble(int value) { printf (“%d\t”, value); printf (“%d\n”, value * 2); }

Passing Multiple Arguments When calling a function and passing multiple arguments: –the number of arguments in the call must match the prototype and definition –the first argument will be used to initialize the first parameter, the second argument to initialize the second parameter, etc.

(Program Continues) Passing Multiple Arguments - example #include /* Function prototype */ void showSum(int, int, int); int main() { int value1, value2, value3; /*Get three integers*/ printf("Enter three integers and I will display "); printf("their sum: "); scanf("%d %d %d", &value1, &value2, &value3); /*Call showSum passing three arguments*/ showSum(value1, value2, value3); getch(); return 0; }

Program (continued) Passing Multiple Arguments - example /*********************************** * Definition of function showSum. * * It uses three integer parameters.* * Their sum is displayed. */ void showSum (int num1, int num2, int num3) { printf ("%d", num1+num2+num3); }

The function call passes value1,value2, and value3 as a arguments to the function. Passing Multiple Arguments (cont..) printf ("%d", num1+num2+num3);

Exercise Week 10_4 #include /*Function prototype*/ void func1(double, int); int main(){ int x = 0; double y = 1.5; printf(“%d %lf\n”, x, y); func1 (y, x); printf(“%d %lf\n”, x, y); getch(); return 0; } void func1(double a, int b){ printf(“%lf %d\n”, a, b); a=0.0; b=10; printf(“%lf %d\n”, a, b);; } Refer to Lab 11, Exe. 4, No. 1 in pg Solve the problem What is the output of this program?

Passing Data by Value 6.5

Passing Data by Value Pass by value: when an argument is passed to a function, its value is copied into the parameter. Changes to the parameter in the function do not affect the value of the argument –After the function call completed, the original data remain unchanged

Passing Information to Parameters by Value Example: int val=5; evenOrOdd(val); evenOrOdd can change variable num, but it will have no effect on variable val 5 val argument in calling function 5 num parameter in evenOrOdd function

Pass by value example

Passing expression by value When passing an expression, the expression is evaluated first, then the result is passed to the called function

Exercise Week 10_5 Refer to Lab 11, Exe. 2, No. 2 in pg. 97. Solve the problem

The return Statement 6.6

The return Statement Used to end execution of a function Can be placed anywhere in a function –Statements that follow the return statement will not be executed Can be used to prevent abnormal termination of program In a void function without a return statement, the function ends at its last }

(Program Continues) The return Statement - example /* This program uses a function to perform division. * * If division by zero is detected, the function returns.*/ #include //Function prototype void divide (double, double); int main() { double num1, num2; printf("Enter two numbers and I will divide the first\n"); printf("number by the second number: "); scanf("%lf %lf", &num1, &num2); divide (num1, num2); getch(); return 0; }

Program (continued) Return to called function The return Statement - example /****************************************************** * Definition of function divide. Uses two parameters: * * arg1 and arg2. The function divides arg1 by arg2 * * and shows the result. If arg2 is zero, however, the * * function returns. * ******************************************************/ void divide (double arg1, double arg2) { if (arg2 == 0.0) { printf("Sorry, I cannot divide by zero.\n"); return; } printf("The quotient is %lf\n", (arg1/arg2)); }

Returning a Value From a Function 6.7

Returning a Value from a Function A function can return a value back to the statement that called the function. You've already seen the pow function, which returns a value: double x; x = pow(2.0, 10.0);

Returning a Value From a Function In a value-returning function, the return statement can be used to return a value from function to the point of call. Example: int sum(int num1, int num2) { double result; result = num1 + num2; return result; }

A Value-Returning Function int sum(int num1, int num2) { double result; result = num1 + num2; return result; } Return Type Value Being Returned

A Value-Returning Function int sum(int num1, int num2) { return num1 + num2; } Functions can return the values of expressions, such as num1 + num2

(Program Continues) Returning a Value From a Function Returning Function - example /* This program uses a function that returns a value */ #include /* Function prototype */ int sum (int, int); int main() { int value1 = 20, /*the first value*/ value2 = 40,/*the second total*/ total; /*to hold the total*/ /*Call the sum function, passing the contents of value1 and value2 as arguments. Assign the return value to the total variable.*/ total = sum(value1, value2); /*Display the sum of the values.*/ printf("The sum of %d and %d is %d\n", value1, value2, total); getch(); return 0; }

Program 6-12 (continued) Returning Function - example /******************************************** * Definition of function sum. This function * * returns the sum of its two parameters. * ********************************************/ int sum (int num1, int num2) { return num1 + num2; }

The statement total = calls the sum function, passing value1 and value2 as arguments. The return value is assigned to the total variable. sum value2 value1 total Returning a Value From a Function Returning Function - example

Returning a Value From a Function The prototype and the definition must indicate the data type of return value (not void ) Calling function should use return value: –assign it to a variable, or –send it to printf, or –use it in an expression Code after a return statement is never executed

The following function always returns 10 int square (int a) { return 10; n = n * n; return n; } This line causes the control back to the calling function and ignores the rest of the lines These two lines are ignored and never been executed

Exercise Week 10_6 Refer to your solution for Lab 11, Exe. 4, No. 1 pg 102 Change your solution to use return int in function maximum(). Call Maximum function using the following call techniques: –assign it to a variable –send it to printf –use it in an expression

Local and Global Variables 6.8

Local and Global Variables Variables defined inside a function are local to that function. They are hidden from the statements in other functions, which normally cannot access them. Because the variables defined in a function are hidden, other functions may have separate, distinct variables with the same name.

Local and Global Variables - example /* This program shows that variables defined in a function are hidden from other functions. */ #include void anotherFunction(); /*Function prototype*/ int main() { int num = 1;/*local variable*/ printf("In main, num is %d\n", num); anotherFunction(); printf("Back in main, num is %d\n", num); getch(); return 0; } /******************************************************************** Definition of anotherFunction. It has a local variable, num, whose * *initial value is displayed. * ********************************************************************/ void anotherFunction() { int num = 20; /*local variable*/ printf("In anotherFunction, num is %d\n", num); }

Local and Global Variables - example

When the program is executing in main, the num variable defined in main is visible. When anotherFunction is called, however, only variables defined inside it are visible, so the num variable in main is hidden. Local and Global Variables - example

Local Variable Lifetime A function’s local variables exist only while the function is executing. This is known as the lifetime of a local variable. When the function begins, its local variables and its parameter variables are created in memory, and when the function ends, the local variables and parameter variables are destroyed. This means that any value stored in a local variable is lost between calls to the function in which the variable is declared.

Global Variables and Global Constants A global variable is any variable defined outside all the functions in a program. The scope of a global variable is the portion of the program from the variable definition to the end. This means that a global variable can be accessed by all functions that are defined after the global variable is defined.

Global Variables and Global Constants You should avoid using global variables because they make programs difficult to debug. Any global that you create should be global constants.

Global constants defined for values that do not change throughout the program’s execution. Global Constants - example #include

The constants are then used for those values throughout the program. Global Constants - example

Initializing Local and Global Variables Local variables are not automatically initialized. They must be initialized by programmer. Global variables (not constants) are automatically initialized to 0 (numeric) or NULL (character) when the variable is defined.

Local vs. Global example I

Local vs. Global – example II

Local vs. Global – example III

Exercise Week 10_7 Refer to Lab 11, Exe. 3, No.1 in pg Solve the problem

Static Local Variables 6.9

Static Local Variables Local variables only exist while the function is executing. When the function terminates, the contents of local variables are lost. static local variables retain their contents between function calls. static local variables are defined and initialized only the first time the function is executed. 0 is the default initialization value.

(Program Continues) Local Variables #include

In this program, each time showLocal is called, the localNum variable is re-created and initialized with the value 5. Local Variables - example printf(“localNum is %d\n”, localNum);

A Different Approach, Using a Static Variable (Program Continues) #include

statNum is automatically initialized to 0. Notice that it retains its value between function calls. Using a Static Variable - example printf(“statNum is %d\n”, statNum);

If you do initialize a local static variable, the initialization only happens once. See Program 6-22… Using a Static Variable - example printf(“statNum is %d\n”, statNum);

Exercise Week 10_8 Given the following programs compare the output and reason the output. #include void showVar(); int main ( ) { for (int count=0;count<10; count++) showVar(); getch(); return 0; } void showVar() { static int var = 10; printf(“%d\”n, var); var++; } #include void showVar(); int main ( ) { for (int count=0;count<10; count++) showVar(); getch(); return 0; } void showVar() { int var = 10; printf(“%d\”n, var); var++; }

Default Arguments 6.10

Default Arguments A Default argument is an argument that is passed automatically to a parameter if the argument is missing on the function call. Must be a constant declared in prototype: void evenOrOdd(int = 0); Can be declared in header if no prototype Multi-parameter functions may have default arguments for some or all of them: int getSum(int, int=0, int=0);

Default arguments specified in the prototype (Program Continues) Default Arguments - example #include printf(“\n”);

Program 6-23 (Continued) Default Arguments - example printf(“*”); printf(“\n”);

Default Arguments If not all parameters to a function have default values, the defaultless ones are declared first in the parameter list: int getSum(int, int=0, int=0);// OK int getSum(int, int=0, int); // NO When an argument is omitted from a function call, all arguments after it must also be omitted: sum = getSum(num1, num2); // OK sum = getSum(num1,, num3); // NO

Exercise Week 10_9 Refer to Lab 11, Exercise 2, No.5 in pg. 99. Solve the problem

Using Reference Variables as Parameters 6.11

Using Reference Variables as Parameters A passing technique that passes the address of a variable instead of its value A mechanism that allows a function to work with the original argument from the function call, not a copy of the argument –Causes side effect, when the called function changes a value, it actually changes the original variable in the calling function Allows the function to modify values stored in the calling environment Provides a way for the function to ‘return’ more than one value

Passing by Reference The argument (actual parameter) must be an address of a variable int n; fun (&n); /* &n means “address of a variable n” */ The formal parameter must be a pointer void fun(int *x)/* x is a pointer variable */ ( /* function body */ } Changes to a reference variable are made to the variable it refers to

Passing by reference – example I

The * here in the prototype indicates that the parameter is a reference variable. Here we are passing value by reference. (Program Continues) Passing by Reference – example II /* This program uses a reference variable as a function parameter */ #include /* Function prototype. The parameter is a reference variable */ void doubleNum (int *refVar); int main () { int value = 4; printf("In main, value is %d\n", value); printf("Now calling doubleNum...\n"); doubleNum(&value); printf("Now back in main. value is %d\n", value); getch(); return 0; }

The * also appears here in the function header. Program 6-24 (Continued) Passing by Reference - example /************************************************* * Definition of doubleNum * * The parameter refVar is a reference variable. * * The value in refVar is doubled. */ void doubleNum (int *refVar) { *refVar *= 2; }

Pointer – the concept How the passing by reference works? To understand this, let’s first look at the concept What we have used so far is normal variable or also known as data variable. A data variable contains a value (e.g. integer number, a real number or a character) Pointer is a variable that contains the address of another variable. This is also known as address variable

Pointer – the concept (cont.) Since pointer is also a variable, it is declared like the data variable The difference is, we need to place an asterisk (*) before the pointer Example int n = 5; // n is a normal variable (or data variable) int *p = &n; // p is a pointer that holds the address of // variable n

Pointer – the concept (cont.) There are two special operators for pointers: address operator and indirection operator Address operator, & –Get the address of a variable –Example: &n Meaning: “give me the address of variable n” Indirection operator, * –Get the value of a variable where its address is stored in the pointer –Example: *ptr Meaning: “give me the value of variable where its address is stored in the variable ptr” –Pointer declaration also uses the asterisk (*). But don’t get confused as pointer declaration and indirection operator are different.

Address and Indirection Operators

Another example – how passing by reference works

Exercise Week 10_10 Refer to Lab 11, Exe. 2, No.3 in pg. 98. Solve the problem

Thank You Q & A