Looping and Counting Lecture 3 Hartmut Kaiser

Slides:



Advertisements
Similar presentations
Slides adapted from: Bjarne Stroustrup, Programming – Principles and Practice using C++ Chapter 3 Objects, Types, and Values Hartmut Kaiser
Advertisements

CSE202: Lecture 2The Ohio State University1 Variables and C++ Data Types.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Overview of C++ Chapter 2 in both books programs from books keycode for lab: get Program 1 from web test files.
Chapter 2: Introduction to C++.
Basic Elements of C++ Chapter 2.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
CSC 125 Introduction to C++ Programming Chapter 2 Introduction to C++
CIS Computer Programming Logic
Input & Output: Console
Working with Strings Lecture 2 Hartmut Kaiser
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 3: Requirements Specification, C++ Basics.
CS2311 Computer Programming Dr. Yang, Qingxiong (with slides borrowed from Dr. Xu, Henry) Lecture 2: Basic Syntax – Part I: Variables and Constants.
CSCE 121: Introduction to Program Design and Concepts, Honors Dr. J. Michael Moore Spring 2015 Set 3: Objects, Types, and Values 1 Based on slides.
CS1 Lesson 2 Introduction to C++ CS1 Lesson 2 -- John Cole1.
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
Basic Notions Review what is a variable? value? address? memory location? what is an identifier? variable name? keyword? what is a legal identifier? what.
Chapter 1 Working with strings. Objectives Understand simple programs using character strings and the string library. Get acquainted with declarations,
CPS120: Introduction to Computer Science
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Defining New Types Lecture 21 Hartmut Kaiser
Data & Data Types & Simple Math Operation 1 Data and Data Type Standard I/O Simple Math operation.
Chapter 2. C++ Program Structure C++ program is a collection of subprograms Subprograms in C++ are called FUNCTIONS Each function performs a specific.
Week 1 Algorithmization and Programming Languages.
CSE1222: Lecture 2The Ohio State University1. mathExample2.cpp // math example #include using namespace std; int main() { cout
Loop.  While Loop  Do-while Loop  For Loop Continue Statement Conclusion Loop Loop.
Working with Batches of Data Lecture 4 Hartmut Kaiser
Chapter 3 Objects, types, and values Bjarne Stroustrup
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
VARIABLES AND DATA TYPES Chapter2:part1 1. Objectives: By the end of this section you should: Understand what the variables are and why they are used.
CSC 107 – Programming For Science. Announcements.
Introducing C++ Programming Lecture 3 Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
Computing and Statistical Data Analysis Lecture 2 Glen Cowan RHUL Physics Computing and Statistical Data Analysis Variables, types: int, float, double,
C++ / G4MICE Course Session 1 - Introduction Edit text files in a UNIX environment. Use the g++ compiler to compile a single C++ file. Understand the C++
C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
PROGRAM ESSENTIALS. TOKENS  SMALLEST UNITS OF A PROGRAM LANGUAGE  Special Symbols  Mathematical Operators  Punctuation  Word Symbols  Key Words.
General Computer Science for Engineers CISC 106 Lecture 12 James Atlas Computer and Information Sciences 08/03/2009.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
Primitive Data Types. int This is the type you are familiar with and have been using Stores an integer value (whole number) between -2,147,483,648 (-2.
1 A more complex example Write a program that sums a sequence of integers and displays the result. Assume that the first integer read specifies the number.
A Sample Program #include using namespace std; int main(void) { cout
1 ENERGY 211 / CME 211 Lecture 3 September 26, 2008.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Basic concepts of C++ Presented by Prof. Satyajit De
Chapter 1.2 Introduction to C++ Programming
Chapter Topics The Basics of a C++ Program Data Types
Chapter 1.2 Introduction to C++ Programming
CIS3931 – Intro to JAVA Lecture Note Set 2 17-May-05.
Types CSCE 314 Spring 2016.
Chapter 1.2 Introduction to C++ Programming
Computing and Statistical Data Analysis Lecture 2
Chapter 3 Objects, types, and values
Documentation Need to have documentation in all programs
Basic Elements of C++.
Working with Strings Lecture 2 Hartmut Kaiser
Chapter 3 Objects, Types, and Values
Basic Elements of C++ Chapter 2.
Chapter 3 Objects, types, and values
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Character Set Uppercase Alphabets A,
Working with Strings Lecture 2 Hartmut Kaiser
Variables T.Najah Al_Subaie Kingdom of Saudi Arabia
Introduction to C++ Programming
Chapter 2: Introduction to C++.
Chapter 3 Objects, types, and values
C++ Programming Lecture 3 C++ Basics – Part I
2. Second Step for Learning C++ Programming • Data Type • Char • Float
Chapter 1 c++ structure C++ Input / Output
Presentation transcript:

Looping and Counting Lecture 3 Hartmut Kaiser

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. 1/22/2015, Lecture 3 CSC 1254, Spring 2015, Looping and Counting 2

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 1/22/2015, Lecture 3 CSC 1254, Spring 2015, Looping and Counting 3

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  Boolean literals  true, false  Character literals  'a', 'x', '4', '\n', '$'  Integer literals  0, 1, 123, -6, 0x34, 0xa3  Floating point literals  1.2, ,.3, -0.54, 1.2e3F, 3F,.3F  String literals: "asdf", "Howdy, all y'all!"  Complex literals  std::complex (12.3,99)  std:: complex (1.3F) 1/22/2015, Lecture 3 CSC 1254, Spring 2015, Looping and Counting 4

Types and Value Ranges int short long double float char string 4 bytes: … bytes: … bytes: … bytes: -1.8e+308 … 1.8e+308, 15 digits 4 bytes: -3.4e+38 … 3.4e+38, 6 digits 1 byte: -2 7 … Arbitrary length character sequence 1/22/2015, Lecture 3 CSC 1254, Spring 2015, Looping and Counting 5

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 1/22/2015, Lecture 3 CSC 1254, Spring 2015, Looping and Counting 6

Definition and Initialization int a = 7; int b = 9; char c = 'a'; double x = 1.2; std::string s1 = "Hello"; std::string s2 = "1.2"; 1/22/2015, Lecture 3 CSC 1254, Spring 2015, Looping and Counting 'a' | "Hello" 3 | "1.2" a: b: c: x: s1: s2:

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 1/22/2015, Lecture 3 CSC 1254, Spring 2015, Looping and Counting 8 int a = 7; char c = 'x'; complex z(1.0,2.0); string s = "qwerty"; 7 a: "qwerty"6 s: 'x' c: z:

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) 1/22/2015, Lecture 3 CSC 1254, Spring 2015, Looping and Counting 9

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 1/22/2015, Lecture 3 CSC 1254, Spring 2015, Looping and Counting 10

The Problem Given the following interaction: Please enter your name: John We would like to print: ******************* * * Hello John! * * ******************* 1/22/2015, Lecture 3 CSC 1254, Spring 2015, Looping and Counting 11

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 1/22/2015, Lecture 3 CSC 1254, Spring 2015, Looping and Counting 12

Overall Structure // Ask a persons name, greet the person #include 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; } 1/22/2015, Lecture 3 CSC 1254, Spring 2015, Looping and Counting 13

Overall Structure Writing an unknown number of rows int const line_pad = 1; // number of blank lines surrounding greeting int const column_pad = 2; // number of blank columns surrounding greeting // total number of rows to write int const rows = line_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 } 1/22/2015, Lecture 3 CSC 1254, Spring 2015, Looping and Counting 14

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 1/22/2015, Lecture 3 CSC 1254, Spring 2015, Looping and Counting 15

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 1/22/2015, Lecture 3 CSC 1254, Spring 2015, Looping and Counting 16

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 1/22/2015, Lecture 3 CSC 1254, Spring 2015, Looping and Counting 17

Writing a Row All rows have the same length: std::string::size_type const cols = greeting.size() + column_pad * 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 } 1/22/2015, Lecture 3 CSC 1254, Spring 2015, Looping and Counting 18

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 } 1/22/2015, Lecture 3 CSC 1254, Spring 2015, Looping and Counting 19

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) 1/22/2015, Lecture 3 CSC 1254, Spring 2015, Looping and Counting 20

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 1/22/2015, Lecture 3 CSC 1254, Spring 2015, Looping and Counting 21

Writing Non-Border Characters Writing greeting is special, the rest are spaces: if (r == line_pad + 1 && c == column_pad + 1) { std::cout << greeting; c += greeting.size(); } else { std::cout << ' '; ++c; } 1/22/2015, Lecture 3 CSC 1254, Spring 2015, Looping and Counting 22

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' } 1/22/2015, Lecture 3 CSC 1254, Spring 2015, Looping and Counting 23

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 1/22/2015, Lecture 3 CSC 1254, Spring 2015, Looping and Counting 24

The for Statement The for Statement is equivalent to: { init-statement while (condition) { statement expression; } 1/22/2015, Lecture 3 CSC 1254, Spring 2015, Looping and Counting 25

The for Statement 1/22/2015, Lecture 3 CSC 1254, Spring 2015, Looping and Counting 26

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 1/22/2015, Lecture 3 CSC 1254, Spring 2015, Looping and Counting 27

Collapsing the Tests Reordering simplifies code: // test for greeting using std::cout; if (r == line_pad + 1 && c == column_pad + 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; } 1/22/2015, Lecture 3 CSC 1254, Spring 2015, Looping and Counting 28

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 } 1/22/2015, Lecture 3 CSC 1254, Spring 2015, Looping and Counting 29

Counting 1/22/2015, Lecture 3 CSC 1254, Spring 2015, Looping and Counting 30

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. 1/22/2015, Lecture 3 CSC 1254, Spring 2015, Looping and Counting 31