type name(arg1, arg2,...) { body return }

Similar documents
EECS402 Lecture 02. Functions. Function Prototype

The University Of Michigan. EECS402 Lecture 02. Andrew M. Morgan. Savitch Ch. 3-4 Functions Value and Reference Parameters.

Functions. CS111 Lab Queens College, CUNY Instructor: Kent Chin

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

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

CS201- Introduction to Programming Current Quizzes

A SHORT COURSE ON C++

CIS 130 Exam #2 Review Suggestions

Ch 6. Functions. Example: function calls function

switch case Logic Syntax Basics Functionality Rules Nested switch switch case Comp Sci 1570 Introduction to C++

Lab Instructor : Jean Lai

Arrays in C++ Instructor: Andy Abreu

Help File on C++ and Programming at CSUSM by Rika Yoshii

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 (!

Computer Programming: C++

Computer Programming

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

UEE1302(1066) F12: Introduction to Computers and Programming Function (II) - Parameter

CSI33 Data Structures

CS 177 Recitation. Week 8 Methods

CS31 Discussion 1E. Jie(Jay) Wang Week3 Oct.12

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

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions

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

8. Functions (II) Control Structures: Arguments passed by value and by reference int x=5, y=3, z; z = addition ( x, y );

Chapter 7 - Notes User-Defined Functions II

The University of Alabama in Huntsville Electrical and Computer Engineering CPE Example of Objective Test Questions for Test 4


pointers + memory double x; string a; int x; main overhead int y; main overhead

FORM 2 (Please put your name and form # on the scantron!!!!)

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

Chapter 7 Functions. As an example, let us write some code to make a virtual cup of coffee.

Lecture 9 - C Functions

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

Chapter 1. Section 1.4 Subprograms or functions. CS 50 - Hathairat Rattanasook

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

Exercise 1.1 Hello world

CS Exam 2 Study Suggestions

Distributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes

Functions, Arrays & Structs

Programming Language. Functions. Eng. Anis Nazer First Semester

Compiling with Multiple Files The Importance of Debugging CS 16: Solving Problems with Computers I Lecture #7

Chapter 15 - C++ As A "Better C"

Lab 8. Follow along with your TA as they demo GDB. Make sure you understand all of the commands, how and when to use them.

8. The C++ language, 1. Programming and Algorithms II Degree in Bioinformatics Fall 2017

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

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

Week 2. Muhao Chen.

Functions. Introduction :

Exercise: Inventing Language

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

User Defined Functions

Week 4 EECS 183 MAXIM ALEKSA. maximal.io

CS201 Some Important Definitions

Functions. Functions in C++ Calling a function? What you should know? Function return types. Parameter Type-Checking. Defining a function

For loops, nested loops and scopes. Jordi Cortadella Department of Computer Science

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

Functions, Arrays & Structs

Lab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1

C++ Final Exam 2017/2018

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1

BITG 1113: Function (Part 2) LECTURE 5

Functions and Recursion

Functions. Arizona State University 1

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING

Makefiles Makefiles should begin with a comment section of the following form and with the following information filled in:

Your first C++ program

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

CS150 Intro to CS I. Fall Fall 2017 CS150 - Intro to CS I 1

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

Outline. For loops, nested loops and scopes. Calculate x y. For loops. Scopes. Nested loops. Algorithm: repeated multiplication x x x x

Computer Science II Lecture 1 Introduction and Background

EECS 183, Week 5. General. Variables I/O. 0. At which location do you have to take the exam? 1. Source code vs. object code? 2. What s a library?

Lecture 2:- Functions. Introduction

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

CSE 230 Intermediate Programming in C and C++ Functions

What Is a Function? Illustration of Program Flow

Outline. Arrays. Function Arguments. Arrays. Adding Two Arrays /* */ /* This program adds 2 arrays */ ELEC 330 1

Data type of a pointer must be same as the data type of the variable to which the pointer variable is pointing. Here are a few examples:

Local and Global Variables

CS 31 Discussion 1A, Week 4. Zengwen Yuan (zyuan [at] cs.ucla.edu) Humanities A65, Friday 10:00 11:50 a.m.

Operator Overloading and Templates. Linear Search. Linear Search in C++ second attempt. Linear Search in C++ first attempt

CMSC202 Computer Science II for Majors

Introduction to Programming using C++

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

CS31 Discussion 1E. Jie(Jay) Wang Week5 Oct.27

C++ for Java Programmers

Templating functions. Comp Sci 1570 Introduction to C++ Administrative notes. Review. Templates. Compiler processing. Functions Overloading

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Looping. Arizona State University 1

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

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.

Exam I KEY (corrected)

To become familiar with array manipulation, searching, and sorting.

CS 106B Lecture 2: C++ Functions

How to approach a computational problem

Transcription:

defining functions function: a group of statements given a name that can be called from some point in the program. Functions allow us to write programs in pieces of code that perform individual tasks type name(arg1, arg2,...) { body return type: type of value (e.g. int, double, string, etc.) returned by the function name: identifier for calling the function arguments: arg1, arg2,... (as many as you want): each argument is a variable for the function to use. Arguments allow us to pass information to the function from where it is called body: a group of statements surrounded by { that tell what the function does return: a special statement that passes information back to where the function was called. The return value must have the same type as type (e.g. int, double, string, etc.). Often considered part of the body. CS31 Fall 2014 Discussion 4: Functions

an example function int add(int x, int y) { return type function name arguments int z = x + y; return z; body return value of return type type: int name: add arguments: int x, int y (notice arguments are specified like variable declarations: type name) body: int z = x + y return: return z (specification: return name) task: adds two numbers x and y and returns the result CS31 Fall 2014 Discussion 4: Functions

another example function return type function name no arguments statements return 0; body can also return a literal type: int name: main (main is a special c++ function. It s the only one that is automatically called when running a program. All other functions must be called from the main function arguments: none (for now) body: bunch of statements return: return 0 (if the main function is missing a return statement, the compiler assumes a return 0; ) task: whatever your heart desires (so long as you can program it) CS31 Fall 2014 Discussion 4: Functions

using or calling functions: function call execution spaces: place where a program runs. spaces don t share data space 0 int add(int x, int y) { int z = x + y; return z; 1: before function call: A. program starts B. a = 1, b = 2 int a = 1, b = 2; int c = add(a, b); cout << c << endl;

using or calling functions: function call space 0 int add(int x, int y) { int z = x + y; return z; int a = 1, b = 2; int c = add(a, b); cout << c << endl; execution paused for add function call space 1 int add(int x = 1, int y = 2) { int z = x + y; return z; 1: before function call: A. program starts B. a = 1, b = 2 2: add function is called: A. space 0 (main) is paused B. space 1 is created to run add C. the values of a and b are copied into this new space, and renamed to the local variable names x and y. Thus, x = a, which is 1, and y = b, which is 2 D. space 1 (add function) runs

using or calling functions: return space 0 int add(int x, int y) { int z = x + y; return z; int a = 1, b = 2; int c = 3; cout << c << endl; space 1 int add(int x = 1, int y = 2) { int z = 1 + 2; // z = 3 return z; 1: before function call: A. program starts B. a = 1, b = 2 2: add function is called: A. space 0 (main) is paused B. space 1 is created to run add C. the values of a and b are copied into this new space, and renamed to the local variable names x and y. Thus, x = a, which is 1, and y = b, which is 2 D. space 1 (add function) runs 4: return: end of the function is reached A. program returns to the location in space 0 where add was originally called B. replace the call with the return value (i.e. 3). space 1 disappears

using or calling functions: return space 0 int add(int x, int y) { int z = x + y; return z; int a = 1, b = 2; int c = 3; cout << c << endl; 1: before function call: A. program starts B. a = 1, b = 2 2: add function is called: A. space 0 (main) is paused B. space 1 is created to run add C. the values of a and b are copied into this new space, and renamed to the local variable names x and y. Thus, x = a, which is 1, and y = b, which is 2 D. space 1 (add function) runs 4: return: end of the function is reached A. program returns to the location in space 0 where add was originally called B. replace the call with the return value (i.e. 3). space 1 disappears 5: after function call: A. space 0 (main) resumes with 3 replacing the function call to add. B.Then prints 3

more examples of calling add int add(int x, int y); // literals int a = add(1, 2); cout << a << endl; more ways to call add // user input int a, b, c; cin >> a >> b; int c = add(a, b); cout << c << endl; // w/o storing the result cout << add(2, 4); 6 int add(int x, int y){ return x + y; declared first 3? define later int a = add(1, 2) + add(3, 4); cout << a << endl; 10 multiple calls int c = add(10,5); int d = add(c, 3); int e = add(6, d); cout << e << endl; nested calls int a = add(1, add(3, 4)); cout << a << endl; 3 24 int b = add(add(1,2), add(3,4)); cout << b << endl; 10 int c = add(10,5); cout << add(add(c, c), 1); 31

function calling problems with add, sub int add(int x, int y) { return x + y; what s the output? int sub(int x, int y) { return x - y; how to get this output? let x = 2, y = 5, z = -3 sub(1, 2) + sub(2, 1) 0 10 add(y, y) add(sub(2, 1), sub(1, 2)) 0-2 sub(sub(add(y, z), x), x) sub(10, add(2, 3)) 5 5 w/o y sub(x, z) add(1, sub(3, add(2, 3))) -1-1 w/o z sub(add(x, x), y) add(a, a) 2a 0 sub(sub(y, z), add(add(x, x), add(x,x))

more function examples calculates hypotenuse length #include <cmath> new library for std::sqrt double square(double x) { return x * x; double a, x, y, d; cin >> x >> y; a = square(x) + square(y); d = sqrt(a); cout << Distance: << d; builtin-function of cmath library Notice this function has return type void, so it does not return anything, and does not require a return statement at the end draws pyramids void draw_line(int size); int i, j, n; cin >> n; declared first for (i = 0; i < 2 * n; i++) { if (i <= n) { // up draw_line(i); else { // down draw_line(2 * n - i); void draw_line(int size); { for (int i = 0; i < size; i++) { cout << 0 ; defined later cout << endl;

nested functions calculates hypotenuse length int square(int x) { return x * x; int approx_sqrt(int x2) { int x = 0; while (square(x) < x2) { x++; return x; int hyp_length(int x, int y) { int z = square(x) + square(y); return approx_sqrt(z); double x, y; cin >> x >> y; cout << hyp_length(x, y) << endl;

pass-by-value vs. pass-by-reference when the execution space is created: value: argument values are copied into the function space. The original arguments are unchanged. reference: argument variables are passed directly into the function space, and can change upon exit. Why is this useful? 1. efficiency: copying argument values can be expensive if the arguments take up a large space in memory (e.g. really long strings like whole novels, or datatypes that take lots of memory) 2. returning multiple arguments: functions can have as many arguments as you want, but only one return value. By being able to change the input arguments, you can effectively return more data function definition function call pass-by-value int square(int x) { return x * x; int x = 10; x = square(x); cout << x << endl; pass-by-reference void square(int& x) { x = x * x; int x = 10; square(x); cout << x << endl;

pass-by-reference examples swap void swap(int& a, int& b) { int c = a; a = b; b = c; int x = 10, y = 5; cout << x << << y; swap(x, y); cout << x << << y; sort (small to large) void sort(int& a, int& b) { if (a > b) { swap(a, b); #include <cctype> string capitalizer void capitalizer(string& s) { for (int i = 0; i < s.size(); i++) { s[i] = toupper(s[i]); string hi = Hello! ; capitalizer(hi); cout << hi << endl; library for toupper(char c) sort3 (small to large) void sort3(int& a, int& b, int& c) { if (a > b) { swap(a, b); if (b > c) { swap(b, c); if (a > b) { swap(a, b);

project 3 tips Incremental development: break down the program from larger steps into a bunch of smaller simpler steps, perhaps structured into various functions that perform specific tasks Comment well, so that both you and your TA can follow along what your program is doing Read all of the links on the website about processing strings and functions

overloading functions overloaded functions: same name, different inputs A debugging program void debug(int x) { cout << int: << x << endl; void debug(double x) { cout << double: << x << endl; void debug(string s) { cout << string: << s << endl; Can print many types of variables with the same function and get info about the variable s type math functions int square(int x) { return x * x; double square(double x) { return x * x; float square(float x) { return x * x; Many math functions are available for different numerical types