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

Similar documents
Sixth lecture; classes, objects, reference operator.

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

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

COSC 2P91. Introduction Part Deux. Week 1b. Brock University. Brock University (Week 1b) Introduction Part Deux 1 / 14

Maciej Sobieraj. Lecture 1

printf( Please enter another number: ); scanf( %d, &num2);

1007 Imperative Programming Part II

PIC 10A Objects/Classes

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

Intro. Scheme Basics. scm> 5 5. scm>

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

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

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

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++

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

C++ Support Classes (Data and Variables)

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Unit 7. 'while' Loops

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

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language. Dr. Amal Khalifa. Lecture Contents:

Variables and literals

Expressions and Casting

Coding Workshop. Learning to Program with an Arduino. Lecture Notes. Programming Introduction Values Assignment Arithmetic.

CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch

Java Bytecode (binary file)

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

CS102: Variables and Expressions

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

Looping and Counting. Lecture 3 Hartmut Kaiser hkaiser/fall_2012/csc1254.html

Ch. 12: Operator Overloading

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

CS125 : Introduction to Computer Science. Lecture Notes #4 Type Checking, Input/Output, and Programming Style

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

5. Control Statements

Divisibility Rules and Their Explanations

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

CIS220 In Class/Lab 1: Due Sunday night at midnight. Submit all files through Canvas (25 pts)

Chapter 2: Introduction to C++

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

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

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

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

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

Introduction to C ++

Chapter 2 Basic Elements of C++

(Refer Slide Time: 02:59)

Lecture 3. Input, Output and Data Types

The Basics. chapter 2. Why You Should Read This Chapter

Lecture 4 CSE July 1992

Text Input and Conditionals

Variables and Constants

CS 115 Data Types and Arithmetic; Testing. Taken from notes by Dr. Neil Moore

CS103 Handout 29 Winter 2018 February 9, 2018 Inductive Proofwriting Checklist

Looping and Counting. Lecture 3. Hartmut Kaiser hkaiser/fall_2011/csc1254.html

How to approach a computational problem

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Fast Introduction to Object Oriented Programming and C++

Getting started with C++ (Part 2)

4. Structure of a C++ program

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Operator overloading

3. Simple Types, Variables, and Constants

MITOCW watch?v=0jljzrnhwoi

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

Chapter 1 Getting Started

C++ for Java Programmers

Visual C# Instructor s Manual Table of Contents

LECTURE 02 INTRODUCTION TO C++

2SKILL. Variables Lesson 6. Remembering numbers (and other stuff)...

T H E I N T E R A C T I V E S H E L L

Fundamentals of Programming. Lecture 3: Introduction to C Programming

CS Introduction to Data Structures How to Parse Arithmetic Expressions

Chapter 1. C++ Basics. Copyright 2010 Pearson Addison-Wesley. All rights reserved

BITG 1233: Introduction to C++

2/5/2018. Expressions are Used to Perform Calculations. ECE 220: Computer Systems & Programming. Our Class Focuses on Four Types of Operator in C

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials

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

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

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26

This watermark does not appear in the registered version - Slide 1

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

Overview (4) CPE 101 mod/reusing slides from a UW course. Assignment Statement: Review. Why Study Expressions? D-1

Lecture 1: Overview

Computer Science II Lecture 1 Introduction and Background

Annotation Annotation or block comments Provide high-level description and documentation of section of code More detail than simple comments

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

What Every Programmer Should Know About Floating-Point Arithmetic

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

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

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

Hardware versus software

Full file at

Introduction. C provides two styles of flow control:

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

Transcription:

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

Yeah, this is going to be the second slide in a lot of lectures. 2

- Dominant language for desktop application development - Most modern operating systems are written in C and C++ - Much faster than interpreted languages - Tons of library support for both C and C++ 3

- Interpreted languages are usually much slower than compiled languages - But! The difference is a lot less noticeable if the user is waiting on something (e.g., the internet) other than the processor to calculate things - Often easier to work with - Often more portable - Less drama when they crash - Web developed is almost exclusively interpreted (or bytecode compiled) languages - More secure 4

The tools we ll be using this semester. The IDE is what ties them together, but it is effectively just a wrapper for the other tools. The compiler compiles the code the text we send it into machine-readable binary code. The linker connects the function calls we make in our source code to the libraries the operating system uses, so when the computer executes our code it knows where to find the functions we call but don t describe. The debugger makes software engineering survivable. 5

Two separate things. We #include headers, this tells the compiler what functions we can call and what classes we can use. The linker connects our compiled code to the libraries that contain the machine code for the functions we call and classes we use. They are different concepts. 6

#include to include header files in our source code files. These are the two we ve used iostream (cout, endl) and string (uh, string) This is a preprocessor directive as a result, it follows different rules from other statements. Preprocessor directives are (largely) a relic left over from C; there are some others, but #include is the only one that s important for this course. 7

Will show up in all programs. Needed to prevent us from having std:: everywhere. Not to much to really think about, but make sure it s there. 8

The important scalar types we use. Slide says it all. 9

Sending output to the console. cout : console output. String literal. endl: end line 10

Big subject of the previous lecture we ll get to why this can be a serious problem later. 11

We also learned that the 70s were not a good time for fashion. 12

13

I m going to mention (and show) a few things I will describe as bad form. This is stuff that will work, but is considered (whether a loose consensus or fairly universally) to be bad form as in, stuff you just shouldn t do. 14

The boolean type. A basic type in C++. Can be true or false. Storage size is not specified by the C++ standard. 15

Literals are values embedded in the code itself. Note that these very frequently end up being magic numbers and should be avoided, but they have to be defined somewhere. (To repeat; magic numbers are values embedded in the code of a program that are not explicitly declared as constants. 0, 1, -1 and sometimes 2 do not qualify as magic numbers) 16

A number without a decimal point is an integer. A number with a decimal point is a double. Anything within double quotes is a string. A single character within single quotes is a char. The words true or false (no quotes of any type!) are literal bool values. 17

How to embed quotes in literal strings. These special sequences to represent values that would otherwise have meaning within the string (or character) are called escape sequences. The process of doing so is called escaping. Backslashes must be escaped themselves because they are used to escape other characters. 18

Result of program execution. 19

Now, we ll talk about something else important to variables converting from one type to another. We will talk about explicit conversion later, but now we ll talk about implicit conversion. This happens when we put an expression in a place where we need it to be of a different type. Scalar types have some fairly simple rules for this; objects (like strings) work very differently, but we ll cover those a good bit later in the class. 20

When you take a floating point value, and assign it to an integer, C++ performs a truncation. This strips everything past the decimal point and gives you what s left over. It does not perform rounding, only truncation. This will throw a warning in the compiler as you are losing precision anything after the decimal point is lost, so the compiler will tell you about it. Assigning an integer value to a double just puts that value in the double (or as close as it can manage!) 21

Bools work only slightly differently. If the expression evaluates to zero (integer or floating point), the boolean value is false. Otherwise, it s true. This will be very important later 22

We re going to talk a little bit about expressions. In C++, everything is an expression. There is a special type called void which does not evaluate to any value (and the compiler will tell you in no uncertain terms when you try to assign a void value to a variable), but anything that is not void (which is just about everything) evaluates to a value. This deserves to be repeated everything (well, almost) is an expression. That was one of the goals of the original C language, and C++ follows it faithfully. 23

Everybody loves this, don t they? 24

Everyone seen something like this before on the internet? Seen the huge flamewar that usually crops up? I m going to give you the answer from the engineering perspective (remember that?) for not just this one but all such problems. 25

This isn t a puzzle. This isn t a competition to show off expression parsing abilities. At the core of software engineering is the desire to maximize the clarity of expression of our ideas. Clarity of expression is something that s going to come up a lot in this class; it s a vital part of software engineering. Writing code that s difficult to read for no good reason is the epitome of poor engineering. 26

That said, we ve got to talk about order of operations in C++ a little bit. Red marked operators on the slide (increment (++), decrement(--), and assignment (=)) all have side effects they do something other than return the result. Increment (++) adds one to the variable it s attached to. Decrement (--) subtracts one from the variable it s attached to. Assignment (=) sets the variable on its left side to the value on its right side. And then returns that value Also noted above are the insertion(<<) and extraction(>>) operators, which we use a lot to send stuff to the console; their position in the list is good to know when writing expressions to the console. 27

Note the error squiggle. Comments in the slide explain this pretty well; the compiler follows the order of operation rules, and will throw an error in the second case because what it evaluates to doesn t make sense. 28

Increment/decrement unary operators. ++ increments the variable. -- decrements it. The order they appear in relation to the variable depends on how the expression evaluates if the operator is before, the operation happens before the expression s value is evaluated, if it s after the operation happens afterward. 29

Just some code to demonstrate the difference 30

And the results. 31

This does raise the question shouldn t the language be called ++C if it is an enhancement to C, as while C++ (as an expression) does increment the value of C, it evaluates to what was in C before the operation 32

This is the non-intuitive one. The assignment operator (=) can be part of an expression itself; in the above code, (a = 5) does assign the value 5 to a, but also evaluates to 5. Results follow on the next slide. 33

34

This isn t going into a long conceptual rambling, like the slides with Why on them, but we re talking about the if statement. 35

If is a conditional statement. We usually just call this a conditional (plural conditionals), as engineers typically aren t big fans of a lot of extra syllables. 36

Things to note: The if statement does not terminate with a semicolon. A block immediately follows it. If the expression inside evaluates to true, what is in the block is executed. 37

What goes in the parentheses immediately following the if is called the condition. The block (or single statement) that follows is called the body. 38

We can execute more statements within the block; everything within the block gets executed if the condition is true, nothing inside the block gets executed if it is not. 39

We can also just put a single statement after the if statement, although this is often considered to be bad form; please avoid this. 40

The compiler will warn you about this one. 41

The next step is to add the else statement to the if This lets us execute some different code if the condition is false. 42

Format of the if statement with else included. 43

Again with the bad form. While an if with a single statement body is sometimes acceptable, I m going to assert that single-statement if/else pairs are always bad form. Page 98 in your book describes the dangling else problem, which is a pretty big reason why I say single-statement if/else pairs are bad. It s worth reading, but we won t go over it in class because we re going to be using full blocks in all of our if/else pairs, so it won t matter. 44

You should have all covered the basics of ands and ors and complex conditions. They work just like normal expressions. CS 115 should have covered the basics. Most of you will take (have taken, or are taking) EE 280, which is an excellent course (taught by an excellent educator, no less) that covers an awful lot about boolean mathematics, and it applies pretty directly to computer science. 45

That said, you should understand what this means... What I will talk about, though 46

We have mentioned this concept. What does it actually mean? 47

The condition in an if statement gets converted to a bool value; it always gets converted to either true or false using the implicit conversion rules for bools mentioned earlier (to recap: numerically equal to zero (integer or floating point)? False. Anything else? True.). This combines with assignment being a normal operator that can be evaluated as a normal expression to allow some pretty vicious mistakes to happen. 48

Explanation of the evaluation process in the first example. This is the simplest case; the expression directly evaluates to a bool value, so no more conversion has to happen. 49

This is an example of implicit conversion to bool the expression evaluates to a numeric value, and that value is compared to zero. Since it s not zero, it gets converted to true. 50

And here we have the problem! In almost all of these cases, the programmer meant to have a comparison (==) operator instead of an assignment (=) operator. But the assignment operator is part of a legitimate expression which evaluates to a legitimate integer value which can then be implicitly converted to a bool value. Which is all perfectly valid C++ -- but almost never what the programmer intended! 51

Just to recap 52

Now for loops. 53

The simplest loop type is the while loop. It, uh, loops while a condition is true. 54

Like if statements, while loops have a condition and body. The condition is evaluated. If false, the loop ends (note that the body is not guaranteed to be execited at all!). If true, the body is executed and then we return to the condition. 55

Output of the previous program. 56

Visual representation. The loop can be terminated at the red statement. Note that the test condition always is checked first, and there s no guarantee that the body is ever executed. 57

What do we think this is going to do? Other than make your computer seem really happy, it keeps executing the body and never stops this is an infinite loop. 58

And what does this one do? Nothing a all the condition is false at the start, so the body is never executed. 59

The next style of loop; the do/while loop. Turns out to be a subtle variant of the while loop 60

Syntax of the do/while loop. 61

It has a condition and body just like ifs and whiles. They re just in the opposite order, because (unlike the while loop) the body is always executed at least once; first the body is executed, and then the condition is tested. 62

Program output. 63

Visual description. Body executed first (and always at least once!), then the condition is tested. The loop can terminate at the test condition. 64

Another example; condition is false to start. 65

But unlike the while loop, the body still gets executed once. 66

Single statement loops are bad form. Don t write them. 67

And now, the big one the for loop. Most programmers prefer to use for loops because of their versitility. 68

A basic for loop. 69

And its output. 70

The parts of the for loop: - The initializer gets executed (and is always executed) at the start of the loop. As you can see here, you can declare variables here. - The condition is much like the other conditions; it is tested before the first execution of the body (like a while loop, a for loop is not guaranteed to execute the body!), and at each iteration of the loop. - The increment gets executed after the body and before the condition is tested during each iteration. 71

Visual description. Initializer is executed first, always, and only once. Then the condition is tested the loop ends if the condition is false. Then the body is executed. Then the increment is executed. Then we go back to the condition. 72

The sub-statements within a for are optional, but it s bad form to not use them (unless you have a good reason not to). This will be discussed more when we get to scope 73

Here s an example of a for loop working from 10 to 1; note that the increment step uses the decrement operator (--). Yes, we still call it the increment step in this case. 74

Here s the output. Note! While we used the same numbers (0 and 10) as the forward loop, in the forward loop, we printed out 0 through 9, here we printed out 10 through 1. Why the difference? Because we need to be careful with our conditions; if we use greater than/less than (>/<; as opposed to >=/<=), the loop will never get to the last value. i > 0 is false when i gets to zero, so we don t execute the body of the loop with i equal to zero. If we wanted the loop to do something at i equal to zero, this would be an off by one error it s what happens when you write code that stops one iteration before you want it to (or starts one iteration late!). It s an easy mistake to make be careful to have the correct comparison operator in your conditions! 75

And a recap and comparison of the three loop types. 76