Topics. Functions. Functions

Similar documents
Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.

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

More Functions. Pass by Value. Example: Exchange two numbers. Storage Classes. Passing Parameters by Reference. Pass by value and by reference

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7. CS 5301 Spring 2018

Functions, Arrays & Structs

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

Increment and the While. Class 15

Lab Instructor : Jean Lai

Name SECTION: 12:45 2:20. True or False (12 Points)

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

Functions, Arrays & Structs

Name Section: M/W or T/TH. True or False (14 Points)

C++ Programming for Non-C Programmers. Supplement

True or False (12 Points)

CSCE 206: Structured Programming in C++

do { statements } while (condition);

Ch 6. Functions. Example: function calls function

Your first C++ program

CPE 112 Spring 2015 Exam III (100 pts) April 8, True or False (12 Points)

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

6. C++ Subprograms David Keil CS I slides 7/03 1

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Object Oriented Design

Topics. Constructor. Constructors

CE221 Programming in C++ Part 1 Introduction

A First Program - Greeting.cpp

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Introduction to Programming using C++

CS 376b Computer Vision

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

CMSC 202 Midterm Exam 1 Fall 2015

1) You want to determine whether time has run out. The following code correctly implements this:

Integer Data Types. Data Type. Data Types. int, short int, long int

6 Functions. 6.1 Focus on Software Engineering: Modular Programming TOPICS. CONCEPT: A program may be broken up into manageable functions.

Functions. Lecture 6 COP 3014 Spring February 11, 2018

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

2. Functions I: Passing by Value

Introduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver)

BITG 1113: Function (Part 2) LECTURE 5

Exceptions, Case Study-Exception handling in C++.

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Exam 2. CSI 201: Computer Science 1 Fall 2016 Professors: Shaun Ramsey and Kyle Wilson. Question Points Score Total: 80

Computer Programming

CS 117 Programming II, Spring 2018 Dr. Ghriga. Midterm Exam Estimated Time: 2 hours. March 21, DUE DATE: March 28, 2018 at 12:00 PM

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Short Notes of CS201

C++ Programming for Non-C Programmers. Supplement

Chapter 6: Functions

Pointers, Dynamic Data, and Reference Types

True or False (15 Points)

6.1. Chapter 6: What Is A Function? Why Functions? Introduction to Functions

Introduction to Programming

CS201 - Introduction to Programming Glossary By

CS2141 Software Development using C/C++ C++ Basics

CSCE 110 PROGRAMMING FUNDAMENTALS

Array Elements as Function Parameters

REVIEW. The C++ Programming Language. CS 151 Review #2

1 Unit 8 'for' Loops

Why Is Repetition Needed?

Chapter 13. Recursion. Copyright 2016 Pearson, Inc. All rights reserved.

Total 100. The American University in Cairo Computer Science & Engineering Department CSCE 106. Dr. Khalil Exam II Fall 2011

CSCE Practice Midterm. Data Types

2 nd Week Lecture Notes

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each):

5. Assuming gooddata is a Boolean variable, the following two tests are logically equivalent. if (gooddata == false) if (!

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

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science

Preview 8/28/2018. Review for COSC 120 (File Processing: Reading Data From a File)

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

Review. Modules. CS 151 Review #6. Sample Program 6.1a:

Exercise 1.1 Hello world

Scientific Computing

CSC 126 FINAL EXAMINATION Spring Total Possible TOTAL 100

Introduction to C++ (Extensions to C)

What we will learn about this week: Declaring and referencing arrays. arrays as function arguments. Arrays

Function Overloading

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

! Pass by value: when an argument is passed to a. ! It is implemented using variable initialization. ! Changes to the parameter in the function body

Functions and Recursion

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

Total 100. The American University in Cairo Computer Science & Engineering Department CSCE 106. Instructor: Final Exam Fall Section No.

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

Standard Version of Starting Out with C++, 4th Edition. Chapter 6 Functions. Copyright 2003 Scott/Jones Publishing

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

1) What of the following sets of values for A, B, C, and D would cause the string "one" to be printed?

LECTURE 06 FUNCTIONS

AN OVERVIEW OF C++ 1

Computing and Statistical Data Analysis Lecture 3

Chapter 7 - Notes User-Defined Functions II

CS242 COMPUTER PROGRAMMING

Pointers, Arrays and C-Strings

A brief introduction to C++

Transcription:

Topics Notes #8 Functions Chapter 6 1) How can we break up a program into smaller sections? 2) How can we pass information to and from functions? 3) Where can we put functions in our code? CMPT 125/128 Dr. B. Fraser 19/06/11 1 19/06/11 2 Functions Functions: Each function should perform... Functions Also called methods, or procedures. Ex: hold the window open, display the menu,... Allows for the divide and conquer approach: Divide: split the big problem down into multiple smaller problems. Conquer: 19/06/11 3 19/06/11 4

Function definition Function definition // A simple C++ program. #include <iostream> using namespace std; void displaymsg() { cout << "Hello world"; displaymsg(); The type of value/information the function returns. displaymsg. List of variables to hold values passed into the function. Statements to carry out the task of the function. Must have () on call or get msg: 19/06/11 5 A function (like a variable) must be For the moment, put the definition of a function earlier (above) in the file than any calls to the function; otherwise will not compile. Function Return Type: a specific type (such as int or double); or 19/06/11 hibye.cpp Example 6 Review What is the difference between defining a function and calling a function? Write a function to display "I code therefore I am." Getting data in and out of a function. 19/06/11 7 19/06/11 8

Function Parameters Function call (use): displaysum( 2, 'a'); void displaysum(int x, char y) { cout << "Sum: " << ( x + y); Parameters Arguments: Parameter List: Inside the (...) of the function header. May be empty if no parameters required. Parameters: Function definition: Arguments Parameter List These are variables inside the method. 19/06/11 displaysum.cpp 9 Returning a value The return statements does 2 things: Causes the current function to exit, returning control to the calling function. /* Return the number of points the user scored based on the number of zombies killed. Returns 0 if number killed is less than 0. */ int calcscore(int numzombies) { if (numzombies < 0) { return numzombies * POINTS_PER_ZOMBIE; 19/06/11 10 Review Write a function: named add() which accepts 2 float parameters; and returns the sum of the two parameters as a float Local vs Global Scope 19/06/11 11 19/06/11 12

Local variables Global variables Local variables: Global variables are Restricted scope (visibility) to within the function. Restricted lifetime to when function is executing. (These Includes function parameters.) What's that mean? Cannot use a local variable outside the function. Local variables are... Accessible anywhere between its definition and the end of the.cpp file. Lifetime is the same as the program. Guidelines: Good for constants: const int DAYS_PER_WEEK = 7; Often problematic for variables: can be very Next time through, a new one is created. Use local variables as much as possible. 19/06/11 local.cpp 13 19/06/11 14 Scope and variable names Static local variables Scope is Static local variables: scope: accessible inside the local function only; Global scope: Local scope to a function: Inside a function. Blocks: Any block {..., such as for a while loop. You could reuse a variable name in different nested scopes, but is very confusing! Try and give variables in nested scope unique names. lifetime:... Lifetime same as the program. Only initialized once! Example: int getnewnum() { static int nextnum = 0; return ++nextnum; // Done once! First value returned is... 19/06/11 scopename.cpp 15 19/06/11 static.cpp 16

Scope, Lifetime, and Puppies Scope Local Global Lifetime Temporary Persistent Pass-by-reference vs pass-by-value 19/06/11 17 19/06/11 18 Pass by value Explaining pass by value Normally, only the value of an argument is passed into the function's parameter. void growolder(int inval) { int age = 25; growolder(age); cout << "Age is: " << age << endl; Changing the parameter's value in a function... Pass by value: function's parameter is set to a copy of argument. Changing the copy does not affect the original. Inside calling code. age 25 Operations on inval never affect age. Inside the function. inval 25 But what if you want to change the value of age when you change inval? 19/06/11 passbyvalue.cpp 19 19/06/11 20

Explaining pass by reference Reference: one variable refers to the actual memory used by the another variable... Pass by reference: function's parameter refers to the actual argument. Changing the parameter's value... Inside calling code. age 25 Operations on inval always affect age. Inside the function. inval 19/06/11 21 Pass by reference To pass-by-reference, put an & between the parameter's type and name in the parameter list. This makes the function's parameter an alias for the calling argument. void growolder(int &inval) { int age = 25; growolder(age); cout << "Age is: " << age << endl; say: "inval is a reference to an int." 19/06/11 passbyvalue.cpp 22 Uses for pass-by-reference Useful for passing back multiple values: // Return true if successfully read first and last names. // Otherwise, return false. bool readname(string &first, string &last); Cautions on Use: Use pass-by-value as much as possible! Use a return value to pass back a single value. Arguments for pass-by-reference... Prototypes Ex: string a, b; readname(a, b); readname("hello", "World"); // Good // Compile Error. 19/06/11 Example: Write a function to swap the value of 2 int variables. 23 19/06/11 24

Prototypes Needed information to call Must know some things about a function to call it. Function prototypes eliminates the need to put To call a function we need to know: number, type, and order of parameters, myprogram.cpp void dostuff() {... dostuff(); myprogram.cpp dostuff(); void dostuff() {... This is the prototype. We can now call dostuff() above where the function is defined. return type of function. Function prototype idea: Rather than defining the whole function at the top, tell the compile at the top of the.cpp file 19/06/11 25 19/06/11 26 Using prototypes Prototype and references Function prototype is similar to a function definition except: (place a ';' instead of {...) Do not need names for parameters. // Prototype void printsum(int x, int y); // or: void printsum(int, int); printsum(1,2); // Display the sum of the two values. void printsum(int x, int y) { cout << x << " + " << y << " = " << (x + y) << endl; 19/06/11 prototype.cpp 27 19/06/11 28 When using pass by reference, function prototype and definition must have the &. void growolder(int &inval); int age = 25; growolder(age); cout << "Age is: " << age << endl; void growolder(int &inval) { Equivalent prototypes: void growolder(int &inval); void growolder(int& inval); void growolder(int &); void growolder(int&);

Summary Function definition: type, name, parameter list, body. Function call must use (): int age = getage(); Use return to pass back a value. Local variables exist only inside the function. Static local variables maintain value between calls. Global variables often bad; global constants good! Pass-by-... Pass-by-value: pass in just a copy. Pass-by-reference: working on actual argument. Use prototypes to define function below a call to it. 19/06/11 29