CSCI 1061U Programming Workshop 2. C++ Basics

Similar documents
Programming with C++ as a Second Language

This watermark does not appear in the registered version - Slide 1

Chapter 1. C++ Basics. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Chapter 2. Flow of Control. Copyright 2016 Pearson, Inc. All rights reserved.

Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language. Dr. Amal Khalifa. Lecture Contents:

Ch 1. Algorithms and Basic C++ Programming

CS313D: ADVANCED PROGRAMMING LANGUAGE

Fundamentals of Structured Programming

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

Chapter 2: Basic Elements of C++

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

CS110: PROGRAMMING LANGUAGE I

Introduction to Programming

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Computer Programming : C++

Chapter 2. C++ Basics

Chapter 1 Introduction to Computers and C++ Programming

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

Reserved Words and Identifiers

UNIT- 3 Introduction to C++

Programming. C++ Basics

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

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

The C++ Language. Arizona State University 1

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

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

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

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

Chapter 2: Introduction to C++

Chapter 2 Basic Elements of C++

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

Fundamental of Programming (C)

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

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.

CSI33 Data Structures

Understanding main() function Input/Output Streams

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

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

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

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

Full file at

LECTURE 02 INTRODUCTION TO C++

Fundamentals of Programming CS-110. Lecture 2

Introduction to Programming EC-105. Lecture 2

CHAPTER 3 BASIC INSTRUCTION OF C++

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

Absolute C++ Walter Savitch

BITG 1233: Introduction to C++

Creating a C++ Program

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Visual C# Instructor s Manual Table of Contents

A First Program - Greeting.cpp

Introduction to C++ (Extensions to C)

Basics of Java Programming

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.

1 Lexical Considerations

Programming with C++ Language

Decaf Language Reference Manual

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

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

Introduction to C++ Programming. Adhi Harmoko S, M.Komp

CS242 COMPUTER PROGRAMMING

Chapter 2: Overview of C++

Lecture 2 Tao Wang 1

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

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

Chapter 2: Using Data

Chapter 7. Additional Control Structures

Why Is Repetition Needed?

A Fast Review of C Essentials Part I

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

CS302 - Data Structures using C++

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

5. Selection: If and Switch Controls

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

Maciej Sobieraj. Lecture 1

Control Structures. Control Structures Conditional Statements COMPUTER PROGRAMMING. Electrical-Electronics Engineering Dept.

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

Chapter 2. Outline. Simple C++ Programs

Lexical Considerations

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++

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

CSc 10200! Introduction to Computing. Lecture 4-5 Edgardo Molina Fall 2013 City College of New York

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

Chapter 5: Loops and Files

QUIZ: What value is stored in a after this

CSCI 123 Introduction to Programming Concepts in C++

Your First C++ Program. September 1, 2010

Quiz Determine the output of the following program:

Chapter 4: Control Structures I (Selection)

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

Fundamentals of Programming

Getting started with C++ (Part 2)

Chapter 3. More Flow of Control

PART I. Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++.

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1

CS2255 HOMEWORK #1 Fall 2012

5. Control Statements

Basic Types, Variables, Literals, Constants

Transcription:

CSCI 1061U Programming Workshop 2 C++ Basics 1

Learning Objectives Introduction to C++ Origins, Object-Oriented Programming, Terms Variables, Expressions, and Assignment Statements Console Input/Output Program Style Libraries and Namespaces 2

Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 3

C++ Identifiers and Variables Identifiers (variable and function names) are case sensitive Reserved words cannot be used as an identifier E.g., it is not possible to name a variable int Variables must be declared before these can be used Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 4

Data Types Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 5

Data Types Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 6

C++11 Fixed Width Integer Types Avoids problem of variable integer sizes for different CPUs Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 7

New C++11 Types auto Deduces the type of the variable based on the expression on the right side of the assignment statement auto x = expression; More useful later when we have verbose types decltype Determines the type of the expression. In the example below, x*3.5 is a double so y is declared as a double. decltype(x*3.5) y; Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 8

Data Assignment Assignment operator (=) is used to assign value to a variable Assignment can take place during or after declaration Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 9

Data Assignment var4 = var3 * var1 * var2 * 2; L-value Must be a variable R-value Any valid expression Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 10

Assigning Data: Shorthand Notations Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 11

Data Assignment Rules Generally speaking type mismatches are not allowed Cannot place value of one type into variable of another type Special case implicit or automatic type conversions allow us to place value of one type into variable of another type Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 12

Literal Data Cannot change values during execution Called "literals" because you "literally typed" them in your program! Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 13

Escape Sequences "Extend" character set Backslash (\) preceding a character Instructs compiler: a special "escape character" is coming Following character treated as "escape sequence char Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 14

Raw String Literals Introduced with C++11 Avoids escape sequences by literally interpreting everything in parens string s = R (\t\\t\n) ; The variable s is set to the exact string \t\\t\n Useful for filenames with \ in the filepath Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 15

Constants Literal constants are "OK", but provide little meaning Use named constants instead Meaningful name to represent data Called a "declared constant" or "named constant Now use it s name wherever needed in program Added benefit: changes to value result in one fix Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 16

Arithmetic Precision Precision of Calculations VERY important consideration! Expressions in C++ might not evaluate as you d "expect"! "Highest-order operand" determines type of arithmetic "precision" performed Common pitfall! Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 17

Arithmetic Precision Examples 17 / 5 evaluates to 3 in C++! Both operands are integers Integer division is performed! 17.0 / 5 equals 3.4 in C++! Highest-order operand is "double type" Double "precision" division is performed! int intvar1 =1, intvar2=2; intvar1 / intvar2; Performs integer division! Result: 0! Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 18

Individual Arithmetic Precision Calculations done "one-by-one" 1 / 2 / 3.0 / 4 performs 3 separate divisions. Firstà 1 / 2 equals 0 Thenà 0 / 3.0 equals 0.0 Thenà 0.0 / 4 equals 0.0! So not necessarily sufficient to change just "one operand" in a large expression Must keep in mind all individual calculations that will be performed during evaluation! Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 19

Type Casting Can add ".0" to literals to force precision arithmetic, but what about variables? Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 20

Type Casting Implicit also called "Automatic" Done FOR you, automatically 17 / 5.5 This expression causes an "implicit type cast" to take place, casting the 17 à 17.0 Explicit type conversion Programmer specifies conversion with cast operator (double)17 / 5.5 Same expression as above, using explicit cast (double)myint / mydouble More typical use; cast operator on variable 21

Shorthand Operators Post increment and decrement i++; // i=i+1; k--; // k=k-1; Pre increment and decrement ++i; // i=i+1; --k; // k=k-1; Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 22

Console Input/Output cin used to read from console cout used to write to console cerr used to write to console, typically used for error messages Must include these two lines. cin, cout and cerr are defined in std namespace and are found in iostream header file. Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 23

Console Input/Output Spot the differences Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 24

Console Output Any data can be outputted to display screen Variables Constants Literals Expressions (which can include all of above) Cascading (multiple values in one cout) is allowed Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 25

Console Output Any data can be outputted to display screen Variables Constants Literals Expressions (which can include all of above) Cascading (multiple values in one cout) is allowed Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 26

String type C++ has a data type of string to store sequences of characters Not a primitive data type (more on that later) Use cin to read strings from console Up to the first space string defined in std namespace and is found in string header file. Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 27

Formatting Numbers We can explicitly tell C++ how to output numbers in our programs How many decimal places, etc. Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 28

Input Using cin Extraction operator ">>" (extraction operator) points toward where the data goes Must input "to a variable, literals are not allowed. cin >> num; Waits on-screen for keyboard entry Value entered at keyboard is "assigned" to num int x; cin >> x; cin >> "9"; Ok Error Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 29

Prompting for Input: cin and cout Always "prompt" user for input cout << "Enter number of dragons: "; cin >> numofdragons; Note no "\n" in cout. Prompt "waits" on same line for keyboard input as follows (underscore below denotes where keyboard entry is made): Enter number of dragons: Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 30

Program Style Bottom-line: Make programs easy to read and modify Comments, two methods: // Two slashes indicate entire line is to be ignored /* Delimiters indicates everything between is ignored */ Both methods commonly used Identifier naming ALL_CAPS for constants lowertoupper or parta_partb for variables Most important: MEANINGFUL NAMES! Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 31

Libraries C++ Standard Libraries #include <Library_Name> Directive to "add" contents of library file to your program Called "preprocessor directive" Executes before compiler, and simply "copies library file into your program file C++ has many libraries Input/output, math, strings, etc. Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 32

Namespaces Namespaces defined: Collection of name definitions For now: interested in namespace "std" Has all standard library definitions we need Includes entire standard library of name definitions #include <iostream> using namespace std; Can specify just the objects we want #include <iostream> using std::cout; using std::cin; 33

Summary 1 C++ is case-sensitive Use meaningful names For variables and constants Variables must be declared before use Should also be initialized Use care in numeric manipulation Precision, parentheses, order of operations #include C++ libraries as needed Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 34

Summary 2 Object cout Used for console output Object cin Used for console input Object cerr Used for error messages Use comments to aid understanding of your program Do not overcomment Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 35

CSCI 1061U Programming Workshop 2 Flow Control 36

Learning Objectives Boolean Expressions Building, Evaluating & Precedence Rules Branching Mechanisms if-else switch Nesting if-else Loops While, do-while, for Nesting loops Introduction to File Input Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 37

Flow control Branching if else elseif switch Loops for while do-while 38

Comparison Operators Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 39

Boolean Expressions Use && for Boolean AND operator Use for Boolean OR operator Use data type bool to store Boolean values Boolean expressions return either true or false true, false are predefined library consts Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 40

Branching: if-else if (<Boolean expression>) <statement>; else <statement>; Only one statement allowed in each block. if (<Boolean expression>) { <statement1>; <statement2>; } else { <statement1>; <statement2>; } Use {} block when using multiple statements. 41

Branching: if-else if (<Boolean expression>) <statement>; else <statement>; if (<Boolean expression>) { <statement1>; <statementn>; } else { <statement1>; <statementn>; } 42

Branching: if-else if-else 43

Branching: if else block is optional. if (<Boolean expression>) <statement>; 44

Nested Branch Statements It is possible to nest branching statements Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 45

Branching: switch A statement for controlling multiple branches Can do the same thing with if statements but sometimes switch is more convenient 46

Branching: switch example Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 47

Branching: switch combining cases Execution "falls thru" until break Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 48

Conditional Operator or Ternary Operator Conditional assignment Shorthand if-else syntax if (n1 > n2) max = n1; else max = n2; max = (n1 > n2)? n1 : n2; Both of these are equivalent Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 49

Loops 3 Types of loops in C++ while Most flexible No "restrictions" do-while Least flexible Always executes loop body at least once for Natural "counting" loop Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 50

while Loops Syntax Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 51

while Loop Example count = 0; while (count < 3) { cout << "Hi "; count++; } // Initialization // Loop Condition // Loop Body // Update expression Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 52

do-while Loop Syntax Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 53

do-while Loop Example count = 0; // Initialization do { cout << "Hi "; // Loop Body count++; // Update expression } while (count < 3); // Loop Condition Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 54

while vs. do-while What is the difference between while and do-while? Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 55

Comma Operator Evaluate list of expressions, returning value of the last expression Most often used in a for-loop Example: first = (first = 2, second = first + 1); first gets assigned the value 3 second gets assigned the value 3 No guarantee what order expressions will be evaluated. Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 56

for Loop Syntax A natural "counting" loop for (<Init_Action>; <Bool_Exp>; <Update_Action>) Single_Body_Statement for (<Init_Action>; <Bool_Exp>; <Update_Action>) { Multiple_Body_Statements } Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 57

for Loop Example for (count=0;count<3;count++) { cout << "Hi ";// Loop Body } How many times does loop body execute? Initialization, loop condition and update all "built into" the for-loop structure! A natural "counting" loop Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 58

Loop Pitfalls: Misplaced ; Watch the misplaced ; (semicolon) while (response!= 0); { cout << "Enter val: "; cin >> response; } Result here: INFINITE LOOP! Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 59

Loop Pitfalls: Infinite Loops Loop condition must evaluate to false at some iteration through loop, otherwise the loop will run forever Infinite loops can be desirable e.g., "Embedded Systems" An infinite loop while (1) { cout << "Hello "; } Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 60

The break and continue Statements break; Forces loop to exit immediately. continue; Skips rest of loop body Use these statements with caution to break the natural control flow of a loop Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 61

Nested Loops Any valid C++ statements can be inside body of loop This includes additional loop statements, resulting in "nested loops for (outer=0; outer<5; outer++) for (inner=7; inner>2; inner--) cout << outer << inner; Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 62

Basic File IO Reading from a text file Add at the top #include <fstream> using namespace std; You can then declare an input stream just as you would declare any other variable. ifstream inputstream; Next you must connect the inputstream variable to a text file on the disk. inputstream.open("filename.txt"); The filename.txt is the pathname to a text file or a file in the current directory Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 63

Reading from a Text File Use inputstream >> var; The result is the same as using cin >> var except the input is coming from the text file and not the keyboard When done with the file close it with inputstream.close(); Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 64

File Input Example Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 65

Precedence of Operators (1 of 4) Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 66

Precedence of Operators (2 of 4) Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 67

Precedence of Operators (3 of 4) Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 68

Precedence of Operators (4 of 4) Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 69

Precedence Examples Arithmetic before logical x + 1 > 2 x + 1 < -3 means: (x + 1) > 2 (x + 1) < -3 Short-circuit evaluation (x >= 0) && (y > 1) Be careful with increment operators! (x > 1) && (y++) Integers as boolean values All non-zero values à true Zero value à false Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 70

Strong Enum C++11 introduces strong enums or enum classes Does not act like an integer enum class Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat }; enum class Weather { Rain, Sun }; Days d = Days::Tue; Weather w = Weather::Sun; Illegal: if (d == 0) Legal: if (d == Days::Wed) Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 71

Summary 1 Boolean expressions Similar to arithmetic à results in true or false C++ branching statements if-else, switch switch statement great for menus C++ loop statements while do-while for Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 72

Summary 2 do-while loops Always execute their loop body at least once for-loop A natural "counting" loop Loops can be exited early break statement continue statement Usage restricted for style purposes Reading from a text file is similar to reading from cin Slide Credit: Copyright 2016 Pearson Inc. All rights reserved. 73

Reading Ch. 1 2 74