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

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

Chapter 3 Objects, Types, and Values

Chapter 3 Objects, types, and values. Bjarne Stroustrup

Types, Values, Variables & Assignment. EECS 211 Winter 2018

Computer Science II Lecture 2 Strings, Vectors and Recursion

Working with Strings. Lecture 2. Hartmut Kaiser. hkaiser/spring_2015/csc1254.html

Working with Batches of Data

Programmazione. Prof. Marco Bertini

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

LECTURE 02 INTRODUCTION TO C++

CS302 - Data Structures using C++

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

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

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

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

Your first C++ program

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

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

CS242 COMPUTER PROGRAMMING

CSE 303: Concepts and Tools for Software Development

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

Introduction to Programming using C++

Console input 26/09/2018. Background. Background

Computer Science II Lecture 1 Introduction and Background

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

Pointers, Arrays and C-Strings

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

Exercise 1.1 Hello world

Chapter 4 Computation

Integer Data Types. Data Type. Data Types. int, short int, long int

A First Program - Greeting.cpp

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

Input And Output of C++

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

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

Scientific Computing

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

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

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

Chapter 2: Introduction to C++

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

2 nd Week Lecture Notes

Cours de C++ Introduction

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

6.096 Introduction to C++ January (IAP) 2009

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

Variables and Constants

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

Name Section: M/W or T/TH. True or False (14 Points)

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

CS 376b Computer Vision

Distributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes

Basic Types, Variables, Literals, Constants

Lecture 2 Tao Wang 1

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

! A literal represents a constant value used in a. ! Numbers: 0, 34, , -1.8e12, etc. ! Characters: 'A', 'z', '!', '5', etc.

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O

Computational Physics Operating systems

Exercise 3 Logical Operators, Branching, Loops. Informatik I für Mathematiker und Physiker (HS 2015) Yeara Kozlov

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

Variables and Functions. ROBOTC Software

Computer Programming : C++

C++ basics Getting started with, and Data Types.

CSc Introduction to Computing

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

PIC 10A Objects/Classes

pointers + memory double x; string a; int x; main overhead int y; main overhead

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

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

C++ Programming Lecture 1 Software Engineering Group

Physics 234: Computational Physics

download instant at Introduction to C++

C++ Lab 03 - C++ Functions

Numbers. John Perry. Spring 2017

8. The C++ language, 1. Programming and Algorithms II Degree in Bioinformatics Fall 2017

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

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

Introduction to C++ (Extensions to C)

Solving a 2D Maze. const int WIDTH = 10; const int HEIGHT = 10;

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

Informatik I (D-ITET) Übungsstunde 9, Hossein Shafagh

The C++ Language. Arizona State University 1

Computing and Statistical Data Analysis Lecture 3

CSCI 135 Software Design and Analysis, C++ Homework 8 Solution

CSCI-1200 Data Structures Spring 2013 Lecture 1 Introduction to C++, STL, & Strings

Overview. Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and arrays. Initialization Searching

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

Chapter 15 - C++ As A "Better C"

Input and Output. Data Processing Course, I. Hrivnacova, IPN Orsay

Chapter 2: Basic Elements of C++

CE221 Programming in C++ Part 1 Introduction

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

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

Lexical Structure (Chapter 3, JLS)

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

6. Pointers, Structs, and Arrays. 1. Juli 2011

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

Variables. Data Types.

6. Control Statements II

REVIEW. The C++ Programming Language. CS 151 Review #2

Transcription:

Looping and Counting Lecture 3 Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/fall_2012/csc1254.html

Abstract First we ll discuss types and type safety. Then we will modify the program we developed last time (Framing a Name) to make it more flexible. We will touch on arithmetic expressions, looping constructs and conditions. In addition we will talk about loop invariants and counting.

Types C++ provides a set of types E.g. bool, char, int, double Called built-in types C++ programmers can define new types Called user-defined types We'll get to that eventually The C++ standard library provides a set of types E.g. string, vector, complex Technically, these are user-defined types they are built using only facilities available to every user

Types and Literals Built-in types Boolean type bool Character types char Integer types int and short and long Floating-point types double and float Standard-library types std::string std::complex<scalar> Boolean literals true, false Character literals 'a', 'x', '4', '\n', '$' Integer literals 0, 1, 123, -6, 0x34, 0xa3 Floating point literals 1.2, 13.345,.3, -0.54, 1.2e3F, 3F,.3F String literals: "asdf", "Howdy, all y'all!" Complex literals std::complex<double>(12.3,99) std:: complex<float>(1.3f)

Types and Value Ranges int short long double float char string 4 bytes: -2 31 +2 31-1 2 bytes: -2 15 +2 15-1 8 bytes: -2 63 +2 63-1 8 bytes: -1.8e+308 1.8e+308, 15 digits 4 bytes: -3.4e+38 3.4e+38, 6 digits 1 byte: -2 7 +2 7-1 Arbitrary length character sequence

Types and Objects A type Defines a set of values and a set of operations (for an object) An object Is some memory that holds a value of a given type A value Is a set of bits in memory interpreted according to a type A variable Is a named object A declaration Is a statement giving a name to an object A definition Is a declaration that sets aside memory for an object

Definition and Initialization int a = 7; int b = 9; char c = 'a'; double x = 1.2; a: b: c: x: 1.2 7 9 'a' std::string s1 = "Hello"; std::string s2 = "1.2"; s1: s2: 5 "Hello" 3 "1.2"

Objects An object is some memory that can hold a value (instance) of a given type A variable is a named object A declaration names an object int a = 7; char c = 'x'; complex<double> z(1.0,2.0); string s = "qwerty"; a: c: 7 'x' z: 1.0 2.0 s: 6 "qwerty"

Type safety Language rule: type safety Every object will be used only according to its type A variable will be used only after it has been initialized Only operations defined for the variable's declared type will be applied Every operation defined for a variable leaves the variable with a valid value Ideal: static type safety A program that violates type safety will not compile The compiler reports every violation (in an ideal system) Ideal: dynamic type safety If you write a program that violates type safety it will be detected at run time Some code (typically "the run-time system") detects every violation not found by the compiler (in an ideal system)

Type safety Type safety is a very big deal Try very hard not to violate it when you program, the compiler is your best friend But it won t feel like that when it rejects code you re sure is correct C++ is not (completely) statically type safe No widely-used language is (completely) statically type safe Being completely statically type safe may interfere with your ability to express ideas C++ is not (completely) dynamically type safe Many languages are dynamically type safe Being completely dynamically type safe may interfere with the ability to express ideas and often makes generated code bigger and/or slower Most of what you ll be taught here is type safe We ll specifically mention anything that is not

The Problem Given the following interaction: Please enter your name: John We would like to print: ******************* * * * Hello John! * * * *******************

The Problem Problems with our Solution Each printed line has its own variable associated Even simple change to format requires rewrite Solution to generate each character separately No need to store strings

Overall Structure // Ask a persons name, greet the person #include <iostream> #include <string> int main() { // ask for the persons name std::cout << "Please enter your first name: "; // read into 'first_name' std::string first_name; std::cin >> first_name; // build the message we intend to write std::string const greeting = "Hello, " + first_name + "!"; // we have to rewrite this part return 0;

Overall Structure Writing an unknown number of rows // number of blank lines surrounding greeting int const pad = 1; // total number of rows to write int const rows = pad * 2 + 3; // write 'rows' rows of output int r = 0; // invariant: we have written 'r' rows of output while (r!= rows) { //... write a row of output... std::cout << std::endl; ++r; // increment r, equivalent to r = r + 1

The while Statement The while statement while (condition) statement If condition is false, statement will not be executed If condition is true, statement will be executed once, after which condition is re-checked The statement is either a single statement or a block ({ ) of several statements

Understanding while Statements After while finished the condition must be false i.e. r == rows (because r!= rows is false) Loop invariant A property of the loop to be true each time the condition is about to be checked Write program to make sure invariant holds all the time

The Loop Invariant // invariant: we have written 'r' rows so far // write 'rows' rows of output int r = 0; // makes the invariant true // invariant: we have written 'r' rows of output while (r!= rows) { // we can assume that the invariant is true here // write a row of output, makes invariant false std::cout << std::endl; ++r; // increment r, makes invariant true again // we can conclude that the invariant is true here

Writing a Row All rows have the same length: std::string::size_type const cols = greeting.size() + (pad + 2) * 2 + 2 Writing a row: // write 'cols' columns of output std::string::size_type c = 0; // invariant: we have written 'c' columns of // output while (c!= cols) { // write one or more characters // adjust the value of c

Writing Border Characters // write 'cols' columns of output std::string::size_type c = 0; // invariant: we have written 'c' columns of // output while (c!= cols) { if (r == 0 r == rows-1 c == 0 c == cols-1) { std::cout << '*'; ++c; else { // write one or more non-border characters // adjust the value of c

The if Statement The if statement if (condition) statement1 Or if (condition) statement1 else statement2 If condition is true, statement1 will be executed, otherwise statement2 (or nothing)

Logical Operators Condition r == 0 r == rows-1 c == 0 c == cols-1 is true if either (r == 0) or (r == rows-1) or (c == 0) or (c == cols-1) is true Left associative Evaluated left to right Short cutting Evaluation stops as soon as one test is true

Writing Non-Border Characters Writing greeting is special, the rest are spaces: if (r == pad + 1 && c == (pad*2) + 1) { std::cout << greeting; c += greeting.size(); else { std::cout << ' '; ++c;

Being more concise The while statement: int r = 0; while (r!= rows) { // stuff that doesn't change value of 'r' ++r; Can be written as: for (int r = 0; r!= rows; ++r) { // stuff that doesn't change value of 'r'

The for Statement The for statement for (init-statement condition; expression) statement The for statement starts executing the init-statement (done once) The condition is evaluated before statement is executed, including the first time The statement is executed only if condition evaluated to true The expression is executed after statement

The for Statement The for Statement is equivalent to: { init-statement while (condition) { statement expression;

The for Statement

Abbreviating use of std:: Writing std:: everywhere is tedious Either use using namespace std; Imports all names from std:: into current scope But never do that in a header file! Or import individual names using std::cout; Imports std::cout from std:: into current scope Using declaration is in effect for the scope it is used in

Collapsing the Tests Reordering simplifies code: // test for greeting using std::cout; if (r == pad + 1 && c == (pad*2) + 1) { cout << greeting; c += greeting.size(); else { // test for border if (r == 0 r == rows-1 c == 0 c == cols-1) cout << '*'; else cout << ' '; ++c;

Counting We ve used: for (int r = 0; r!= rows; ++r) { // write a row What about: for (int r = 1; r <= rows; ++r) { // write a row

Counting Why counting from zero? Open range [0, n) easier to understand than closed range [1, n] Use of operator!= vs. operator<= Open range [n, m) has m-n elements Closed range [n, m] has m-n-1 elements Consider empty range: [n, n) vs. [n, n-1] Consider loop invariances What does it mean to have r [1, rows] r is the number of rows to be written? r-1 is the number of rows written?

Conclusions We have seen C++ has a rich set of operators, flexible input and output, and how to extend the core language by defining what it means to apply build-in operators to user defined types.