Programming Functions: Passing Parameters by Reference.

Slides:



Advertisements
Similar presentations
1 Random number generation Using srand(), rand() & time(0) Searching and Sorting Demo Making searching & sorting more generic Overloading the functions.
Advertisements

Overview Reference parameters Documenting functions A game of craps. Design, code, test and document.
1 Lecture 10 Chapter 7 Functions Dale/Weems/Headington.
Local and Global Variables. COMP104 Local and Global / Slide 2 Scope The scope of a declaration is the block of code where the identifier is valid for.
Introduction to Functions Programming. COMP102 Prog Fundamentals I: Introduction to Functions /Slide 2 Introduction to Functions l A complex problem is.
Chapter 5 Functions.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 5 Function Basics.
Arrays Programming COMP102 Prog. Fundamentals I: Arrays / Slide 2 Arrays l An array is a collection of data elements that are of the same type (e.g.,
Problem Solving and Program Design Programming. COMP102 Prog Fundamentals I : Problem Solving and Program Design/Slide 2 Problem Solving Process l Define.
More on Functions Programming. COMP104 Lecture 19 / Slide 2 Passing Parameters by Reference l To have a function with multiple outputs, we have to use.
1 11/05/07CS150 Introduction to Computer Science 1 Functions Chapter 6, page 303.
Writing and Testing Programs Drivers and Stubs Supplement to text.
Character I/O. COMP104 Character I/O Slide 2 Data Type: char * Constant declaration const char star = '*'; * Variable declaration char resp; * Variable.
Characters. COMP104 Lecture 21 / Slide 2 Data Type: char * Constant declaration const char star = '*'; * Variable declaration char resp; * Variable assignment.
Functions:Passing Parameters by Value Programming.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Functions. COMP104 Lecture 13 / Slide 2 Function Prototype * The function prototype declares the interface, or input and output parameters of the function,
What is the out put #include using namespace std; void main() { int i; for(i=1;i
C++ programming I Lab#3 Control Statements Instructor: Eng. Ruba A. Salamah Tuseday: 17/10/2010.
Computer Science 1620 Reference Parameters. Parameters – Pass by Value recall that the parameter of a function is assigned the value of its corresponding.
Pass by Reference. COMP104 Pass by Reference / Slide 2 Passing Parameters by Reference * To have a function with multiple outputs, we have to use pass.
Chapter 7 Functions.
Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.
Programming Functions: Passing Parameters by Reference.
Functions Parameters & Variable Scope Chapter 6. 2 Overview  Using Function Arguments and Parameters  Differences between Value Parameters and Reference.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
METHODS Introduction to Systems Programming - COMP 1005, 1405 Instructor : Behnam Hajian
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.1 Chapter 4 Mathematical Functions, Characters, and Strings.
Chapter 3 Expressions and Interactivity Department of Computer Science Missouri State Univeristy.
Chapter 5 Functions For All Subtasks. Void functions Do not return a value. Keyword void is used as the return type in the function prototype to show.
Functions—Part I. Slide 2 Where are we now? Simple types of variables 3 program structures cin(>>)/cout(
1 INTRODUCTION TO PROBLEM SOLVING AND PROGRAMMING.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed.
VARIABLES AND DATA TYPES Chapter2:part1 1. Objectives: By the end of this section you should: Understand what the variables are and why they are used.
Chapter 2: Introduction to C++. Language Elements Keywords Programmer-defined symbols (identifiers) Operators Punctuation Syntax Lines and Statements.
Modular Programming ELEC 206 Computer Applications for Electrical Engineers Dr. Ron Hayne.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Copyright © 2002 W. A. Tucker1 Chapter 9 Lecture Notes Bill Tucker Austin Community College COSC 1315.
1 Lecture 12 Pointers and Strings Section 5.4, ,
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 4 Loops.
CS1201: PROGRAMMING LANGUAGE 2 FUNCTIONS. OVERVIEW What is a Function? Function Prototype Vs Decleration Highlight Some Errors in Function Code Parameters.
Introduction to Functions.  A complex problem is often easier to solve by dividing it into several smaller parts, each of which can be solved by itself.
Lecture 5: Expressions and Interactivity Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
1 Lecture 8 Pointers and Strings: Part 2 Section 5.4, ,
Reference Parameters There are two ways to pass arguments to functions: pass- by-value and pass-by-reference. pass-by-value –A copy of the arguments’svalue.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 6 Methods Dr. Musab Zghoul.
1 Generating Random Numbers Textbook ch.6, pg
MR. CRONE Generating Random Numbers. Random Numbers Many programs require the computer to generate random numbers Random numbers are used in many applications.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
L131 Assignment Operators Topics Increment and Decrement Operators Assignment Operators Debugging Tips rand( ) math library functions Reading Sections.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 6 Methods.
Variables Mr. Crone.
Fundamentals of structural programming
Chapter 5 Function Basics
Chapter 5 Functions.
CS 1430: Programming in C++ Turn in your Quiz1-2 No time to cover HiC.
Compound Assignment Operators in C++
CS150 Introduction to Computer Science 1
Assignment Operators Topics Increment and Decrement Operators
Variables T.Najah Al_Subaie Kingdom of Saudi Arabia
Pass by Reference.
Assignment Operators Topics Increment and Decrement Operators
CS150 Introduction to Computer Science 1
Fundamental Programming
Introduction to Functions
Assignment Operators Topics Increment and Decrement Operators
Presentation transcript:

Programming Functions: Passing Parameters by Reference

COMP102: Prog. Fundamentals: Pass by Reference/Slide 2 Passing Parameters by Reference l To have a function with multiple outputs, we have to use pass by reference. l We use & to denote a parameter that is passed by reference: & Examples: void Increment(int& Number); void SumAve (double, double,double&, double&);

COMP102: Prog. Fundamentals: Pass by Reference/Slide 3 Passing Parameters by Reference l The corresponding argument must be a variable. Increment(Inc); SumAve (2.5, y+3, sum, mean); l The address (reference) of that variable is passed to the function, instead of its value. l If the function changes the parameter value, the change will be reflected in the corresponding argument, since they share the same memory location.

COMP102: Prog. Fundamentals: Pass by Reference/Slide 4 Pass by Reference: Example 1 l To show how the function affects a variable which is used as an argument: #include using namespace std; void Increment(int& Number){ Number = Number + 1; cout << "The parameter Number: " << Number << endl; } int main(){ int Inc = 10; Increment(Inc); // parameter is a variable cout << "The variable Inc is: "<<Inc<<endl; return 0; }

COMP102: Prog. Fundamentals: Pass by Reference/Slide 5 Pass by Reference: Example 2 l It is possible to use both pass by reference and pass by value parameters in the same function. // Print the sum and average of two numbers // Input: two numbers num_1 and num_2 // Output: sum of num_1 and num_2 // average of num_1 and num_2 #include using namespace std; void SumAve (double, double, double&, double&);

COMP102: Prog. Fundamentals: Pass by Reference/Slide 6 Pass by Reference: Example 2 int main ( ) { double x, y, sum, mean; cout << "Enter two numbers: "; cin >> x >> y; SumAve (x, y, sum, mean); cout << "The sum is " << sum << endl; cout << "The average is " << mean << endl; return 0; } void SumAve(double no1, double no2, double& sum, double& average) { sum = no1 + no2; average = sum / 2; }

COMP102: Prog. Fundamentals: Pass by Reference/Slide 7 Pass by Reference: Example 2 l Data areas after call to SumAve:

COMP102: Prog. Fundamentals: Pass by Reference/Slide 8 Pass by Reference: Example 3 // Compare and sort three integers #include using namespace std; void swap (int&, int&); int main ( ) { int first, second, third;// input integers // Read in first, second and third. cout << "Enter three integers: "; cin >> first >> second >> third; if (first > second) swap (first, second); if (second > third) swap (second, third); if (first > second) swap (first, second); cout << "The sorted integers are " << first <<", "<<second<<", "<<third << endl; return 0; }

COMP102: Prog. Fundamentals: Pass by Reference/Slide 9 Pass by Reference: Example 3 // Function for swapping two integers void swap (int& num_1, int& num_2) { int temp; temp = num_1; num_1 = num_2; num_2 = temp; }

COMP102: Prog. Fundamentals: Pass by Reference/Slide 10 Pass by Reference: Example 4 // Pass-by-reference versus pass-by-value example #include using namespace std; void One (int a, int b, int& c) { int d; a = 10; b = 11; c = 12; d = 13; cout<<"The values of a, b, c, and d in One:\n"; cout << a << " " << b << " " << c << " " << d << endl; } void Two (int a, int b, int& d) { int c = 0; cout<<"The values of a, b, c, and d in Two:\n"; cout << a << " " << b << " " << c << " " << d << endl; }

COMP102: Prog. Fundamentals: Pass by Reference/Slide 11 Pass by Reference: Example 4 int main () { int a = 1, b = 2, c = 3, d = 4; cout<<"The original values of a,b,c,and d:\n"; cout << a << " " << b << " " << c << " " << d << endl << endl; One(a, b, c); cout<<"The values of a,b,c,and d after One:\n"; cout << a << " " << b << " " << c << " " << d << endl; Two(a, b, d); cout<<"The values of a,b,c,and d after Two:\n"; cout << a << " " << b << " " << c << " " << d << endl; return 0; }

COMP102: Prog. Fundamentals: Pass by Reference/Slide 12 Pass by Reference: Example 4 Output: The original values of a,b,c,and d: The values of a, b, c, and d in One: The values of a, b, c, and d after One: The values of a, b, c, and d in two: The values of a, b, c, and d after two:

COMP102: Prog. Fundamentals: Pass by Reference/Slide 13 Testing and Debugging Functions l One major advantage of functions is that they can be designed, coded and tested separately from the rest of the program. l Use a "driver" program to test a function with several inputs: int main( ) { for (int count = 1; count <= 13; count++){ diamond(count); cout << " Calling diamond with size " << count <<endl; } return 0; }

COMP102: Prog. Fundamentals: Pass by Reference/Slide 14 Testing and Debugging Functions l If a yet-to-be written function is needed in testing a program, replace it with a "stub" for testing. l A stub has the same interface as the original function, but not the full implementation. Oftentimes, a stub contains just a simple return or cout command. void diamond(int size) { cout << " diamond is called with size " << size <<endl; }

COMP102: Prog. Fundamentals: Pass by Reference/Slide 15 Example: A Simple Math Learning Tool This example creates a program for a first grader to practice subtractions. The program randomly generates two single-digit integers number1 and number2 with number1 > number2 and displays a question such as “What is 9 – 2?” to the student, as shown in the sample output. After the student types the answer, the program displays a message to indicate whether the answer is correct.

COMP102: Prog. Fundamentals: Pass by Reference/Slide 16 #include #include // for time function #include // for rand and srand functions using namespace std; int main() { // 1. Generate two random single-digit integers srand(time(0)); int number1 = rand() % 10; int number2 = rand() % 10; // 2. If number1 < number2, swap number1 with number2 if (number1 < number2) { int temp = number1; number1 = number2; number2 = temp; } Random function: rand()

COMP102: Prog. Fundamentals: Pass by Reference/Slide 17 // 3. Prompt the student to answer cout << "What is " << number1 << " - " << number2 << "? "; int answer; cin >> answer; // 4. Grade the answer and display the result if (number1 - number2 == answer) cout << "You are correct!"; else cout << "Your answer is wrong.\n" << number1 << " - " << number2 << " should be " << (number1 - number2) << endl; return 0; } Random function: rand()

COMP102: Prog. Fundamentals: Pass by Reference/Slide 18 Generating Random Characters Computer programs process numerical data and characters. You have seen many examples that involve numerical data. It is also important to understand characters and how to process them. Since every character has a unique ASCII code between 0 and 127. To generate a random character is to generate a random integer between 0 and 127. We already learn how to generate random number from last example. Basically it is to use the srand(seed) function to set a seed and use rand() to return a random integer. You can use it to write a simple expression to generate random numbers in any range. For example,

COMP102: Prog. Fundamentals: Pass by Reference/Slide 19 Case Study: Generating Random Characters,

#include using namespace std; // Generate a random character between ch1 and ch2 char getRandomCharacter(char ch1, char ch2) { return static_cast (ch1 + rand() % (ch2 - ch1 + 1));} // Generate a random lowercase letter char getRandomLowerCaseLetter() { return getRandomCharacter('a', 'z');} // Generate a random uppercase letter char getRandomUpperCaseLetter() { return getRandomCharacter('A', 'Z');} // Generate a random digit character char getRandomDigitCharacter() { return getRandomCharacter('0', '9');} // Generate a random character char getRandomCharacter() { return getRandomCharacter(0, 127);} Random function: rand()

COMP102: Prog. Fundamentals: Pass by Reference/Slide 21 int main() { const int NUMBER_OF_CHARS = 175; const int CHARS_PER_LINE = 25; srand(time(0)); // Set a new seed for random function // Print random characters between '!' and '~', 25 chars per line for (int i = 0; i < NUMBER_OF_CHARS; i++) { char ch = getRandomLowerCaseLetter(); if ((i + 1) % CHARS_PER_LINE == 0) cout << ch << endl; else cout << ch; } return 0;} Random function: rand()