Chapter 4. Computation. Bjarne Stroustrup.

Similar documents
Chapter 4 Computation

Working with Batches of Data

Chapter 5 Errors. Bjarne Stroustrup

Abstract. Chapter 4 Computation. Overview 8/13/18. Bjarne Stroustrup Note:

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

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

Chapter 5 Errors. Hyunyoung Lee. Based on slides by Bjarne Stroustrup.

2 nd Week Lecture Notes

Boolean Algebra Boolean Algebra

Scientific Computing

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

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

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

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

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

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

Chapter 2: Overview of C++

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

5. Control Statements

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

CSCE 121 ENGR 112 List of Topics for Exam 1

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

CSCE 110 PROGRAMMING FUNDAMENTALS

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

CS242 COMPUTER PROGRAMMING

Chapter 2 C++ Fundamentals

If Control Construct

A SHORT COURSE ON C++

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

CSCI-1200 Computer Science II Fall 2008 Lecture 15 Associative Containers (Maps), Part 2

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

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

How to approach a computational problem

Chapter 2 Basic Elements of C++

Computer Programming : C++

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

CS313D: ADVANCED PROGRAMMING LANGUAGE

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

Control Structures: The IF statement!

Errors. Lecture 6. Hartmut Kaiser hkaiser/fall_2011/csc1254.html

Creating a C++ Program

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

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

Chapter 3 Objects, types, and values. Bjarne Stroustrup

Chapter 3 Objects, Types, and Values

Introduction to C++ Dr M.S. Colclough, research fellows, pgtas

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

ECE 122 Engineering Problem Solving with Java

Objectives. In this chapter, you will:

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

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

The sequence of steps to be performed in order to solve a problem by the computer is known as an algorithm.

LESSON 2 VARIABLES, OPERATORS, EXPRESSIONS, AND USER INPUT

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

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

C++ Support Classes (Data and Variables)

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

C++ Programming Lecture 1 Software Engineering Group

Lecture 5. Review from last week. Selection Statements. cin and cout directives escape sequences

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:

BASIC ELEMENTS OF A COMPUTER PROGRAM

REPETITION CONTROL STRUCTURE LOGO

Arithmetic Operators. Binary Arithmetic Operators. Arithmetic Operators. A Closer Look at the / Operator. A Closer Look at the % Operator

Abstract. Chapter 6 Writing a Program. Overview. Writing a program: Strategy. Building a program. Bjarne Stroustrup

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

1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl?

Chapter 2: Introduction to C++

Add Subtract Multiply Divide

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

Unit 7. 'while' Loops

Computer Science II Lecture 2 Strings, Vectors and Recursion

CS201 Some Important Definitions

Introduction to Programming using C++

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

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

Chapter 18 Vectors and Arrays [and more on pointers (nmm) ] Bjarne Stroustrup

Lecture 3 Tao Wang 1

Full file at

Control Structures. A program can proceed: Sequentially Selectively (branch) - making a choice Repetitively (iteratively) - looping

Maciej Sobieraj. Lecture 1

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

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Chapter 2: Basic Elements of C++

Class 2: Variables and Memory. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

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

CpSc 111 Lab 3 Integer Variables, Mathematical Operations, & Redirection

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Flow Control. CSC215 Lecture

Connecting with Computer Science, 2e. Chapter 15 Programming II

CpSc 1011 Lab 3 Integer Variables, Mathematical Operations, & Redirection

COMP322 - Introduction to C++ Lecture 01 - Introduction

Fundamentals of Programming CS-110. Lecture 2

VARIABLES & ASSIGNMENTS

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

3. Simple Types, Variables, and Constants

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

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

SORTING AND SEARCHING

Transcription:

Chapter 4 Computation Bjarne Stroustrup www.stroustrup.com/programming

Abstract Today, I ll present the basics of computation. In particular, we ll discuss expressions, how to iterate over a series of values ( iteration ), and select between two alternative actions ( selection ). I ll also show how a particular sub- computation can be named and specified separately as a function. To be able to perform more realistic computations, I will introduce the vector type to hold sequences of values. Selection, Iteration, Function, Vector 2

Overview Computation What is computable? How best to compute it? Abstractions, algorithms, heuristics, data structures Language constructs and ideas Sequential order of execution Expressions and Statements Selection Iteration Functions Vectors 3

You already know most of this Note: You know how to do arithmetic d = a+b*c You know how to select if this is true, do that; otherwise do something else You know how to iterate do this until you are finished do that 100 times You know how to do functions go ask Joe and bring back the answer hey Joe, calculate this for me and send me the answer What I will show you today is mostly just vocabulary and syntax for what you already know 4

Computation (input) data Code, often messy, often a lot of code data (output) data Input: from keyboard, files, other input devices, other programs, other parts of a program Computation what our program will do with the input to produce the output. Output: to screen, files, other output devices, other programs, other parts of a program 5

Computation Our job is to express computations Correctly Simply Efficiently One tool is called Divide and Conquer to break up big computations into many little ones Another tool is Abstraction Provide a higher-level concept that hides detail Organization of data is often the key to good code Input/output formats Protocols Data structures Note the emphasis on structure and organization You don t get good code just by writing a lot of statements 6

Language features Each programming language feature exists to express a fundamental idea For example + : addition * : multiplication if (expression( expression) statement else statement ; selection while (expression( expression) statement ; iteration f(x); function/operation We combine language features to create programs 7

Expressions // compute area: int length = 20; // the simplest expression: a literal (here, 20) // (here used to initialize a variable) int width = 40; int area = length*width; // a multiplication int average = (length+width)/2; // addition and division The usual rules of precedence apply: a*b+c/d means (a*b)+(c/d) and not a*(b+c)/d. If in doubt, parenthesize. If complicated, parenthesize. Don t write absurdly complicated expressions: a*b+c/d*(e-f/g)/h+7 // too complicated and possibly wrong Choose meaningful names. 8

Expressions Expressions are made out of operators and operands Operators specify what is to be done Operands specify the data for the operators to work with Boolean type: bool (true and false) Equality operators: = = (equal),!= (not equal) Logical operators: && (and), (or),! (not) Relational operators: < (less than), > (greater than), <=, >= Character type: char (e.g., 'a', '7',, and '@') Integer types: short, int, long arithmetic operators: +, -, *, /, % (remainder) Floating-point types: e.g., float, double (e.g., 12.45 and 1.234e3) arithmetic operators: +, -, *, / 9

Concise Operators For many binary operators, there are (roughly) equivalent more concise operators For example a += c means a = a+c a *= scale means a = a*scale ++a means a += 1 or a = a+1 Concise operators are generally better to use (clearer, express an idea more directly) 10

Warnings (nmm) Never use ++a except as an expression on its own There are some truly foul gotchas,, which are much easier to avoid than describe! These uses are fine (the second two are covered later): ++a; for (int i = 0; i < n; ++i) { while (x == 0.0 && n) { But this one gets close to the edge of a cliff! These uses are not, for reasons too nasty to describe: a = 5*(++a); Avoid even this: b = 5*(++a); 11

Warnings (nmm) a/b*c is ambiguous in mathematics, and may mean either of (a/b)*c or a/(b*c) use one of the latter forms! In C++, it means (a/b)*c The same applies to a/b/c I do not recommend using tabs ('\t( \t'), because they have a lot of ''gotchas'' and are not reliably portable They work fine for quick tests, and in a single environment But, move between systems or even applications, and they often behave differently 12

Statements A statement is an expression followed by a semicolon, or a declaration, or a control statement that determines the flow of control For example a = b; double d2 = 2.5; if (x == 2) y = 4; while (cin >> number) numbers.push_back(number); int average = (length+width)/2; return x; You may not understand all of these just now, but you will 13

Selection Sometimes we must select between alternatives For example, suppose we want to identify the larger of two values. We can do this with an if statement The syntax is if (a<b) // Note: No semicolon here max = b; else // Note: No semicolon here max = a; if (condition) statement-1 // if the condition is true, do statement-1 else statement-2 // if not, do statement-2 14

Warnings (nmm) Don't do this if (a<b) // Note: No semicolon here if (b < errval) max = b; else // Note: No semicolon here max = a; Can you see why not? Be warned the ''TRY THIS'' on page 107 is a bit of a trick question 15

Iteration (while loop) The world s first real program running on a stored-program computer (David Wheeler, Cambridge, May 6, 1949) // calculate and print a table of squares 0-99: int main() { int i = 0; while (i<100) { cout << i << '\t' << square(i) << '\n'; ++i ; // increment i } } // (No, it wasn t actually written in C++.) 16

Iteration (while loop) What it takes A loop variable (control variable); Initialize the control variable; A termination criterion; Increment the control variable; Something to do for each iteration; here: i here: int i = 0 here: if i<100 is false, terminate here: ++i here: cout << int i = 0; while (i<100) { cout << i << '\t' << square(i) << '\n'; ++i ; // increment i } 17

Iteration (for loop) Another iteration form: the for loop You can collect all the control information in one place, at the top, where it s easy to see for (int i = 0; i<100; ++i) { cout << i << '\t' << square(i) << '\n'; } That is, for (initialize( initialize; condition ; increment ) controlled statement Note: what is square(i)? 18

Functions But what was square(i)? A call of the function square() int square(int x) { return x*x; } We define a function when we want to separate a computation because it is logically separate makes the program text clearer (by naming the computation) is useful in more than one place in our program eases testing, distribution of labor, and maintenance 19

Control Flow int main() { i=0; int square(int x) { while (i<100) { } return x * x; i<100 square(i) } } i==100 20

Our function int square(int x) { return x*x; } is an example of Functions Return_type function_name ( Parameter list ) // (type name, etc.) { // use each parameter in code return some_value; // of Return_type } 21

Another Example Earlier we looked at code to find the larger of two values. Here is a function that compares the two values and returns the larger value. int max(int a, int b) // this function takes 2 parameters { if (a<b) return b; else return a; } int x = max(7, 9); // x becomes 9 int y = max(19, -27); // y becomes 19 int z = max(20, 20); // z becomes 20 22

Data for Iteration - Vector To do just about anything of interest, we need a collection of data to work on. We can store this data in a vector.. For example: // read some temperatures into a vector: int main() { vector<double> temps; // declare a vector of type double to store // temperatures lik 62.4 double temp; // a variable for a single temperature value while (cin>>temp) // cin reads a value and stores it in temp temps.push_back(temp); // store the value of temp in the vector // do something } // cin>>temp will return true until we reach the end of file or encounter // something that isn t a double: like the word end 23

Vector Vector is the most useful standard library data type a vector<t> holds an sequence of values of type T Think of a vector this way A vector named v contains 5 elements: {1, 4, 2, 3, 5}: v: size() 5 v s elements: v[0] v[1] v[2] v[3] v[4] 1 4 2 3 5 24

vector<int> v; // start off empty Vectors v: 0 v.push_back(1); // add an element with the value 1 v: 1 1 v.push_back(4); // add an element with the value 4 at end ( the back ) v: 2 1 4 v.push_back(3); // add an element with the value 3 at end ( the back ) v[0] v[1] v[2] v: 3 1 4 3 25

Vectors Once you get your data into a vector you can easily manipulate it: // compute mean (average) and median temperatures: int main() { vector<double> temps; // temperatures in Fahrenheit, e.g. 64.6 double temp; while (cin>>temp) temps.push_back(temp); // read and put into vector double sum = 0; for (int i = 0; i< temps.size(); ++i) sum += temps[i]; // sums temperatures } cout << "Mean temperature: " << sum/temps.size() << endl; sort(temps.begin(),temps.end()); cout << "Median temperature: " << temps[temps.size()/2] << endl; 26

Combining Language Features You can write many new programs by combining language features, built-in types, and user-defined types in new and interesting ways. So far, we have Variables and literals of types bool, char, int, double (subscripting) vector, push_back(), [ ] (subscripting)!=, ==, =, +, -, +=, <, &&,,! max( ), sort( ), cin>>, cout<< if, for, while You can write a lot of different programs with these language features! Let s try to use them in a slightly different way 27

// boilerplate left out Example Word List vector<string> words; string s; while (cin>>s && s!= "quit") // && means AND words.push_back(s); sort(words.begin(), words.end()); // sort the words we read for (int i=0; i<words.size(); ++i) cout<<words[i]<< "\n"; /* */ read a bunch of strings into a vector of strings, sort them into lexicographical order (alphabetical order), and print the strings from the vector to see what we have. 28

Word list Eliminate Duplicates // Note that duplicate words were printed multiple times. For // example the the the. That s tedious, let s eliminate duplicates: vector<string> words; string s; while (cin>>s && s!= "quit") words.push_back(s); sort(words.begin(), words.end()); for (int i=1; i<words.size(); ++i) if(words[i-1]==words[i]) get rid of words[i] // (pseudocode) for (int i=0; i<words.size(); ++i) cout<<words[i]<< "\n"; // there are many ways to get rid of words[i] ; many of them are messy // (that s typical). Our job as programmers is to choose a simple clean // solution given constraints time, run-time, memory. 29

Example (cont.) Eliminate Words! // Eliminate the duplicate words by copying only unique words: vector<string> words; string s; while (cin>>s && s!= "quit") words.push_back(s); sort(words.begin(), words.end()); vector<string>w2; if (0<words.size()) { // Note style { } w2.push_back(words[0]); for (int i=1; i<words.size(); ++i) if(words[i-1]!=words[i]) w2.push_back(words[i]); } cout<< "found " << words.size()-w2.size() << " duplicates\n"; for (int i=0; i<w2.size(); ++i) cout << w2[i] << "\n"; 30

Algorithm We just used a simple algorithm An algorithm is (from Google search) a a logical arithmetical or computational procedure that, if correctly applied, ensures the solution of a problem. Harper Collins a a set of rules for solving a problem in a finite number of steps, as for finding the greatest common divisor. Random House a a detailed sequence of actions to perform or accomplish some task. Named after an Iranian mathematician, Al-Khawarizmi. Technically, an algorithm must reach a result after a finite number of steps, The term is also used loosely for any sequence of actions (which may or may not terminate). Webster s We eliminated the duplicates by first sorting the vector (so that duplicates are adjacent), and then copying only strings that differ from their predecessor into another vector. 31

Ideal Basic language features and libraries should be usable in essentially arbitrary combinations. We are not too far from that ideal. If a combination of features and types make sense, it will probably work. The compiler helps by rejecting some absurdities. 32

Exercises (nmm) Warning for exercises 20 and 21 If you have the first printing of the book, you must read the errata, as the exercises have been changed to be possible under gcc 33

The next lecture How to deal with errors 34