PIC 10A Flow control. Ernest Ryu UCLA Mathematics

Similar documents
REPETITION CONTROL STRUCTURE LOGO

DELHI PUBLIC SCHOOL TAPI

Maciej Sobieraj. Lecture 1

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

Input And Output of C++

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

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

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

These are notes for the third lecture; if statements and loops.

How to approach a computational problem

5. Control Statements

Chapter 2 Basic Elements of C++

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

The C++ Language. Arizona State University 1

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Objectives. In this chapter, you will:

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

8. Control statements

Your first C++ program

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Numerical Computing in C and C++ Jamie Griffin. Semester A 2017 Lecture 2

Chapter 2. C++ Basics

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

Computer Programming : C++

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

Introduction. C provides two styles of flow control:

The following expression causes a divide by zero error:

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

PIC 10A Objects/Classes

CSCE 121 ENGR 112 List of Topics for Exam 1

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

Increment and the While. Class 15

1 Unit 8 'for' Loops

2 nd Week Lecture Notes

Chapter 4. Computation. Bjarne Stroustrup.

Relational Operators and if. Class 10

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

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

Introduction to Programming using C++

Chapter 4 Introduction to Control Statements

Why Is Repetition Needed?

CGS 3066: Spring 2015 JavaScript Reference

C++ Data Types. 1 Simple C++ Data Types 2. 3 Numeric Types Integers (whole numbers) Decimal Numbers... 5

Chapter 2: Introduction to C++

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

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Flow Control. CSC215 Lecture

Chapter 4 - Notes Control Structures I (Selection)

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

Starting Out with C++: Early Objects, 9 th ed. (Gaddis, Walters & Muganda) Chapter 2 Introduction to C++ Chapter 2 Test 1 Key

Chapter 2 C++ Fundamentals

Scientific Computing

Programming for Engineers Iteration

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

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

Chapter 3 - Simple JavaScript - Programming Basics. Lesson 1 - JavaScript: What is it and what does it look like?

Boolean Algebra Boolean Algebra

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 INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Unit 7. 'while' Loops

LECTURE 02 INTRODUCTION TO C++

Introduction to C++ Lecture Set 2. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 1

Programming for Electrical and Computer Engineers. Loops

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

Programming Language. Functions. Eng. Anis Nazer First Semester

Chapter 4 Computation

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:

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

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

Text Input and Conditionals

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

DECISION STRUCTURES: USING IF STATEMENTS IN JAVA

Chapter 6. Loops. Iteration Statements. C s iteration statements are used to set up loops.

CSCI 1061U Programming Workshop 2. C++ Basics

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

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

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

2. First Program Stuff

CSc Introduc/on to Compu/ng. Lecture 8 Edgardo Molina Fall 2011 City College of New York

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

CS106X Handout 03 Autumn 2012 September 24 th, 2012 Getting Started

YOLOP Language Reference Manual

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

4.1. Chapter 4: Simple Program Scheme. Simple Program Scheme. Relational Operators. So far our programs follow a simple scheme

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

download instant at Introduction to C++

Programming, numerics and optimization

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

Chapter 2. Flow of Control. Copyright 2016 Pearson, Inc. All rights reserved.

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;

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

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

Transcription:

PIC 10A Flow control Ernest Ryu UCLA Mathematics

If statement An if statement conditionally executes a block of code. # include < iostream > using namespace std ; int main () { double d1; cin >> d1; if (d1 <0) { cout << " Error. Negative input!" << endl ; 2

If-else statement An if-else statement conditionally executes one of the alternatives. # include < iostream > using namespace std ; int main () { int n; cin >> n; if (n>0) { cout << " n is positive." << endl ; else { cout << " n is not positive." << endl ; 3

If-else statement An if-else statement can have more than one alternatives. int main () { int n; cin >> n; if (n>0) { cout << " n is positive." << endl ; else if (n<0) { cout << " n is negative." << endl ; else { cout << " n is 0." << endl ; 4

Flow control The programs we had encountered had a linear sequence of instructions. However, real programs may bifurcate, repeat code, and take decisions. Control structures allow programs to follow a more complicated flow. 5

The type bool A Boolean (named after Prof. Boole) is a data type with two possible values: true or false. The type bool represents a Boolean value. bool is a fundamental type. (#include not needed.) A literal of type bool is written as true false No capitals. bool b = true ; cout << b << endl ; The output is 1. 6

Comparison operators The comparison/relational operators are >, >=, <, <=, ==, and!=. When used with integer types or floating-point types, they return a bool. They represent >,, <,, =, and. bool b = ( 454 < 324 ); cout << b << endl ; cout << ( 6.4!= 3.2 ) << endl ; The output is 0 and 1. 7

Comparison operators The comparison operator == is closer to = than the assignment operator =. Never use == (or!=) with floating-point numbers! double d1 = 3./15. ; double d2 =.3 / 1.5 ; cout << ( d1 == d2) << endl ; The output is 0. (Results may vary. Each CPU handles round-off errors slightly differently.) An operator does different things based on what type it is used with. On strings, comparison operators look at the lexicographical order. string s1 = " Alice "; string s2 = " Bob "; cout << ( s1 < s2) << endl ; The output is 1. 8

Comparison operators: warning Do not mix up = and ==. 9

Logical operators The Logical operators are &&,, and!. && = and = conjunction = = or = disjunction =! = not = negation = bool b1 = true ; bool b2 = false ; cout << ( b1 && b2) << endl ; cout << ( b1 b2) << endl ; cout <<! b1 << endl ; The output is 0, 1, and 0. 10

Logical operators: warning Use && and. & and are something else! You can t do int x = 5; cout << ( 4 <= x <= 10) << endl ; (Why?) Instead do int x = 5; cout << ( 4 <= x && x <= 10) << endl ; 11

while loop The while loop while (condition) { code to run loops through the code as long as the condition is true. (Running while the condition is true.) The code runs 0, 1, 2,..., or even infinitely many times. 12

while loop This code prints integers 0, 1,..., n-1. # include < iostream > using namespace std ; int main () { int n, i = 0; cin >> n; while (i < n) { cout << i << endl ; i += 1; The code in the loop executes n times. 13

while loop: example I put $100 in my bank, which gives 4% annual interest. How many years until it becomes $300? int main () { double annual_ interest, current_ money, goal ; int years = 0; cin >> annual_ interest ; cin >> current_ money ; cin >> goal ; while ( current_ money < goal ) { current_ money *= ( 1. + annual_ interest ); years += 1; cout << " You ll reach your goal after "; cout << years << " years " << endl ; 14

Infinite loop An infinite loop is a loop that never ends while ( true ) { cout << " This will never end." << endl ; Infinite loops (mostly) happen by accident. In the interest example, the loop never terminates if the interest is 0.0. 15

Increment/decrement operator The increment/decrement operators are ++ and --. Actually, there are 4 such operators. When x is of type int, ++x pre-increment x++ post-increment --x pre-decrement x-- post-decrement ++x and x++ are similar to x += 1. (Increment the value of x by 1.) --x and x-- are similar to x -= 1. (Decrement the value of x by 1.) ++x and x++ (--x and x--) are slightly different. More on this later. 16

Increment/decrement operator int a = 10; while (a>0) { cout << a << endl ; a - -; Output is 10, 9,..., 1. 17

for loop The for loop for (intialization; condition; update) { code to run executes the initialization, loops through the code as long as the condition is true, and perform the update after each loop. It is similar to initialization while (condition) { code to run update 18

for loop for loops can be slightly cleaner than while loops # include < iostream > using namespace std ; int main () { int n; cin >> n; for ( int i=0; i<n; i ++) { cout << i << endl ; Output is 0, 1,..., n-1. 19

for loop You are running the loop for i equals 0 through n-1. for ( int i=0; i<n; i ++) {... 20

for loop: warning When you get the iteration index of a loop off by one, you commit an off-by-one error. If you wish to print 1, 2,..., n, the program # include < iostream > using namespace std ; int main () { int n; cin >> n; for ( int i=0; i<n; i ++) { cout << i << endl ; has an off-by-one error. The for loop should be for ( int i=1; i <=n; i ++) 21

do-while loop Similar to the while loop, but will run the loop at least once. # include < iostream > # include < string > using namespace std ; int main () { string s; do { cout << " Enter text : "; cin >> s; cout << " You entered : " << s << "\n"; while (s!= " goodbye "); 22

break The break statement exits a loop. string s; while ( true ) { cout << " Enter text : "; cin >> s; if (s == " goodbye ") { break ; cout << " You entered : " << s << "\n"; 23

continue The continue statement skips the remaining part of the loop and continues to the next iteration. for ( int i = 1; i <= 10; ++i) { if ( i==6 i==9 ) { continue ; cout << i << endl ; Sometimes, using continue and break makes the code cleaner. 24

Useful digression: Boolean algebra In Elementary algebra (the algebra you know) you learned things like a + b = b + a a (b + c) = a b + a c. Elementary algebra studies arithmetic on real numbers. Boolean algebra is the study of things like a or b = b or a a and (b or c) = (a and b) or (a and c). Boolean algebra studies logical operations on Booleans. https://en.wikipedia.org/wiki/boolean_algebra 25

Useful digression: Boolean algebra The notation seems intimidating. However, it s not that hard if you think by example. a or b = b or a You must be smart or hardworking. = You must be hardworking or smart. a and (b or c) = (a and b) or (a and c) Your shirt must have long sleeves, and it must be red or green. = Your shirt must be a red long-sleeve or a green long-sleeve. 26

Useful digression: Boolean algebra Useful identities of Boolean algebra. Distributivity of and over or a and (b or c) = (a and b) or (a and c) Distributivity of or over and a or (b and c) = (a or b) and (a or c) 27

Useful digression: Boolean algebra De Morgan s law 1 not (a or b) = (not a) and (not b) This is a club for those who are smart or hard-working. He s not allowed because he s not smart and he lazy. De Morgan s law 2 not (a and b) = (not a) or (not b) To enter this establishment, you must have shoes and a shirt. If you barefoot or shirtless, you re not allowed. Again, this isn t that hard if you think by example. 28

Useful digression: Boolean algebra The truth table of the 3 logical operators is a b a && b a b!a false false false false true false true false true true true false false true false true true true true false 29

Useful digression: Boolean algebra The Venn diagram for a && (b c) b a c The shaded area also represents (a && b) (a && c). 30

Short-circuit evaluation In C++, && and implement short-circuit evaluation; the second bool isn t evaluated if the first bool determines the output. int numer = 4, denom = 0; if ( denom!= 0 && ( numer / denom < 7) ) { cout << " Short - circuit eval example " << endl ; This is also called minimal evaluation and McCarthy evaluation. Short-circuit evaluation is efficient and convenient: the program doesn t spend time evaluating the second expression, and we can take advantage of this feature to make code concise. 31

Why does this work? # include < iostream > # include < string > using namespace std ; int main () { string s; while ( true ) { cout << " Enter text : "; cin >> s; if (s == " goodbye ") break ; cout << " You entered : " << s << "\n"; 32

Why does this work? # include < iostream > using namespace std ; int main () { int n; cin >> n; for ( int i=0; i<n; i ++) for ( int j=0; j<n; j ++) cout << i << ", " << j << endl ; The 2 code snippets are in compliance with the rules for constructing if statements and for loops. What are these precise rules? 33

Why bother with precise syntax? We ll learn some precise syntax. Here s why. Generally, you don t have to know the precise syntax. Even with a vague understanding of the rules, you are capable of writing control structures. In real life, you learn the rules more precisely over time and achieve a more deeper understanding. Nothing wrong about this. There is pedagogical value to learning the precise rules upfront, especially since this is a first course in programming. Programs follow rigid instructions. When you program, the compiler, a program itself, converts your program into an executable. So the syntax of a programming language is a collection of precise and rigid set of rules. 34

Statements A C++ program comprises a series of statements. There are several types: declaration statements string s; int i=0; jump statements break; continue; expression statements compound statements selection statements if and if-else statement iteration statements for, while, and do-while loops 35

Expression statements Roughly speaking, an expression is a line of code that evaluates to something. They are things like i = 4 + j i++ 34.23 cout << "UCLA" << endl b1 && b2 (the empty expression) Terminate an expression with ; to get an expression statement. 36

Null statements The null statement is the empty expression terminated with ; So the following 4 statements string s = " UCLA "; cout << s << endl ;;; are legal. The code will compile. Needless to say, 2 of the 3 expression statements are unnecessary. 37

Useful digression: whitespace in C++ Whitespace is the set of characters like space, tab, and newline. In C++, whitespace mostly mean nothing to the computer. So you could write your program like # include < iostream > using namespace std ; int main (){ int i;cin >>i;cout <<" Good morning. The input However, do use whitespace to make your code human-readable. 38

Compound statements A compound statement compounds multiple statements into one with curly braces. { statement statement... statement 39

if and if-else statement The precise syntax for if and if-else statement are if (expression) statement if (expression) statement else statement So if ( true ) { cout << " output 1" << endl ; cout << " output 2" << endl ; is legal since the block of code within { and compose a single compound statement. 40

if and if-else statement When you only have a single expression statement, { and are unnecessary. if ( true ) cout << " output 1" << endl ; else cout << " output 1" << endl ; is legal. 41

if and if-else statement The 2 statements if (i < n) { cout << i << endl ; ; are legal and will compile. However, the extra null statement suggests that the author doesn t understand the language (in particular about expressions and statements) terribly well. An if statement doesn t need a semicolon at the end! 42

while loop The precise syntax for a while loop is while (expression) statement So while ( true ) cout << " This will never end." << endl ; is a single legal (iteration) statement. 43

for loop The precise syntax for a for loop is for (statement expression; expression) statement So for (; true ; ) cout << " This will never end." << endl ; is a single legal (iteration) statement. 44

for loop The following (legal) program contains 3 statements # include < iostream > using namespace std ; int main () { int n; cin >> n; for ( int i=0; i<n; i ++) for ( int j=0; j<n; j ++) cout << i << ", " << j << endl ; What are the 3 statements? Why is the for loop legal? 45

do-while loop The precise syntax for a do-while loop is do statement while (expression); Unlike the other control structures, the do-while loop does require a semicolon at the end! string s; do { cout << " Enter text : "; cin >> s; cout << " You entered : " << s << "\n"; while (s!= " goodbye "); Without ; the code wouldn t compile. 46

The following code doesn t compile int main () { int i = 5; cout << i << endl ; int i = 10; cout << i << endl ; Why does this work? because you can t declare i a variable twice. However, this works. for ( int i=0; i<5; i ++) cout << i << endl ; for ( int i=5; i>0; i - -) cout << i << endl ; Why? 47

Variable scope The scope of a variable is the part of the code where the variable is available. Throughout a program, variables are created and destroyed. A destroyed variable is inaccessible. A variable (not yet destroyed) may be inaccessible for other reasons. More on this later. 48

Variable scope: compound statements Variables declared within a compound statement go out of scope at the end of the compount statement. int i = 0; { i = 2; int j = 5; cout << i << ", " << j << endl ; cout << i << endl ; cout << j << endl ; This won t compile. By the time the program reaches the last line, j went out of scope. 49

Variable scope: for loop A variable declared within the initialization statement of a for loop is in scope throughout the loop, but not after. for ( int i=0; i <5; i ++) { cout << " For loop is looping " << endl ; cout << i << endl ; cout << i << endl ; This doesn t compile: i is destroyed once the for loop is done. 50

Variable scope: for loop In contrast, the following does compile. int i; for (i=0; i <5; i ++) { cout << " For loop is looping " << endl ; cout << i << endl ; cout << i << endl ; 51

Variable scope It is often good to limit the scope of a variable. More on this later. Usually, you don t want to use generic variable names like i or str. You may later accidentally use it when you mean to create a different variable. It s fine to use the variable name i it within a for loop, as it goes out of scope after the loop. 52