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

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

Chapter 3 Objects, Types, and Values

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

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

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

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

LECTURE 02 INTRODUCTION TO C++

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

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

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

Chapter 2: Introduction to C++

The C++ Language. Arizona State University 1

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

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

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

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:

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

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

Programming. C++ Basics

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

CS242 COMPUTER PROGRAMMING

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

Introduction to Scientific Programming with C++

CHAPTER 3 BASIC INSTRUCTION OF C++

CSCE 110 PROGRAMMING FUNDAMENTALS

Chapter 2 C++ Fundamentals

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

A First Program - Greeting.cpp

Chapter 2. Outline. Simple C++ Programs

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

CS302 - Data Structures using C++

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:

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

6.096 Introduction to C++ January (IAP) 2009

Increment and the While. Class 15

Programming Fundamentals. With C++ Variable Declaration, Evaluation and Assignment 1

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

BITG 1233: Introduction to C++

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

Chapter 2. C++ Syntax and Semantics, and the Program Development Process. Dale/Weems 1

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

Your first C++ program

Variables. Data Types.

Creating a C++ Program

Input And Output of 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++

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

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

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

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

Fundamentals of Programming CS-110. Lecture 2

CSCI 1061U Programming Workshop 2. C++ Basics

2 nd Week Lecture Notes

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

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

COMP322 - Introduction to C++

LOGO BASIC ELEMENTS OF A COMPUTER PROGRAM

Computer Programming : C++

Chapter 2: Basic Elements of C++

CSc Introduction to Computing

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

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

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

Chapter 2. C++ Basics

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

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

C++ Quick Guide. Advertisements

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

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

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

Getting started with C++ (Part 2)

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

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

Lecture 2 Tao Wang 1

WARM UP LESSONS BARE BASICS

UNIT- 3 Introduction to C++

Objectives. In this chapter, you will:

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

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

Programmazione. Prof. Marco Bertini

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

III. Classes (Chap. 3)

C++ Programming Basics

Introduction to C++ Programming Pearson Education, Inc. All rights reserved.

Chapter 2: Overview of C++

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

Computer Science II Lecture 1 Introduction and Background

Introduction to C ++

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

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

Variables and numeric types

PIC 10A Objects/Classes

Variables and Constants

IT 1033: Fundamentals of Programming Data types & variables

Introduction to Programming EC-105. Lecture 2

Numbers. John Perry. Spring 2017

EEE145 Computer Programming

CS 31 Review Sheet. Tau Beta Pi - Boelter Basics 2. 2 Working with Decimals 2. 4 Operators 3. 6 Constants 3.

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

Transcription:

Types, Values, Variables & Assignment EECS 211 Winter 2018

2 Road map Strings and string I/O Integers and integer I/O Types and objects * Type safety * Not as in object orientation we ll get to that much later.

3 Input and output #include <iostream> #include <string> using namespace std; int main() { cout << "Please enter your name: "; string first_name; cin >> first_name; } cout << "Hello, " << first_name << '\n';

4 Using libraries #include <iostream> #include <string> Includes the I/O stream library header, which lets us refer to cin and cout to do I/O, and the string library header, which lets us use strings.

4 Using libraries #include <iostream> #include <string> Includes the I/O stream library header, which lets us refer to cin and cout to do I/O, and the string library header, which lets us use strings. using namespace std; Tells C++ to let us refer to things in the standard library without prefixing them with std::. Otherwise we d have to write std::cin.

5 Main function int main() { }. Wraps the main function of every program.

6 Input and type string first_name; cin >> first_name; We define a variable first_name to have type string This means that first_name can hold textual data The type of the variable determines what we can do with it Here, cin>>first_name; reads characters until it sees whitespace ( a word )

7 Reading multiple words int main() { cout << Please enter your first and second names:\n ; string first; string second; cin >> first >> second; string name = first + ' ' + second; } cout << "Hello, " << name << '\n'; Fine print: left out the includes and using, since every program will have those from now on

8 Syntax of cin cin >> a >> b; means the same thing as cin >> a; cin >> b;

8 Syntax of cin cin >> a >> b; means the same thing as cin >> a; cin >> b; IS THIS MAGIC?

8 Syntax of cin cin >> a >> b; means the same thing as cin >> a; cin >> b; IS THIS MAGIC? No, because cin >> a returns a reference to cin

8 Syntax of cin cin >> a >> b; means the same thing as cin >> a; cin >> b; IS THIS MAGIC? No, because cin >> a returns a reference to cin cin >> a >> b means (cin >> a) >> b

8 Syntax of cin cin >> a >> b; means the same thing as cin >> a; cin >> b; IS THIS MAGIC? No, because cin >> a returns a reference to cin cin >> a >> b means (cin >> a) >> b i.e., operator>> is left associative

8 Syntax of cin cin >> a >> b; means the same thing as cin >> a; cin >> b; IS THIS MAGIC? No, because cin >> a returns a reference to cin cin >> a >> b means (cin >> a) >> b i.e., operator>> is left associative (same deal for cout and operator<<)

9 Reading integers int main() { cout << Please enter your first name and age:\n ; string first_name; int age; cin >> first_name >> age; } cout << "Hello, " << first_name << ", age " << age << '\n';

10 Integers and numbers string s int x or double x

10 Integers and numbers string s cin >> s reads a word int x or double x cin >> x reads a number

10 Integers and numbers string s cin >> s reads a word cout << s writes int x or double x cin >> x reads a number cout << x writes

10 Integers and numbers string s cin >> s reads a word cout << s writes s1 + s2 concatenates int x or double x cin >> x reads a number cout << x writes x1 + x2 adds

10 Integers and numbers string s cin >> s reads a word cout << s writes s1 + s2 concatenates ++s is an error int x or double x cin >> x reads a number cout << x writes x1 + x2 adds ++x increments in place

10 Integers and numbers string s cin >> s reads a word cout << s writes s1 + s2 concatenates ++s is an error int x or double x cin >> x reads a number cout << x writes x1 + x2 adds ++x increments in place The type of a variable determines what operations are valid and what they mean for that type

11 Names, a/k/a identifiers A legal name in C++ starts with a letter,

11 Names, a/k/a identifiers A legal name in C++ starts with a letter, contains only letters, digits, and underscores, and

11 Names, a/k/a identifiers A legal name in C++ starts with a letter, contains only letters, digits, and underscores, and isn t a language keyword (e.g., if).

Names, a/k/a identifiers A legal name in C++ starts with a letter, contains only letters, digits, and underscores, and isn t a language keyword (e.g., if). Which of these names are illegal? Why? purple line number_of_bees jflsiejslf_ else time$to$market Fourier_transform 12x y2 11

Names, a/k/a identifiers A legal name in C++ starts with a letter, contains only letters, digits, and underscores, and isn t a language keyword (e.g., if). Which of these names are illegal? Why? purple line (space not allowed) number_of_bees jflsiejslf_ else (keyword) time$to$market (bad punctuation) Fourier_transform 12x (starts with a digit) y2 11

12 Also, don t start a name with an underscore The compiler might allow it, but technically such names are reserved for the system

13 Choose meaningful names Abbreviations and acronyms can be confusing: myw, bamf, TLA

13 Choose meaningful names Abbreviations and acronyms can be confusing: myw, bamf, TLA Very short names are meaningful only when there s a convention: x is a local variable n is an int i is a loop index

13 Choose meaningful names Abbreviations and acronyms can be confusing: myw, bamf, TLA Very short names are meaningful only when there s a convention: x is a local variable n is an int i is a loop index The length of a name should be proportional to its scope

13 Choose meaningful names Abbreviations and acronyms can be confusing: myw, bamf, TLA Very short names are meaningful only when there s a convention: x is a local variable n is an int i is a loop index The length of a name should be proportional to its scope Don t use overly long names

13 Choose meaningful names Abbreviations and acronyms can be confusing: myw, bamf, TLA Very short names are meaningful only when there s a convention: x is a local variable n is an int i is a loop index The length of a name should be proportional to its scope Don t use overly long names Good: partial_sum element_count

13 Choose meaningful names Abbreviations and acronyms can be confusing: myw, bamf, TLA Very short names are meaningful only when there s a convention: x is a local variable n is an int i is a loop index The length of a name should be proportional to its scope Don t use overly long names Good: partial_sum element_count Bad: the_number_of_elements remaining_free_slots_in_the_symbol_table

14 Simple arithmetic #include <cmath> // For sqrt. int main() { cout << "Please enter a floating-point number: "; double f; cin >> f; } cout << "f == " << f << "\nf + 1 == " << f + 1 << "\n2f == " << 2 f << "\n3f == " << 3 f << "\nf² == " << f f << "\n f == " << sqrt(f) << '\n';

15 A simple computation #include <cmath> #include <iostream> using namespace std; int main() { double r; cout << "Please enter the radius: "; cin >> r; } double c = 2 M_PI r; cout << "Circumference is " << c << '\n';

16 Types and literals type bits * literals * on current architectures

16 Types and literals type bits * literals bool 1 true, false * on current architectures stored as 8 bits

16 Types and literals type bits * literals bool 1 true, false char 8 'a', 'B', '4', '/' * on current architectures stored as 8 bits

16 Types and literals type bits * literals bool 1 true, false char 8 'a', 'B', '4', '/' int 32 or 64 0, 1, 765, -6, 0xCAFE * on current architectures stored as 8 bits

16 Types and literals type bits * literals bool 1 true, false char 8 'a', 'B', '4', '/' int 32 or 64 0, 1, 765, -6, 0xCAFE long 64 0L, 1L, 10000000000L * on current architectures stored as 8 bits

16 Types and literals type bits * literals bool 1 true, false char 8 'a', 'B', '4', '/' int 32 or 64 0, 1, 765, -6, 0xCAFE long 64 0L, 1L, 10000000000L double 64 0.0, 1.2, -0.765, -6e15 * on current architectures stored as 8 bits

16 Types and literals type bits * literals bool 1 true, false char 8 'a', 'B', '4', '/' int 32 or 64 0, 1, 765, -6, 0xCAFE long 64 0L, 1L, 10000000000L double 64 0.0, 1.2, -0.765, -6e15 string varies "Hello, world!" * on current architectures stored as 8 bits actually has type const char[], but converts automatically to string

17 Types C++ provides built-in types: bool (unsigned or signed) char (unsigned) short (unsigned) int (unsigned) long float double

17 Types C++ provides built-in types: bool (unsigned or signed) char (unsigned) short (unsigned) int (unsigned) long float double C++ programmers can define new types called user-defined types you ll learn to define your own soon

17 Types C++ provides built-in types: bool (unsigned or signed) char (unsigned) short (unsigned) int (unsigned) long float double C++ programmers can define new types called user-defined types you ll learn to define your own soon The C++ standard library (STL) provides types e.g., string, vector, complex technically these are user-defined, but they come with C++

18 Objects An object is some memory that can hold a value (of some particular type)

18 Objects An object is some memory that can hold a value (of some particular type) A variable is a named object

18 Objects An object is some memory that can hold a value (of some particular type) A variable is a named object A definition names and creates an object

18 Objects An object is some memory that can hold a value (of some particular type) A variable is a named object A definition names and creates an object A initialization fills in the initial value of a variable

19 Definition and initialization int a;

19 Definition and initialization int a; a:

19 Definition and initialization int a; a: -2340024

19 Definition and initialization int a; a: -2340024 int b = 9; b: 9

19 Definition and initialization int a; a: -2340024 int b = 9; b: 9 auto c = 'z'; // c is a char c: z

19 Definition and initialization int a; a: -2340024 int b = 9; b: 9 auto c = 'z'; // c is a char c: z double x = 6.7; x: 6.7

19 Definition and initialization int a; a: -2340024 int b = 9; b: 9 auto c = 'z'; // c is a char c: z double x = 6.7; x: 6.7 string s = "hello!"; s: 6 hello!

19 Definition and initialization int a; a: -2340024 int b = 9; b: 9 auto c = 'z'; // c is a char c: z double x = 6.7; x: 6.7 string s = "hello!"; s: 6 hello! string t; t: 0

20 Language rule: Type safety Definition: In a type safe language, objects are used only according to their types

20 Language rule: Type safety Definition: In a type safe language, objects are used only according to their types Only operations defined for an object will be applied to it A variable will be used only after it has been initialized Every operation defined for a variable leaves the variable with a valid value

20 Language rule: Type safety Definition: In a type safe language, objects are used only according to their types Only operations defined for an object will be applied to it A variable will be used only after it has been initialized 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

An operation that violates type safety will not be run The program or run-time system catches every potential violation 20 Language rule: Type safety Definition: In a type safe language, objects are used only according to their types Only operations defined for an object will be applied to it A variable will be used only after it has been initialized 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 Ideal: Dynamic type safety

21 Assignment and increment The value of a variable may change. a: int a = 7; 7

21 Assignment and increment The value of a variable may change. a: int a = 7; 7 a = 9;

21 Assignment and increment The value of a variable may change. a: int a = 7; 7 a = 9; 9

21 Assignment and increment The value of a variable may change. a: int a = 7; 7 a = 9; 9 a = a + a;

21 Assignment and increment The value of a variable may change. a: int a = 7; 7 a = 9; 9 a = a + a; 18

21 Assignment and increment The value of a variable may change. a: int a = 7; 7 a = 9; 9 a = a + a; 18 a += 2;

21 Assignment and increment The value of a variable may change. a: int a = 7; 7 a = 9; 9 a = a + a; 18 a += 2; 20

21 Assignment and increment The value of a variable may change. a: int a = 7; 7 a = 9; 9 a = a + a; 18 a += 2; 20 ++a;

21 Assignment and increment The value of a variable may change. a: int a = 7; 7 a = 9; 9 a = a + a; 18 a += 2; 20 ++a; 21

22 A type safety violation: implicit narrowing Beware! C++ does not prevent you from putting a large value into a small variable (though a compiler may warn) int main() { 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

23 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; // 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 value, and on some // implementations copying an invalid float/double is an error: double dd = d; // potential error: some implementations } // prints garbage (if you re lucky): cout << x: << x << c: << c << d: << d << \n ;

Always initialize your variables. Watch out: The debugger may initialize variables that don t get initialized when running 23 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; // 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 value, and on some // implementations copying an invalid float/double is an error: double dd = d; // potential error: some implementations } // prints garbage (if you re lucky): cout << x: << x << c: << c << d: << d << \n ;

24 A technical detail In memory, everything is just bits; type is what gives meaning to the bits: (bits/binary) 01100001 is the int 97 and also char 'a' (bits/binary) 01000001 is the int 65 and also char 'A' (bits/binary) 00110000 is the int 48 and also 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

25 A word on efficiency For now, don t worry about efficiency Concentrate on correctness and simplicity of code

25 A word on efficiency For now, don t worry about efficiency Concentrate on correctness and simplicity of code C++ is derived from C, low-level 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 ops. map directly to machine instructions + on ints is implemented by an integer add operation = on ints is implemented by a simple copy operation C++ provides direct access to most of facilities provided by modern hardware

25 A word on efficiency For now, don t worry about efficiency Concentrate on correctness and simplicity of code C++ is derived from C, low-level 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 ops. map directly to machine instructions + on ints is implemented by an integer add operation = on ints is implemented by a simple copy operation C++ provides direct access to most of facilities provided by modern hardware

26 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