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.

Similar documents
The cin Object. cout << "Enter the length and the width of the rectangle? "; cin >> length >> width;

3.1 The cin Object. Expressions & I/O. Console Input. Example program using cin. Unit 2. Sections 2.14, , 5.1, CS 1428 Spring 2018

3.1. Chapter 3: The cin Object. Expressions and Interactivity

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

CHAPTER 3 Expressions, Functions, Output

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

Chapter 3: Expressions and Interactivity. Copyright 2012 Pearson Education, Inc. Thursday, October 9, 14

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.

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

3.1. Chapter 3: The cin Object in Program 3-1. Displaying a Prompt 8/23/2014. The cin Object

Chapter 3: Expressions and Interactivity

UNIT- 3 Introduction to C++

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

Engineering Problem Solving with C++, Etter/Ingber

Expressions, Input, Output and Data Type Conversions

Chapter 3. Numeric Types, Expressions, and Output

CS103L FALL 2017 UNIT 1: TYPES, VARIABLES,EXPRESSIONS,C++ BASICS

3.1. Chapter 3: Displaying a Prompt. Expressions and Interactivity

Chapter 2. Outline. Simple C++ Programs

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

VARIABLES & ASSIGNMENTS

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

Input and Expressions Chapter 3 Slides #4

Operators. Lecture 3 COP 3014 Spring January 16, 2018

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

1. Variables 2. Arithmetic 3. Input and output 4. Problem solving: first do it by hand 5. Strings 6. Chapter summary

Operators and Expressions:

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

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

CSCE 110 PROGRAMMING FUNDAMENTALS

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

CHAPTER 3 BASIC INSTRUCTION OF C++

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

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

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur

9/10/10. Arithmetic Operators. Today. Assigning floats to ints. Arithmetic Operators & Expressions. What do you think is the output?

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

PIC 10A. Lecture 3: More About Variables, Arithmetic, Casting, Assignment

A First Program - Greeting.cpp

Outline. Performing Computations. Outline (cont) Expressions in C. Some Expression Formats. Types for Operands

Chapter 2: Basic Elements of C++

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

Chapter 4: Basic C Operators

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

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

Operators. Java operators are classified into three categories:

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

C++ Programming Lecture 11 Functions Part I

Chapter Two: Fundamental Data Types

GO - OPERATORS. This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

Chapter 3 Structure of a C Program

2. Distinguish between a unary, a binary and a ternary operator. Give examples of C++ operators for each one of them.

C Programming

WARM UP LESSONS BARE BASICS

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

Chapter 2: Using Data

Chapter 2 Basic Elements of C++

Chapter 2: Introduction to C++

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

The C++ Language. Arizona State University 1

Arithmetic Operators. Binary Arithmetic Operators. Arithmetic Operators. A Closer Look at the / Operator. A Closer Look at the % Operator

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

Objectives. In this chapter, you will:

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A.

CIS133J. Working with Numbers in Java

Declaration and Memory

Lecture 3 Tao Wang 1

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

Section we will not cover section 2.11 feel free to read it on your own

Add Subtract Multiply Divide

Operations. Making Things Happen

Overview (4) CPE 101 mod/reusing slides from a UW course. Assignment Statement: Review. Why Study Expressions? D-1

Visual C# Instructor s Manual Table of Contents

BITG 1233: Introduction to C++

CSCI 1061U Programming Workshop 2. C++ Basics

LECTURE 3 C++ Basics Part 2

Programming with C++ as a Second Language

2 nd Week Lecture Notes

Reserved Words and Identifiers

More Programming Constructs -- Introduction

Department of Computer Science

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013

LECTURE 02 INTRODUCTION TO C++

Lecture 4 Tao Wang 1

Operators in java Operator operands.

On a 64-bit CPU. Size/Range vary by CPU model and Word size.

Expressions and Casting

Unit 3. Operators. School of Science and Technology INTRODUCTION

Data Types and Variables in C language

by Pearson Education, Inc. All Rights Reserved. 2

Introduction to Programming

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

Window s Visual Studio Output

Homework #3 CS2255 Fall 2012

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

JAVA OPERATORS GENERAL

Fundamentals of Programming CS-110. Lecture 3

Operators in C. Staff Incharge: S.Sasirekha

Transcription:

Week 2: Console I/O and Operators Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.1) CS 1428 Fall 2014 Jill Seaman 1 2.14 Arithmetic Operators An operator is a symbol that tells the computer to perform specific mathematical or logical manipulations An operand is a value used in an operation. C++ has unary, binary, and ternary operators: unary (1 operand) -5 binary (2 operands) 13-7 ternary (3 operands) exp1? exp2 : exp3 2 Unary operators: Binary operators: Arithmetic Operators SYMBOL OPERATION EXAMPLES + unary plus +10, +y - negation -5, -x SYMBOL OPERATION EXAMPLE + addition x + y - subtraction index - 1 * multiplication hours * rate / division total / count % modulus count % 3 3 Integer Division If both operands are integers, / (division) operator always performs integer division. The fractional part is lost cout << 13 / 5; // displays 2 cout << 91 / 7; // displays 13 If either operand is floating point, the result is floating point. cout << 13 / 5.0; // displays 2.6 cout << 91.0 / 7; // displays 13.0 4

Modulus % (modulus) operator computes the remainder resulting from integer division cout << 13 % 5; // displays 3 cout << 91 % 7; // displays 0 % requires integers for both operands cout << 13 % 5.0; cout << 91.0 % 7; // error // error 5 3.1 The cin Object cin: short for console input a stream object: represents the contents of the screen that are entered (typed) by the user using the keyboard. requires iostream library to be included >>: the stream extraction operator use it to read data from cin (entered via the keyboard) cin >> height; when this instruction is executed, it waits for the user to type, it reads the characters until space or enter (newline) is typed, then it stores the value in the variable. right-hand operand MUST be a variable. 6 Console Input Output a prompt (using cout) to tell the user what type of data to enter BEFORE using cin: int diameter; cout << What is the diameter of the circle? ; cin >> diameter; You can input multiple values in one statement: int x, y; cout << Enter two integers: << endl; cin >> x >> y; the user may enter them on one line (separated by a space) or on separate lines. 7 Example program using cin #include <iostream> using namespace std; int main() { int length, width, area; cout << "This program calculates the area of a "; cout << "rectangle.\n"; cout << "Enter the length and width of the rectangle "; cout << "separated by a space.\n"; cin >> length >> width; area = length * width; cout << "The area of the rectangle is " << area << endl; return 0; } output screen: This program calculates the area of a rectangle. Enter the length and width of the rectangle separated by a space. 10 20 8 The area of the rectangle is 200

3.2 Mathematical Expressions An expression is a program component that evaluates to a value. An expression can be a literal, a variable, or a combination of these using operators and parentheses. Examples: 4 num x + 5 8 * x * x 16 * x + 3 Each expression has a type, which is the data type of the result value. x * y / z 'A' -15e10 2 * (l + w) 9 Where can expressions occur? The rhs (right-hand-side) of an assignment statement: x = y * 10 / 3; y = 8; num = num + 1; aletter = 'W'; x = y; The rhs of a stream insertion operator (<<) (cout): More places we don t know about yet... cout << The pay is << hours * rate << endl; cout << num; cout << 25 / y; 10 Operator Precedence (order of operations) Which operation gets done first? answer = 1 + x + z; result = x + 5 * y; Precedence Rules specify which happens first, in this order: - (negation) * / % + - If the expression has multiple operators from the same level, they associate left to right or right to left: - (negation) Right to left * / % Left to right + - Left to right 11 Parentheses You can use parentheses to override the precedence or associativity rules: Some examples: a + b / 4 (a + b) / 4 (4 * 17) + (3 1) a (b - c) 5 + 2 * 4 10 / 2-3 8 + 12 * 2-4 4 + 17 % 2-1 6-3 * 5 / 2-1 12

Exponents There is no operator for exponentiation in C++ There IS a library function called pow y = pow(x, 3.0); // x to the third power The expression pow(x,3.0) is a call to the pow function with arguments x and 3.0. Arguments can have type double and the result is a double. If x is 2.0, then 8.0 will be stored in y. The value stored in x is not changed. #include <cmath> is required to use pow. 13 3.3 Type Conversion The computer (ALU) cannot perform operations between operands of different types. If the operands of an expression have different types, the compiler will convert one to be the type of the other This is called an implicit type conversion, or a type coercion. Usually, the operand with the lower ranking type is converted to the type of the higher one. Order of types: double float long int 14 char Type Conversion Rules 3.5 Type Casting Binary ops: convert the operand with the lower ranking type to the type of the other operand. int years; float interestrate, result;... result = years * interestrate; // years is converted to float before being multiplied Assignment ops: rhs is converted to the type of the variable on the lhs. int x, y = 4; float z = 2.7; x = 4 * z; //4 is converted to float, //then 10.8 is converted to int (10) cout << x << endl; OUTPUT: 10 15 Type casting is an explicit (or manual) type conversion. mainly used to force floating-point division y = static_cast<int>(x); // converts x to int int hits, atbats; float battingavg;... cin >> hits >> atbats; battingavg = static_cast<float>(hits)/atbats; why not:? battingavg = static_cast<int>(hits/atbats); 16

3.4 Overflow/Underflow When the value assigned to a variable is too large or small for its type. integers tend to wrap around, without warning: short testvar = 32767; cout << testvar << endl; testvar = testvar + 1; cout << testvar << endl; floating point value overflow/underflow: may or may not get a warning result may be 0 or random value // 32767, max value //-32768, min value 17 3.6 Multiple Assignment You can assign the same value to several variables in one statement: a = b = c = 12; is equivalent to: a = 12; b = 12; c = 12; 18 3.6 Combined Assignment 5.1 Increment and Decrement Assignment statements often have this form: number = number + 1; //add 1 to number total = total + x; //add x to total y = y / 2; //divide y by 2 int number = 10; number = number + 1; cout << number << endl; C/C++ offers shorthand for these: number += 1; // short for number = number+1; total -= x; // short for total = total-x; y /= 2; // short for y = y / 2; 19 C++ provides unary operators to increment and decrement. Increment operator: ++ Decrement operator: -- can be used before (prefix) or after (postfix) a variable Examples: int num = 10; num++; //equivalent to: num = num + 1; num--; // equivalent to: num = num - 1; ++num; //equivalent to: num = num + 1; --num; // equivalent to: num = num - 1; 20

Prefix vs Postfix ++ and -- operators can be used in expressions In prefix mode (++val, --val) the operator increments or decrements, then returns the value of the variable In postfix mode (val++, val--) the operator returns the value of the variable, then increments or decrements int num, val = 12; cout << val++; // cout << val; val = val+1; cout << ++val; // val = val + 1; cout << val; num = --val; // val = val - 1; num = val; num = val--; // num = val; val = val -1; 3.9 More Math Library Functions These require cmath header file These take double as input, return a double Commonly used functions: pow y = pow(x,d); returns x raised to the power d abs y = abs(x); returns absolute value of x sqrt y = sqrt(x); returns square root of x sin y = sin(x); returns the sine of x (in radians) etc. It s confusing, don t do this 21 22 3.10 Hand Tracing a Program You be the computer. Track the values of the variables as the program executes. step through and execute each statement, one-by-one record the contents of variables after each statement execution, using a hand trace chart (table) int main() { double num1, num2, num3, avg; cout << Enter first number ; cin >> num1; cout << Enter second number ; cin >> num2; cout << Enter third number ; cin >> num3; avg = num1 + num2 + num3 / 3; cout << The average is << avg << endl; } num1 num2 num3 avg???????? 10??? 10??? 10 20?? 10 20?? 10 20 30? 10 20 30 40 10 20 30 40 23