Call-by-Type Functions in C++ Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #5

Similar documents
More Examples Using Functions and Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #6

Overloading Functions & Command Line Use in C++ CS 16: Solving Problems with Computers I Lecture #6

Func%ons in C++ Part 2 CS 16: Solving Problems with Computers I Lecture #5

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

Advanced Flow Control CS 16: Solving Problems with Computers I Lecture #5

More on Func*ons Command Line Arguments CS 16: Solving Problems with Computers I Lecture #8

Programming with Arrays Intro to Pointers CS 16: Solving Problems with Computers I Lecture #11

(More) Fun with Pointers and Linked Lists! CS 16: Solving Problems with Computers I Lecture #17

Pre- Defined Func-ons in C++ Review for Midterm #1

More on Arrays CS 16: Solving Problems with Computers I Lecture #13

Arrays 2 CS 16: Solving Problems with Computers I Lecture #12

Welcome to Solving Problems with Computers I

Call- by- Reference Func0ons Procedural Abstrac0ons Numerical Conversions CS 16: Solving Problems with Computers I Lecture #9

Linked Lists CS 16: Solving Problems with Computers I Lecture #16

MIPS Assembly: More about MIPS Instructions Using Functions in MIPS CS 64: Computer Organization and Design Logic Lecture #8

Designing Loops and General Debug Pre-Defined Functions in C++ CS 16: Solving Problems with Computers I Lecture #6

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

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

Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2

Vectors and Pointers CS 16: Solving Problems with Computers I Lecture #13

Numerical Conversions Intro to Strings in C/C++ CS 16: Solving Problems with Computers I Lecture #8

Design and Debug: Essen.al Concepts CS 16: Solving Problems with Computers I Lecture #8

Functions and the MIPS Calling Convention 2 CS 64: Computer Organization and Design Logic Lecture #11

Exercises with Linked Lists CS 16: Solving Problems with Computers I Lecture #15

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

File I/O CS 16: Solving Problems with Computers I Lecture #9

Design and Debug: Essen.al Concepts Numerical Conversions CS 16: Solving Problems with Computers Lecture #7

MIPS Assembly: Practice Questions for Midterm 1 Saving to and Loading from Memory CS 64: Computer Organization and Design Logic Lecture #6

File I/O in Python CS 8: Introduction to Computer Science Lecture #11

Basic Data Types and Operators CS 8: Introduction to Computer Science, Winter 2019 Lecture #2

More on Strings in C++ Arrays CS 16: Solving Problems with Computers I Lecture #11

BOOLEAN EXPRESSIONS CONTROL FLOW (IF-ELSE) INPUT/OUTPUT. Problem Solving with Computers-I

File Input / Output Streams in C++ CS 16: Solving Problems with Computers I Lecture #9

Using the MIPS Calling Convention. Recursive Functions in Assembly. CS 64: Computer Organization and Design Logic Lecture #10 Fall 2018

Strings in Python 1 Midterm#1 Exam Review CS 8: Introduction to Computer Science Lecture #6

BITG 1113: Function (Part 2) LECTURE 5

Announcements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy

Algorithms for Arrays Vectors Pointers CS 16: Solving Problems with Computers I Lecture #14

Review for the Final Exam CS 8: Introduction to Computer Science, Winter 2018 Lecture #15

CS16 Midterm Exam 2 E02, 10W, Phill Conrad, UC Santa Barbara Tuesday, 03/02/2010

Computer Programming

MIPS Instruc,ons CS 64: Computer Organiza,on and Design Logic Lecture #8

Function Calling Conventions 2 CS 64: Computer Organization and Design Logic Lecture #10

Physics 2660: Fundamentals of Scientific Computing. Lecture 3 Instructor: Prof. Chris Neu

Character Functions & Manipulators Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10

Welcome to Computer Organization and Design Logic CS 64: Computer Organization and Design Logic Lecture #1 Winter 2018

Dynamic Arrays Makefiles and Mul3ple File Compiles

Lab Instructor : Jean Lai

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

MIPS and Basic Assembly Language CS 64: Computer Organization and Design Logic Lecture #4

Homework 11 Program Setup (with some IMPORTANT NEW STEPS!)

Chapter void Functions. Overview. Functions for All Subtasks. void-functions. Using a void-function. void-function Definition

Spring CS Homework 12 p. 1. CS Homework 12

CIS 130 Exam #2 Review Suggestions

More on File I/O Strings in C++ CS 16: Solving Problems with Computers I Lecture #10

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

File Input/Output Streams in C++ CS 16: Solving Problems with Computers I Lecture #10

CS Exam 2 Study Suggestions

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:

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

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:

WARM UP LESSONS BARE BASICS

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

CS 106B, Lecture 1 Introduction to C++

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

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.

Programmer-Defined Functions

CS103L FALL 2017 UNIT 1: TYPES, VARIABLES,EXPRESSIONS,C++ BASICS

CSE 333. Lecture 10 - references, const, classes. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

Function Calling Conventions 1 CS 64: Computer Organization and Design Logic Lecture #9

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

C++ for Java Programmers

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

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

File I/O in Python Formats for Outputs CS 8: Introduction to Computer Science, Winter 2018 Lecture #12

Deadline. Purpose. How to submit. Important notes. CS Homework 9. CS Homework 9 p :59 pm on Friday, April 7, 2017

CS16 Midterm Exam 1 E01, 10S, Phill Conrad, UC Santa Barbara Wednesday, 04/21/2010, 1pm-1:50pm

Introduc)on to C++ CS 16: Solving Problems with Computers I Lecture #2

Review: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc

CSCI 123 Introduction to Programming Concepts in C++

Physics 2660: Fundamentals of Scientific Computing. Lecture 7 Instructor: Prof. Chris Neu

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

Strings in Python: Cipher Applications CS 8: Introduction to Computer Science, Winter 2018 Lecture #9

Week 4 EECS 183 MAXIM ALEKSA. maximal.io

Chapter 13. Functions and Parameter Passing (Part 2)

Week 3: Pointers (Part 2)

PIC 10A. Review for Midterm I

Introduc)on to Arrays in C++ Review for Midterm #2 CS 16: Solving Problems with Computers I Lecture #12

Midterm Exam #2 Spring (1:00-3:00pm, Friday, March 15)

Binary Arithmetic Intro to Assembly Language CS 64: Computer Organization and Design Logic Lecture #3

Welcome to Computer Organization and Design Logic

Chapter 9: Pointers Co C pyr py igh i t gh Pear ea so s n n E ducat ca io i n, n Inc. n c.

Week 1: Hello World! Muhao Chen

Structures and Classes CS 16: Solving Problems with Computers I Lecture #15

Lab # 02. Basic Elements of C++ _ Part1

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

CS31 Discussion 1E. Jie(Jay) Wang Week1 Sept. 30

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

Homework #3 CS2255 Fall 2012

Flow Control in C++ Condi&onals & Loops CS 16: Solving Problems with Computers I Lecture #4

Transcription:

Call-by-Type Functions in C++ Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #5 Ziad Matni Dept. of Computer Science, UCSB

Administrative CHANGED T.A. OFFICE/OPEN LAB HOURS! Thursday, 10 AM 12 PM Muqsit Nawaz Friday, 11 AM 1 PM Xiyou Zhou Linux Workshop THIS Week! HFH Conference Room (HFH 1132) Friday, April 20 th, 1:00 2:30 PM Material will be put up on the class website Your 1 st Midterm Exam is NEXT TUESDAY (4/24)!!! Omgomgomgomgomgomgomgomgomgomg 4/17/18 Matni, CS16, Sp18 2

Tuesday, 4/24 in this classroom Starts at 2:00 PM **SHARP** Please start arriving 5-10 minutes before class I may ask you to change seats Please bring your UCSB IDs with you Closed book: no calculators, no phones, no computers Only allowed ONE 8.5 x11 sheet of notes one sided only You have to turn it in with your exam You will write your answers on the exam sheet itself. 4/17/18 Matni, CS64, Wi18 3

What s on the Midterm#1? From the Lectures, including Intro to Computers, Programming, and C++ Variables and Assignments Boolean Expressions (comparison of variables) Input and Output on Standard Devices (cout, cin) Data Types, Escape Sequences, Formatting Decimal Arithmetic Operations and their Priorities Boolean Logic Operators Flow of Control & Conditional Statements Loops: for, while, do-while Types of Errors in Programming Multiway Branching and the switch command Generating Random Numbers Functions in C++: pre-defined, user-defined void functions, the main() function call-by-ref vs. call-by-value Command Line Inputs to C++ Programs Separate compilations and makefiles 4/17/18 Matni, CS16, Sp18 4

Midterm Prep 1. Lecture slides 2. Lab programs 3. Homework problems 4. Book chapters 1 thru 5* *check which lecture slides go with it!! 4/17/18 Matni, CS16, Sp18 5

Lecture Outline void functions Call-by-value vs. Call-by-reference Functions Command-line Arguments 4/17/18 Matni, CS16, Sp18 6

Class Exercise 1 Let s write a program together that contains a function, called FallTime, that calculates the time it takes for a mass to be dropped from a variable height h, given the formula: = sqrt(0.2038 d) Algorithm: 1. FallTime will take as argument, d. It will return the value of t. 2. main() will ask the user for h (in meters). 3. main() will call FallTime(h). 4. main() will print out the value of FallTime(h) (in seconds). 4/17/18 Matni, CS16, Sp18 7

Class Exercise 2 Let s write a program together that contains a function, called WriteIt, that takes a string called message and an integer called r. It then prints out the string repeated r times with an exclamation mark and space between each repetition. The function does not return anything. 4/17/18 Matni, CS16, Sp18 8

Call-by-Value vs Call-by-Reference When you call a function, your arguments are getting passed on as values into the function At least, with what we ve seen so far The call funcx(a, b) passes on (into the function) the values of a and b Seems logical enough!? You can also call a function with your arguments used as references to the actual variable location in memory So, you re not passing the variable itself, but it s location in memory! Why would we want to do that? ANS: Vars inside functions are local to the function! What if we wanted them to change outside of it? 4/17/18 Matni, CS16, Sp18 9

Call-by-Reference Parameters Call-by-reference parameters allow us to change the variable used in the function call Call-by-value parameters do NOT change the variable used in the function call In the example shown here, the output would be: x in fun1: 9 x in fun2: 9 Why did a not change?? Why did b change?? a = 5; b = 9 We use the ampersand symbol (&) to distinguish a variable as being called-by-reference, in a function definition int main() { int a = 5, b = 5; fun1(a); fun2(b); cout << "a = " << a << "; "; cout << "b = " << b << endl; } void fun1(int x) // call by value { x += 4; cout << "x in fun1: " << x << endl; } void fun2(int &x) // call by ref. { x += 4; cout << "x in fun2: " << x << endl; } 4/17/18 Matni, CS16, Sp18 10

Call-by-Reference Behavior Assume int variables first and second are assigned memory addresses 1036 and 1040 (this is usually done by the compiler. Also, these are made-up memory addresses!) Now a function call executes: get_numbers(first, second); The function is defined as: void get_numbers(int &first, int &second) { cout << Enter two integers: ; cin >> first >> second; } The function may as well say: void get_numbers(the int var at mem location 1036, the int var at mem location 1040) { cout << Enter two integers: cin >> the variable at memory location 1036; >> the variable at memory location 1040; } 4/17/18 Matni, CS16, Sp18 11

Call-By-Reference Details void fun2(int &x) // call by ref. The memory location of the argument variable is given to the formal parameter Not the argument variable itself! Whatever is done to a formal parameter inside the function, is actually done to the value at the memory location of the argument variable A subtle, but important, difference! It has the effect of making the called-by-reference variable act like a global var. If it changes inside the function, it changes outside the function too But it s better than using a global variable! (why?) 4/17/18 Matni, CS16, Sp18 12

Class Exercise 3 Let s write a program together that contains a function, called swap, that takes a two integer variables as input arguments and causes their values to swap, like in this example: int a = 3, b = 9; cout << a << "; " << b << endl; // This should print out 3; 9 swap(a, b); cout << a << "; " << b << endl; // This should print out 9 ; 3 4/17/18 Matni, CS16, Sp18 13

Example: swap_values void swap(int &variable1, int &variable2) { int temp = variable1; variable1 = variable2; variable2 = temp; } We can ONLY do this if the function is call-by-reference! 4/17/18 Matni, CS16, Sp18 14

Mixed Parameter Lists Call-by-value and call-by-reference parameters can be mixed in the same function Example: void good_stuff(int &par1, int par2, double &par3); par1 and par3 are call-by-reference formal parameters Changes in par1 and par3 change the argument variable par2 is a call-by-value formal parameter Changes in par2 do not change the argument variable 4/17/18 Matni, CS16, Sp18 15

Caution! Inadvertent Local Variables Forgetting the ampersand (&) creates a call-by-value parameter You just ensured that a variable will remain local to the function (when your intention was NOT to do that!) This is a hard error to debug/find because it looks right! So, be careful 4/17/18 Matni, CS16, Sp18 16

4/17/18 Matni, CS16, Sp18 17

Command Line Arguments with C++ In C++ you can accept command line arguments That is, when you execute your code, you can pass input values at the same time These are arguments (inputs) that are passed into the program from the OS command line For example, from the Linux OS command line: $./addthese 2 3 5 $ ß You re passing 2 and 3 as inputs to the program ß and when it s executed, the program gives you its output (answer). 4/17/18 Matni, CS16, Sp18 18

Command Line Arguments with C++ To use command line arguments in your program, you must add 2 special arguments to the main( ) function Argument #1: The number of elements that you are passing in: argc Argument #2: The full list of all of the command line arguments as an array: *argv[ ] This is an array pointer never mind the details, but more on those in a later class 4/17/18 Matni, CS16, Sp18 19

Command Line Arguments with C++ The main() function header should be written as: int main(int argc, char* argv[]) { } instead of int main() { } In the OS, to execute the program, the command line form should be: $ program_name argument1 argument2 argumentn example: $ sum_of_squares 4 5 6 4/17/18 Matni, CS16, Sp18 20

DEMO: int main ( int argc, char *argv[] ) { cout << "There are " << argc << " arguments here:" << endl; cout << "Let s print out all the arguments:" << endl; for (int i = 0; i < argc; i++) cout << "argv[" << i << "] is : " << argv[i] << endl; } return 0; 4/17/18 Matni, CS16, Sp18 21

argv[n] Is Always a Character Type! While argc is always an int (it s calculated by the compiler for you) all you get from the command-line is character arrays This is a hold-out from the early days of C (i.e. pre-c++) So, the data type of argument being passed is always an array of characters (a.k.a. a C-string more on those later in the quarter ) To treat an argument as another type (like a number, for instance), you have to first convert it inside your program <cstdlib> library has pre-defined functions to help! 4/17/18 Matni, CS16, Sp18 22

What If I Want an Argument That s a Number? Examples: atoi( ) and atof( ) argv[] to double These functions are in <cstdlib> Convert a character array into int and double, respectively. Example: argv[] to int #include <iostream> #include <cstdlib> using namespace std; int main(int argc, char *argv[]) { int num1 = atoi(argv[1]); int num2 = atoi(argv[2]); int add = num1 + num2; int prod = num1 * num2; cout << num3 << endl; return 0; } This is the only way that we can do arithmetic on the first 2 arguments 4/17/18 Matni, CS16, Sp18 23

YOUR TO-DOs q Do Lab3 tomorrow (due Monday) q Do HW5 by next Thursday q Visit Prof s and TAs office hours if you need help! q Eat your vegetables 4/17/18 Matni, CS16, Sp18 24

4/17/18 Matni, CS16, Sp18 25