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

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

Call-by-Type Functions in C++ Command-Line Arguments in C++ 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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Chapter 3. More Flow of Control

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

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

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

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

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

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

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

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

Dynamic Arrays Makefiles and Mul3ple File Compiles

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

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

Using Boolean Expressions. Multiway Branches. More about C++ Loop Statements. Designing Loops. In this chapter, you will learn about:

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

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

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

Welcome to Solving Problems with Computers I

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

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

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

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

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

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

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

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

C++ Programming: From Problem Analysis to Program Design, Third Edition

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

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

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

DHA Suffa University CS 103 Object Oriented Programming Fall 2015 Lab #01: Introduction to C++

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

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

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

Strings and Stream I/O

Announcements. Homework 0: using cin with 10/3 is NOT the same as (directly)

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

Communication With the Outside World

Lecture 7. Log into Linux New documents posted to course webpage

CS 106B, Lecture 1 Introduction to C++

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

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

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

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

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

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

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)

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

CS111: PROGRAMMING LANGUAGE II

C++ Basics 1 CS 16: Solving Problems with Computers I Lecture #3

In this chapter you will learn:

Unit 7. 'while' Loops

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

LAB #8. Last Survey, I promise!!! Please fill out this really quick survey about paired programming and information about your declared major and CS.

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.

C/C++ Functions. Mark Redekopp

CS 101 Computer Programming and utilization. Dr Deepak B Phatak Subrao Nilekani Chair Professor Department of CSE, Kanwal Rekhi Building IIT Bombay

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

C++ for Java Programmers

int n = 10; int sum = 10; while (n > 1) { sum = sum + n; n--; } cout << "The sum of the integers 1 to 10 is " << sum << endl;

CIS 130 Exam #2 Review Suggestions

C++ Programming Lecture 7 Control Structure I (Repetition) Part I

C++ Lab 02 - Command Line Arguments and Strings

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:

Lab Instructor : Jean Lai

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Announcements. HW0 is posted on schedule, due next Friday at 9pm (pretty easy)

#include <iostream> #include <algorithm> #include <cmath> using namespace std; int f1(int x, int y) { return (double)(x/y); }

Chapter 3, Selection. Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved.

File I/O and String Manipula3ons CS 16: Solving Problems with Computers I Lecture #11

CSCE 206: Structured Programming in C++

Introduction to Computer Science Midterm 3 Fall, Points

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

CSCE Practice Midterm. Data Types

Local and Global Variables

LAB #8. GDB can do four main kinds of things (plus other things in support of these) to help you catch bugs in the act:

Lecture 15a Persistent Memory & Shared Pointers

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

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

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

CSCE Practice Midterm. Data Types

Object Oriented Design

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS240 BRANCHING STATEMENTS

Transcription:

Advanced Flow Control CS 16: Solving Problems with Computers I Lecture #5 Ziad Matni Dept. of Computer Science, UCSB

Announcements Demos done in class can be found at: hcp://www.cs.ucsb.edu/~zmatni/cs16s17/demos Turn in homework #4! Lab #2 due today (at noon) Homework #5 assigned Lab #3 will be assigned later on today Note, this lab is due later than usual Midterm #1 is coming!!!!! 4/18/17 Matni, CS16, Sp17 2

Material: Everything we ve done, incl. up to Th. 4/20 Homework, Labs, Lectures, Textbook Tuesday, 4/25 in this classroom Starts at 12:30pm **SHARP** Pre- assigned seazng DuraMon: 1 hour long Closed book: no calculators, no phones, no computers Only 1 sheet (single- sided) of writen notes Must be no bigger than 8.5 x 11 You have to turn it in with the exam You will write your answers on the exam sheet itself. 4/18/17 Matni, CS16, Fa16 3

Lecture Outline Boolean Expressions in Flow Control MulMway Branches Switch Branching Command Line Inputs to C++ Programs FuncMons in C++ (on Wednesday) 4/17/17 Matni, CS16, Sp17 4

Run Time Errors Compile Time Errors Errors that occur during compila1on of a program. Run Time Errors Errors that occur during the execu1on of a program RunMme errors indicate bugs in the program (bad design) or unanmcipated problems (like running out of memory) Examples: Dividing by zero Bad memory calls in the program (bad memory address) SegmentaMon errors (memory over- flow) 4/17/17 Matni, CS16, Sp17 5

Short- Circuit EvaluaMon Avoid possible run 0me errors by using the right Boolean expression If you strategically use the && operator, then some Boolean expressions do not need to be completely evaluated Especially if they can potenmally cause run Mme errors This is known as short- circuit evaluamon Consider this if- statement: if (pieces / kids >= 2) etc ß what s a potential problem? if ( (kids!= 0) && (pieces / kids >= 2) ) etc 4/17/17 Matni, CS16, Sp17 6

MulMway Branching NesMng (embedding) one if/else statement in another. if (count < 10) { if ( x < y) cout << x << " is less than " << y; else cout << y << " is less than " << x; } Note the tab indentamon at each level of nesmng. There are pi_alls to wrizng nested if/else statements, so be careful in how you write these!!! Watch your indentamons Make use of { } brackets to make it clear what your intenmons are 4/17/17 Matni, CS16, Sp17 7

What s Wrong With This Code? if (fuel_gauge_reading < 0.75) if (fuel_gauge_reading < 0.25) cout << "Fuel very low. Caution!\n"; else cout << "Fuel over 3/4. Don't stop now!\n"; 4/17/17 Matni, CS16, Sp17 8

Defaults in Nested IF/ELSE Statements When the condimons tested in an if- else- statement are mutually exclusive, the final if- else can somemmes be omited EXAMPLE: if (guess > number) cout << Too high. ; else if (guess < number) cout << Too low. ; else if (guess == number) cout << Correct! ; if (guess > number) cout << "Too high."; else if (guess < number) cout << "Too low. ; else cout << "Correct!"; i.e. All other possibilimes 4/17/17 Matni, CS16, Sp17 9

A BeTer Way Using switch AlternaMve for construcmng mulm- way branches Syntax is: switch (variable) { case variable_value1: statements; break; case variable_value2: statements; break; Controlling statement break statement is important you cannot forget it! default: statements; } 4/17/17 Matni, CS16, Sp17 10

The Controlling Statement A switch statement's controlling statement must return one of these types: A bool value An int type A char type switch will not work with strings in the controlling statement. 4/18/17 Matni, CS16, Sp17 11

Can I Use the break Statement in a Loop? Yes, technically, the break statement can be used to exit a loop before normal terminamon But it s not good design pracmce! In this class, do NOT use it outside of switch 4/17/17 Matni, CS16, Sp17 12

Note About Blocks A block is a secmon of code enclosed by { } braces Variables declared within a block, are local to the block i.e. They have the block as their scope. Variable names declared in the block cannot be re- used outside the block 4/17/17 Matni, CS16, Sp17 13

Local vs. Global Variables Local variables only work in a specified block of statements Global variables work in the enmre program There are standards to their use Local variables are much preferred as global variables can cause conflicts in the program For example, C++ standard (ANSI) requires that a variable declared in the for- loop inimalizamon secmon be local to the block of the for- loop 4/17/17 Matni, CS16, Sp17 14

Note on Increments: num++ vs ++num (num++) returns the current value of num, then increments it An expression using (num++) will use the value of num BEFORE it is incremented (++num) increments num first and returns its new value An expression using (++num) will use the value of num AFTER it is incremented num has the same value afer either version! Example on the next page 4/17/17 Matni, CS16, Sp17 15

Example: num++ vs ++num int num = 2; int value_produced = 2 * (num++); cout << value_produced << " " << num; Displays: 4 3 int num = 2; int value_produced = 2* (++num); cout << value_produced << " " num; Displays: 6 3 In either case, num ends up being 3. Works the same way with decrements (- - operator) 4/17/17 Matni, CS16, Sp17 16

4/18/17 Matni, CS16, Sp17 17

Command Line Arguments with C++ In C++ you can accept command line arguments These are arguments that are passed into the program from the OS command line To use command line arguments in your program, you must add 2 special arguments in the main() funcmon Argument #1 is the number of elements (argc) Argument #2 is a full list of all of the command line arguments: *argv[] This is an array pointer more on those in a later class 4/18/17 Matni, CS16, Fa16 18

Command Line Arguments with C++ The main() funcmon should be writen as: int main(int argc, char* argv[]) { } 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/18/17 Matni, CS16, Fa16 19

DEMO: int main ( int argc, char *argv[] ) { cout << "There are " << argc << " arguments here:" << endl; for (int i = 0; i < argc; i++) cout << "argv[" << i << "] is : " << argv[i] << endl; } return 0; 4/18/17 Matni, CS16, Fa16 20

argv[n] Is Always a Character! All you get from the command- line is character arrays So, the data type of argument being passed is always an array of characters (a.k.a. a C- string) To treat an argument as another type, you have to convert it inside your program <cstdlib> library has pre- defined funcmons to help! 4/18/17 Matni, CS16, Fa16 21

What If I Want an Argument That s a Number? <cstdlib> library has pre- defined funcmons to help! Examples: atoi( ), atol( ), and atof( ) Convert a character array into int, long, and double, respecmvely. Example: #include <iostream> #include <cstdlib> using namespace std; int main(int argc, char *argv[]) { for(int i = 1; i < argc; i++) cout << atoi(argv[i]) << endl; return 0; } 4/18/17 Matni, CS16, Fa16 22

Programmer- Defined FuncMons There are 2 necessary components for using funcmons in C++ FuncZon declarazon (or funcmon prototype) Just like declaring variables Must be placed outside the main(), usually before it Must be placed before the funcmon is defined & called FuncZon definizon This is where you define the funcmon itself Must be place outside the main() Can be before it or aser it 4/18/17 Matni, CS16, Fa16 23

Programmer- Defined FuncMons FuncZon declarazon Shows how the funcmon is called from main() or other funcmons Must appear in the code before the funcmon can be called Syntax: Type_returned Function_Name(Parameter_List); //Comment describing what function does FuncZon definizon Describes how the funcmon does its task Can appear before or aser the funcmon is called Syntax: Type_returned Function_Name(Parameter_List) { //code to make the function work } ; Only needed for declara0on statement 4/18/17 Matni, CS16, Fa16 24

Example of a Simple FuncMon in C++ #include <iostream> using namespace std; int sum2nums(int num1, int num2); int main ( ) { int a(3), b(5); int sum = sum2nums(3, 5); cout << sum << endl; return 0; } int sum2nums(int num1, int num2) { return (num1 + num2); } DeclaraZon Call DefiniZon 4/18/17 Matni, CS16, Sp17 25

TO DOs Readings Ch. 4 of textbook Homework #5 for Thursday Lab #3 for 5/1 Prep for Midterm Exam #1! 4/17/17 Matni, CS16, Sp17 26

4/17/17 Matni, CS16, Sp17 27