Chapter 3 Objects, Types, and Values

Similar documents
Chapter 3 Objects, types, and values. Bjarne Stroustrup

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

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

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

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

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

Chapter 6 Writing a Program

Review of Important Topics in CS1600. Functions Arrays C-strings

Objectives. In this chapter, you will:

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

Chapter 4 Computation

Program Fundamentals

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

Introduction to Scientific Programming with C++

CS313D: ADVANCED PROGRAMMING LANGUAGE

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

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

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

Chapter 2: Basic Elements of C++

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

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

Full file at

Fundamentals of Programming CS-110. Lecture 2

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

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

CSI33 Data Structures

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

Introduction to Programming EC-105. Lecture 2

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

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

COMP 202 Java in one week

LECTURE 02 INTRODUCTION TO C++

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

Chapter 2 Basic Elements of C++

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

The C++ Language. Arizona State University 1

Chapter 5 Errors. Bjarne Stroustrup

Chapter 2 C++ Fundamentals

Chapter 2. C++ Basics

2 nd Week Lecture Notes

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

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

Princeton University Computer Science 217: Introduction to Programming Systems The C Programming Language Part 1

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

A First Program - Greeting.cpp

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

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

CSCE 121 ENGR 112 List of Topics for Exam 1

Chapter 4. Computation. Bjarne Stroustrup.

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

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:

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

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

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

CPE Summer 2015 Exam I (150 pts) June 18, 2015

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

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

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

A Java program contains at least one class definition.

Computer Programming : C++

Introduce C# as Object Oriented programming language. Explain, tokens,

Princeton University. Computer Science 217: Introduction to Programming Systems. Data Types in C

CS242 COMPUTER PROGRAMMING

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

Today in CS161. Week #3. Learn about. Writing our First Program. See example demo programs. Data types (char, int, float) Input and Output (cin, cout)

Input And Output of C++

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

Programming. C++ Basics

Operations. Making Things Happen

Chapters 1 & 2 Programming and Programs

1 Anatomy of a Program 4

2/12/17. Goals of this Lecture. Historical context Princeton University Computer Science 217: Introduction to Programming Systems

Chapter 11 Customizing I/O

Language Reference Manual

Today in CS161. Lecture #7. Learn about. Rewrite our First Program. Create new Graphics Demos. If and else statements. Using if and else statements

Introduction to Programming Using Java (98-388)

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;

6.096 Introduction to C++ January (IAP) 2009

CSCI-1200 Data Structures Spring 2014 Lecture 5 Pointers, Arrays, Pointer Arithmetic

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

Computer Science II Lecture 1 Introduction and Background

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

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

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

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

CSCS 261 Programming Concepts Exam 1 Fall EXAM 1 VERSION 1 Fall Points. Absolutely no electronic devices may be used during this exam.

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

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

From Pseudcode Algorithms directly to C++ programs

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

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.

Managing Memory. (and low level Data Structures) Lectures 22, 23. Hartmut Kaiser.

THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

Variables and literals

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

Chapter 17 vector and Free Store

Chapter 2: Introduction to C++

BITG 1233: Introduction to C++

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

PIC 10A Objects/Classes

Transcription:

Chapter 3 Objects, Types, and Values Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/~hkaiser/fall_2010/csc1253.html Slides adapted from: Bjarne Stroustrup, Programming Principles and Practice using C++

Abstract Most programming tasks involve manipulating data. Today, we will: describe how to input and output data present the notion of a variable for holding data introduce the central notions of Type and Type Safety 2

Overview Strings and string I/O Integers and integer I/O Types and objects Type safety 3

Recap: Quizz readiness What s the minimal correct C++ program int main() {} int main() { return 0; } What are the four parts a function consists of? name, return type, parameter list, body What tools are needed to create executable code from a C++ program? compiler and linker 4

Input and output // our course header #include "../../include/std_lib_facilities.h" int main() { // read first name: cout << "Please enter your first name (followed " << "by 'enter'):\n"; string first_name; cin >> first_name; cout << "Hello, " << first_name << '!\n'; } // Note how several values can be output by a single // statement. // A statement that introduces a variable is called a // declaration. // A variable holds a value of a specified type. // The final return 0; is optional in main() // but you may need to include it to pacify your compiler 5

Sting input Demo 6

Source Files std_lib_facilities.h: Interfaces to libraries (declarations) Myfile.cpp: #include "std_lib_facilities.h" My code My data (definitions) "std_lib_facilities.h" is the header for our course 7

Input and Type We read into a variable Here, first_name A variable has a type Here, string The type of a variable determines what operations we can do on it Here, cin >> first_name; reads characters until a whitespace character is seen White space: space, tab, newline, Other types we will work with: int, double, vector 8

String input // read first and second name: int main() { cout << "please enter your first and " << "second names\n"; string first; string second; cin >> first >> second; // read two strings string name = first + ' ' + second;// concatenate them // separated by a space cout << "Hello, "<< name << '\n'; } // I left out the #include "std_lib_facilities.h" to save // space and reduce distraction. // Don't forget it in real code! // Similarly, I left out the Windows-specific keep_window_open(); 9

Integers // read name and age: int main() { cout << "please enter your first name and age\n"; string first_name; // string variable int age; // integer variable cin >> first_name >> age; // read cout << "Hello, " << first_name << " age " << age << '\n'; } 10

Integers and Strings Strings cin >> reads (until whitespace) cout << writes + concatenates += s adds the string s at end ++ is an error - is an error Integers and floating point numbers cin >> reads a number cout << writes + adds += n increments by the int n ++ increments by 1 - subtracts The type of a variable determines which operations are valid and what their meanings are for that type (that's called "overloading" or "operator overloading") 11

Names A name in a C++ program Starts with a letter, contains letters, digits, and underscores (only) x, number_of_elements, Fourier_transform, z2 Not names: 12x time$to$market main line Do not start names with underscores: _foo those are reserved for implementation and systems entities Users can't define names that are taken as keywords E.g.: int if while double 12

Names Choose meaningful names Abbreviations and acronyms can confuse people mtbf, TLA, myw, nbv Short names can be meaningful when used conventionally: x is a local variable i is a loop index Don't use overly long names Ok: partial_sum element_count staple_partition Too long: the_number_of_elements remaining_free_slots_in_the_symbol_table 13

Simple arithmetic // do a bit of very simple arithmetic: int main() { cout << "please enter a floating-point number: "; // prompt for a number double n; // floating-point variable cin >> n; cout << "n == " << n << "\nn+1 == " << n+1 // '\n' means a newline << "\nthree times n == " << 3*n << "\ntwice n == " << n+n << "\nn squared == " << n*n << "\nhalf of n == " << n/2 << "\nsquare root of n == " << sqrt(n) // library function << endl; // another name for newline } 14

A simple computation // inch to cm conversion, sentinel based iteration int main() { const double cm_per_inch = 2.54; // number of centimeters // per inch int length = 1; // length in inches while (length!= 0) // length == 0 is used to // exit the program { // a compound statement (a block) cout << "Please enter a length in inches: "; cin >> length; cout << length << "in. = " << cm_per_inch*length << "cm.\n"; } } A while-statement repeatedly executes until its condition becomes false 15

A simple computation Demo 16

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 string 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 complex<double>(12.3,99) complex<float>(1.3f) 17 If (and only if) you need more details, see the book!

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 18

Declaration and Initialization int a = 7; a: 7 int b = 9; b: 9 char c = 'a'; c: 'a' double x = 1.2; x: 1.2 string s1 = "Hello, world"; s1: 12 "Hello, world" string s2 = "1.2"; s2: 3 "1.2" 19

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" 20

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) 21

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 22

Assignment and increment // changing the value of a variable int a = 7; // a variable of type int called a // initialized to the integer value 7 a = 9; // assignment: now change a's value to 9 a = a+a; // assignment: now double a's value a += 2; // increment a's value by 2 ++a; // increment a's value (by 1) a: 7 9 18 20 21 23

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 8 bytes: -3.4e+38 3.4e+38, 6 digits 1 byte: -2 7 +2 7-1 Arbitrary length character sequence 24

A type-safety violation ( implicit narrowing ) // Beware: C++ does not prevent you from trying to put a large value // into a small variable (though a compiler may warn) int main() { a int a = 20000; char c = a; int b = c; if (a!= b) //!= means not equal cout << "oops!: " << a << "!=" << b << '\n'; else cout << "Wow! We have large characters\n"; } Try it to see what value b gets on your machine 20000 c:??? 25

A type-safety violation (Uninitialized variables) // Beware: C++ does not prevent you from trying to use a variable // before you have initialized it (though a compiler typically warns) int main() { int x; char c; double d; // value double dd = d; // x gets a random initial value // c gets a random initial value // d gets a random initial value // not every bit pattern is a valid floating-point // potential error: some implementations // can t copy invalid floating-point values cout << " x: " << x << " c: " << c << " d: " << d << '\n'; } Always initialize your variables beware: debug mode may initialize (valid exception to this rule: input variable) 26

A technical detail In memory, everything is just bits; type is what gives meaning to the bits (bits/binary) 01100001 is the int 97 is the char 'a' (bits/binary) 01000001 is the int 65 is the char 'A' (bits/binary) 00110000 is the int 48 is the char '0' char c = 'a'; cout << c; // print the value of character c, which is a int i = c; cout << i; // print the integer value of the character c, which is 97 This is just as in the real world : What does 42 mean? You don t know until you know the unit used Meters? Feet? Degrees Celsius? $s? a street number? Height in inches? 27

About Efficiency For now, don t worry about efficiency Concentrate on correctness and simplicity of code C++ is derived from C, which is a systems programming language C++ s built-in types map directly to computer main memory A char is stored in a byte An int is stored in a word A double fits in a floating-point register C++ s built-in operations map directly to machine instructions An integer + is implemented by an integer add operation An integer = is implemented by a simple copy operation C++ provides direct access to most of the facilities provided by modern hardware C++ helps users build safer, more elegant, and efficient new types and operations using built-in types and operations. E.g., string Eventually, we ll show some of how that s done 28

A bit of philosophy One of the ways that programming resembles other kinds of engineering is that it involves tradeoffs. You must have ideals, but they often conflict, so you must decide what really matters for a given program. Type safety Run-time performance Ability to run on a given platform Ability to run on multiple platforms with same results Compatibility with other code and systems Ease of construction Ease of maintenance Don't skimp on correctness or testing By default, aim for type safety and portability 29

Another simple computation // inch to cm and cm to inch conversion: int main() { const double cm_per_inch = 2.54; int val; char unit; while (cin >> val >> unit) { // keep reading if (unit == 'i') // 'i' for inch cout << val << "in == " << val*cm_per_inch << "cm\n"; else if (unit == 'c') // 'c' for cm cout << val << "cm == " << val/cm_per_inch << "in\n"; else return 0; // terminate on a bad unit, e.g. 'q' } } 30

Another simple computation Demo 31

The next lecture Will talk about expressions, statements, debugging, simple error handling, and simple rules for program construction 32