C++ Basics 1 CS 16: Solving Problems with Computers I Lecture #3

Similar documents
Introduc)on to C++ CS 16: Solving Problems with Computers I Lecture #2

Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2

Chapter 2. C++ Basics

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

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

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

Compiling C++ Programs Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

Lecture 3. Input and Output. Review from last week. Variable - place to store data in memory. identified by a name should be meaningful Has a type-

Fundamentals of Programming CS-110. Lecture 2

Introduction to Programming EC-105. Lecture 2

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

The C++ Language. Arizona State University 1

CS242 COMPUTER PROGRAMMING

2 nd Week Lecture Notes

BITG 1233: Introduction to C++

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

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

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

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

A First Program - Greeting.cpp

Introduction to Programming

File Input / Output Streams in C++ CS 16: Solving Problems with Computers I Lecture #9

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

Unit 3, Lesson 2 Data Types, Arithmetic,Variables, Input, Constants, & Library Functions. Mr. Dave Clausen La Cañada High School

Flow Control in C++ 1 CS 16: Solving Problems with Computers I Lecture #4

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

Chapter 1 Introduction to Computers and C++ Programming

Chapter 2: Introduction to C++

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

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

6.096 Introduction to C++ January (IAP) 2009

Getting started with C++ (Part 2)

Computer Programming : C++

C: How to Program. Week /Mar/05

Unit 3. Constants and Expressions

CSCI 123 Introduction to Programming Concepts in C++

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

File I/O CS 16: Solving Problems with Computers I Lecture #9

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 3 BASIC INSTRUCTION OF C++

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

Programming with C++ as a Second Language

Basic Data Types and Operators CS 8: Introduction to Computer Science, Winter 2019 Lecture #2

Overloading Functions & Command Line Use in C++ CS 16: Solving Problems with Computers I Lecture #6

Chapter 2 - Introduction to C Programming

Chapter 2: Overview of C++

More on Func*ons Command Line Arguments CS 16: Solving Problems with Computers I Lecture #8

COMP Primitive and Class Types. Yi Hong May 14, 2015

Design and Debug: Essen.al Concepts Numerical Conversions CS 16: Solving Problems with Computers Lecture #7

Outline. Review of Last Week II. Review of Last Week. Computer Memory. Review Variables and Memory. February 7, Data Types

Add Subtract Multiply Divide

CSc Introduction to Computing

Design and Debug: Essen.al Concepts CS 16: Solving Problems with Computers I Lecture #8

Introduction to Programming using C++

More Examples Using Functions and Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #6

Designing Loops and General Debug Pre-Defined Functions in C++ CS 16: Solving Problems with Computers I Lecture #6

More on Arrays CS 16: Solving Problems with Computers I Lecture #13

UNIT- 3 Introduction to C++

LECTURE 02 INTRODUCTION TO C++

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

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

Another Simple Program: Adding Two Integers

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

File Input/Output Streams in C++ CS 16: Solving Problems with Computers I Lecture #10

Fundamentals of Structured Programming

Programming with C++ Language

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

Ch 1. Algorithms and Basic C++ Programming

Call-by-Type Functions in C++ Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #5

Advanced Flow Control CS 16: Solving Problems with Computers I Lecture #5

Introduction to C# Applications

Programming with Arrays Intro to Pointers CS 16: Solving Problems with Computers I Lecture #11

EEE145 Computer Programming

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Creating a C++ Program

Programming. C++ Basics

Maciej Sobieraj. Lecture 1

IT 1033: Fundamentals of Programming Data types & variables

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

These are reserved words of the C language. For example int, float, if, else, for, while etc.

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

Operations. Making Things Happen

Lecture 3 Tao Wang 1

ME240 Computation for Mechanical Engineering. Lecture 4. C++ Data Types

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

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

Overview of C. Basic Data Types Constants Variables Identifiers Keywords Basic I/O

IS 0020 Program Design and Software Tools

Vectors and Pointers CS 16: Solving Problems with Computers I Lecture #13

IT 374 C# and Applications/ IT695 C# Data Structures

Flow Control in C++ Condi&onals & Loops CS 16: Solving Problems with Computers I Lecture #4

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.

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

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Linked Lists CS 16: Solving Problems with Computers I Lecture #16

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

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

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++

Character Functions & Manipulators Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10

Transcription:

C++ Basics 1 CS 16: Solving Problems with Computers I Lecture #3 Ziad Matni Dept. of Computer Science, UCSB

Announcements Homework #2 due today Please take out any staples or paper clips Lab #1 is due on Friday AT NOON! Use submit.cs Class is closed to new registrakon No more switching lab Kmes Labs at 9am, 10am, 11am, 12pm are FULL Other labs have some space leg 9/29/16 Matni, CS16, Fa16 2

Lecture Outline Variables and Assignments Input and Output Data Types and Expressions 9/29/16 Matni, CS16, Fa16 3

1-4: Program start 5: Variable declaravon 6-20: Statements 21-22: Program end cout << some string or another ; output stream statement cin >> some_variable; input stream statement stream is an en-ty where a program can either insert or extract characters cout and cin are objects defined in iostream 9/29/16 Matni, CS16, Fa16 4

Variables A variable is a symbolic reference to data The variable's name represents what informavon it contains They are called variables because the data can change while the operakons on the variable remain the same The variables a and b can take on different values, but I may always want to add them together 9/29/16 Matni, CS16, Fa16 5

Variables 96 A SCORE GRADE Variables are like buckets that can keep data You can label these buckets with a name When you reference a bucket, you use its name, not the data stored in the bucket You can re- use the buckets If two variables are of the same type, you can perform opera/ons on them 9/29/16 Matni, CS16, Fa16 6

Variables in C++ In C++, variables are placeholders for memory locavons in the CPU We can assign a value to them We can change that value stored BUT we cannot erase the memory locavon of that parvcular variable 9/29/16 Matni, CS16, Fa16 7

Types of Variables: General There are 3 properves to a variable: Variables have a name (idenkfier), a type, and a value aeached to them Integers Whole numbers Example: 122, 53, - 47 FloaVng Point Numbers with decimal points Example: 122.5, 53.001, - 47.201 Boolean Takes on one of two values: true or false There are many other types of variables Character A single alphanumeric Example: c, H, % Note the use of quotavon marks String A string of characters Example: baby, what the!@$? Note the use of quotavon marks 9/29/16 Matni, CS16, Fa16 8

Types of Variables: General There are 3 properves to a variable: Variables have a name (idenkfier), a type, and a value Generally, in most HL computer languages, there are the following types of variables: NUMBERS Either integers or real numbers (called double in C++) LETTERS Characters or strings of characters LOGICAL Takes on one of two values: true or false (called Boolean) 9/29/16 Matni, CS16, Fa16 9

About Variable Names Good variable name: indicates what data is stored inside it They should make sense to a non computer programmer Avoid generic names Example: name = Bob Roberts is not descripvve enough, but candidate_name = Bob Roberts is beeer 9/29/16 Matni, CS16, Fa16 10

About Variable Names The name of the variable is not the informakon! Example: class_size = 40 is good, but class_size_is_40 = TRUE is bad Variable names must adhere to certain rules. In C++, they MUST start with either a lewer or an underscore (_) The rest of the leeers can be alphanumerics or underscores. They cannot start with a number They cannot contain spaces or dots or other symbols 9/29/16 Matni, CS16, Fa16 11

Keywords Also called reserved words Used for specific purposes by C++ Must be used as they are defined in C++ Cannot be used as idenvfiers EXAMPLE: You cannot call a variable int or else For a list of all C++ keywords, see: hep://en.cppreference.com/w/cpp/keyword 9/29/16 Matni, CS16, Fa16 12

Declaring Variables Variables must be declared before they are used in a program! DeclaraVon syntax: Type_name Variable_1, Variable_2,... ; Examples: double average, m_score, total_score; int id_num, height, weight, age, shoesize; int points; NOTE: One type of variable is declared at a Vme 9/29/16 Matni, CS16, Fa16 13

IniValizing Variables When you declare a variable, it s not created with any value in parvcular You HAVE to inivalize variable before using them EXAMPLE: int num, doz; num = 5; doz= num + 7; num is inikalized to 5 doz is inikalized to (num + 7) C++ allows alternavve ways to inivalize variables as they are declared: int num = 5, doz = 12; OR int num(5), doz(12); 9/29/16 Matni, CS16, Fa16 14

Assignment Statements How one changes the value of a variable. total_weight = 12 * one_weight ; Note: Assignment statements always end with a semi- colon 9/29/16 Matni, CS16, Fa16 15

Assignment Statements vs. Algebraic Statements C++ syntax is NOT the same as in Algebra EXAMPLE: number = number + 3 Is an impossible statement in algebra (0 = 3?!?!?!?!!!!) In C++, it means: take the current value of number, add 3 to it, then reassign that new value to the variable number 9/29/16 Matni, CS16, Fa16 16

Assignments vs. Comparisons Variables can be assigned as: DeclaraVons e.g. a = 6, or name = Buddy CalculaVons e.g. c = a + b When variables are being compared to one another, we use different symbols a is equal to b a == b a is not equal to b a!= b a is larger than b a > b a is larger than or equal to b a >= b a is smaller that b a < b a is smaller than or equal to b a <= b Note: The outcome of these comparisons are always either true or false 17

Inputs and Outputs 9/29/16 Matni, CS16, Fa16 18

Data Streams Data stream = a sequence of data Typically in the form of characters or numbers Input stream = data for the program to use Typically originates at the keyboard, or from a file Output stream = the program s output DesVnaVon is typically the monitor, or to a file 9/29/16 Matni, CS16, Fa16 19

cout and cin Output and input stream objects very popularly used in C++ To make the definivons of cin and cout available to a program, you have to declare the statement: #include <iostream> Using direcvves like that usually includes a collecvon of defined names. To make the objects cin and cout available to our program, you have to declare the statement: using namespace std; 9/29/16 Matni, CS16, Fa16 20

Examples of Use (cout) cout << number_of_bars << " candy bars\n"; This sends two items to the monitor (display): The value of number_of_bars The quoted string of characters " candy bars\n (note the starvng space) The \n causes a new line to be started following the s in bars Note: a new inservon operator is used for each item of output Note: do not use single quotes for the strings (more on that later) 9/29/16 Matni, CS16, Fa16 21

Escape Sequences Tell the compiler to treat certain characters in a special way \ (back- slash) is the escape character Example: To create a newline in the output, we use \n as in, cout << "\n"; An alternavve (new to later versions of C++): cout << endl; Other escape sequences: \t horizontal tab character \\ backslash character \ quote character \a audible bell character For a more complete list of escape sequences in C++, see: hep://en.cppreference.com/w/cpp/language/escape 9/29/16 Matni, CS16, Fa16 22

Forma{ng Decimal Places A common requirement when displaying numbers. EXAMPLE: Consider the following statements: double price = 78.5; cout << "The price is $" << price << endl; Do you want to print it out as: The price is $78.5 The price is $78.50 The price is $7.850000e01 Likely, you want the 2 nd opvon You re going to have to DEFINE that ahead of Vme 9/29/16 Matni, CS16, Fa16 23

Forma{ng Decimal Places with cout To specify fixed point notavon, use: cout.setf(ios::fixed) To specify that the decimal point will always be shown cout.setf(ios::showpoint) To specify that n decimal places will always be shown cout.precision(n) - - - where n can be 1, 2, 3, etc EXAMPLE: double price = 78.5; cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); cout << The price is << price << endl; 9/29/16 Matni, CS16, Fa16 24

Inputs via cin cin is an input stream bringing data from the keyboard The extracvon operator (>>) removes data to be used EXAMPLE: cout << "Enter the number of bars in a package\n"; cout << " and the weight in ounces of one bar.\n"; cin >> number_of_bars; cin >> one_weight; This code prompts the user to enter data then reads 2 data items from cin The first value read is stored in number_of_bars The second value read is stored in one_weight Data entry can be separated by spaces OR by return key when entered 9/29/16 Matni, CS16, Fa16 25

Entering MulVple Data Input Items MulVple data items are best separated by spaces Data is not read unvl the Enter key is pressed This allows user to make correcvons EXAMPLE: cin >> v1 >> v2 >> v3; Requires 3 space separated values So, user might type: 34 45 12 <enter key> 9/29/16 Matni, CS16, Fa16 26

Design RecommendaVons First, prompt the user for input that is desired Use cout statements provide instrucvons cout << "Enter your age: "; cin >> age; Note: absence of a new line before using cin Why? Then, echo the input by displaying what was read This gives the user a chance to verify the data entered cout << age << " was entered." << endl; 9/29/16 Matni, CS16, Fa16 27

Data Types 9/29/16 Matni, CS16, Fa16 28

Variable Types in C++ 1. Integers int: Basic integer (whole numbers, posivve OR negavve) Usually 32 or 64 bits wide So, if it s 32 bits wide (i.e. 4 bytes), the range is - 2 31 to +2 31 Which is: - 2,147,483,648 to +2,147,483,647 You can express even larger integers using: long int and long long int You can express only posivve integers using: unsigned int 9/29/16 Matni, CS16, Fa16 29

Variable Types in C++ 2. Real (ravonal) numbers double: Numbers, posivve OR negavve Type double can be wrieen in two ways: Simple form must include a decimal point Examples: 34.1, 23.0034, 1.0, - 89.9 Alternate form: Floa-ng Point Nota-on (ScienVfic NotaVon) 3.41e1 means 34.1 3.67e17 means 367000000000000000.0 (17 digits ager 3 ) 5.89e- 6 means 0.00000589 (6 decimal places before 5 ) Number leh of e (for exponent) does not require a decimal point The exponent cannot contain a decimal point 9/29/16 Matni, CS16, Fa16 30

VariaVons on Number Types long int short int float long double (a shorter version of double ) 9/29/16 Matni, CS16, Fa16 31

char: single character Variable Types in C++ 3. Characters Can be any single character from the keyboard To declare a variable of type char: char letter; Character constants are enclosed in single quotes char letter = 'a'; 9/29/16 Matni, CS16, Fa16 32

Variable Types in C++ 4. Strings string: a collecvon of characters (a string of characters) string is a class, different from the primivve data types discussed so far. We ll discuss classes further in the course So, using strings requires the following be added to the top of your program: #include <string> To declare a variable of type string: string name = Homer Simpson ; 9/29/16 Matni, CS16, Fa16 33

Note on vs Single quotes are only used for char types Double quotes are only used for string types So, which of these is ok and which isn t? char letter1 = a ; char letter2 = b ; string town1 = Mayberry ; string town2 = Xanadu ; 9/29/16 Matni, CS16, Fa16 34

Type CompaVbiliVes General Rule: You cannot operate on differently typed variables. In general, store values in variables of the same type, so that you can operate on them later. The following is a type mismatch: int my_var; my_var = 2.99; If your compiler allows this, my_var will most likely contain the value 2, not 2.99 9/29/16 Matni, CS16, Fa16 35

int ß à double Variables of type double should not be assigned to variables of type int Example from Homework #2 Variable of type int, however, can normally be stored in variables of type double EXAMPLE: double numero; numero = 2; numero will contain 2.0 9/29/16 Matni, CS16, Fa16 36

Variable Types in C++ 5. Booleans bool: a binary value of either true (1) or false (0). You can perform LOGICAL operavons on this type: Logical OR && Logical AND Bitwise OR & Bitwise AND ^ Bitwise XOR More on these later Also, when doing comparisons, the result is a Boolean type. EXAMPLE: What will this print out?? int a = 44, b = 9; bool c; c = (a == b); cout << c; 9/29/16 Matni, CS16, Fa16 37

ArithmeVc OperaVons on Numbers ArithmeVc operators can be used with any numeric type Usual types of operavons: + - * % (for int) Usual types of operavons: + - * / (for double) Use brackets ( ) to ensure required flow of operavon An operand is a number or variable used by the operator Result of an operator depends on the types of operands If both operands are int, the result is int If one or both operands are double, the result is double 9/29/16 Matni, CS16, Fa16 38

Division of Type double Division with at least one operator of type double produces the expected results. double divisor, dividend, quotient; divisor = 3; dividend = 5; quotient = dividend / divisor; quovent will be 1.6666 Result is the same if either dividend or divisor is of type int 9/29/16 Matni, CS16, Fa16 39

Division of Type int Don t do this operavon (for serious purposes) Division between two int types, results in an int answer (see Homework #2). int divisor, dividend, quotient; divisor = 3; dividend = 5; quotient = dividend / divisor; quovent will be 1, not 1.6666 Integer division does not round the result, rather the fracvonal part is discarded! 9/29/16 Matni, CS16, Fa16 40

Modulo Operator (%) Shows you the remainder of a division between two int types int divisor, dividend, remainder; divisor = 3; dividend = 5; remainder = dividend % divisor; What value will remainder will be? 9/29/16 Matni, CS16, Fa16 41

ArithmeVc Expressions Precedence rules for operators are the same as what you used in your algebra classes Anyone remember junior high??? EXAMPLE: x + y * z ( y is mulvplied by z first) Use parentheses to force the order of operavons (recommended) EXAMPLE: (x + y) * z ( x and y are added first) 9/29/16 Matni, CS16, Fa16 42

OperaVons on Variables You should only perform operavons on same- type variables Certain operavons only work with certain variable types Examples: Say you have 6 variables: A = 1, B = 2.0, C = head, D = and shoulders, E = true, F = false Integer Double Strings Booleans Can you do the following in C++?: A + B A * B C + D A + E E && F Yes Yes Yes Yes, BUT NOT RECOMMENDED!!! Yes 9/29/16 Matni, CS16, Fa16 43

Operator Shorthands Some expressions occur so ogen that C++ contains shorthand operators for them All arithmevc operators can be used this way: count = count + 2; - - - can be wrieen as- - - count += 2; bonus = bonus * 2; - - - can be wrieen as- - - bonus *= 2; Kme = Kme / factor; - - - can be wrieen as- - - Kme /= factor; remainder = remainder % (cnt1+ cnt2); - - - can be wrieen as- - - remainder %= (cnt1 + cnt2); 9/29/16 Matni, CS16, Fa16 44

TO DOs Readings The rest of Chapter 2, of textbook Homework #3 Due on Tuesday, 10/4 Submit in class Lab #2 Prepare for it by reading the handout Made available to you by Friday evening 9/29/16 Matni, CS16, Fa16 45

9/29/16 Matni, CS16, Fa16 46