Chapter 7 Arithmetic

Similar documents
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

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

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

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

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

Objectives. In this chapter, you will:

Lecture 3 Tao Wang 1

Basic Operations jgrasp debugger Writing Programs & Checkstyle

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

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

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.

Expressions, Input, Output and Data Type Conversions

Full file at

Building Java Programs

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

Expressions and Casting

Building Java Programs

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

Building Java Programs

Type Conversion. and. Statements

Chapter 2: Overview of C++

Class 2: Variables and Memory. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

Operators. Lecture 3 COP 3014 Spring January 16, 2018

UNIT- 3 Introduction to C++

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

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

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

CSI33 Data Structures

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

Slide 1 CS 170 Java Programming 1 Expressions Duration: 00:00:41 Advance mode: Auto

CHAPTER 3 Expressions, Functions, Output

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

download instant at Introduction to C++

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

The C++ Language. Arizona State University 1

Chapter 3. Numeric Types, Expressions, and Output

CS102: Variables and Expressions

Elementary Programming

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

Program Fundamentals

Reserved Words and Identifiers

1. In C++, reserved words are the same as predefined identifiers. a. True

Computer System and programming in C

Operations, Basic Functions, and Game Math

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

Chapter 2: Introduction to C++

Topic 2: C++ Programming fundamentals

Main Memory Organization

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

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

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

Topic 4 Expressions and variables

Information Science 1

WARM UP LESSONS BARE BASICS

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Arithmetic Expressions in C

Chapter 2. Elementary Programming

Chapter 2: Using Data

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

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

Creating a C++ Program

Java Programming Fundamentals. Visit for more.

Chapter 7. Additional Control Structures

Outline. Data and Operations. Data Types. Integral Types

1. C++ Overview. C++ Program Structure. Data Types. Assignment Statements. Input/Output Operations. Arithmetic Expressions.

Chapter 3 Problem Solving and the Computer

What we will do today Explain and look at examples of. Programs that examine data. Data types. Topic 4. variables. expressions. assignment statements

JAVA Programming Fundamentals

QUIZ: What value is stored in a after this

Basics of Java Programming

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

Homework #3 CS2255 Fall 2012

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

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

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

BASIC ELEMENTS OF A COMPUTER PROGRAM

LECTURE 3 C++ Basics Part 2

Primitive Data, Variables, and Expressions; Simple Conditional Execution

CEN 414 Java Programming

Chapter 4: Basic C Operators

Java Notes. 10th ICSE. Saravanan Ganesh

A First Program - Greeting.cpp

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

Chapter 3 Structure of a C Program

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

ENGINEERING 1020 Introduction to Computer Programming M A Y 2 6, R E Z A S H A H I D I

Chapter 2 Elementary Programming. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.

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

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

Chapter 2. C++ Basics

LECTURE 02 INTRODUCTION TO C++

Chapter 2 Basic Elements of C++

Lecture 2: Operations and Data Types

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

Module 2 Introducing Data Types and Operators

Transcription:

Chapter 7 Arithmetic 7-1

Arithmetic in C++ Arithmetic expressions are made up of constants, variables, operators and parentheses. The arithmetic operators in C++ are as follows + (addition) - (subtraction) * (multiplication) / (division) % (modulus - the remainder from integer division) NOTE: The % operator may appear ONLY with integer operands. When expressions are evaluated, they are evaluated left to right according to the following precedence rules: ( ) * / % + - The expression 4 + 8 / 2 is evaluated as follows: 4 + 8 / 2 = (division has the highest precedence) 4 + 4 = 8 The expression (4 + 8) / 2 is evaluated as follows: (4 + 8) / 2 = (parentheses have the highest precedence) 12 / 2 = 6 7-2

The expression 10 % 3 is evaluated as follows: 10 % 3 = 1 (the integer remainder), and 10 / 3 = 3 (the integer quotient) 3 (10 / 3) 3 10 9 1 (10 % 3) The expression 8 % 3.0 would be invalid (3.0 is a floating point value and therefore not valid), as would the expression 8.0 % 3. 7-3

A program to calculate the smallest number of quarters, dimes, nickels, and pennies to give for a desired amount of change would be an appropriate application of the modulus operator. Fill in the flowchart for this algorithm using variables called amount (input), quarters, dimes, nickels, and pennies (calculated and output). Perform a desk check with the following input values: 87 and 68 7-4

When both of the operands are integers, the expression is said to be an integer expression, integer arithmetic is performed and the result is an integer. When both of the operands are floats, the expression is said to be a float expression, floating point arithmetic is performed and the result is a floating point number. If an expression contains both integers and floating point values, the expression is said to be a mixed expression, floating point arithmetic is performed and the result is a floating point number. Evaluate the following expressions. 1) 14 / 3 * 5 = 2) 10 % 3 6 / 2 = 3) 5.0 * 2.0 / 4.0 * 2.0 = 4) 5.0 * 2.0 / (4.0 * 2.0) = 5) 5.0 + 2.0 / (4.0 * 2.0) = 6) 4 + 4 / 8 = 7-5

Assignment of Mixed Expressions Recall that we are using two different data types to represent numeric values, int and float. These two data types require different amounts of memory and the values are stored in different manners. In other words, the integer 6 is stored differently than the floating point value 6.0. When we combine integer and floating point values in the same expression this is called mixed mode arithmetic. One way to place a value into a variable is by using the assignment statement. Recall the general form for an assignment statement variable = expression; Given the declarations int num1; int num2; float result; num1 and num2 may hold integer values only and result will hold a floating point value. What happens if the following assignment statements appear in a program? num1 = 3; num2 = 7.75; result = (num1 + num2) / 2.0; The value 3 is a valid integer and is stored in location num1. The value 7.75 is a floating point value so C++ simply truncates (cuts off) the fractional part and stores the integer value 7 in location num2. NOTE: The value is not rounded. The calculation for the average adds the two integer values 3 and 7 and divides the result by the floating point value 2.0. The result is the floating point value 5.0. This automatic conversion performed by the compiler (storing 7 in num2 rather than 7.75) is called type coercion. 7-6

Consider the following: num1 = 3; num2 = 7.75; result = (num1 + num2) / 20; The result is the integer value 0. The integer values 3 and 7 are added then divided by the integer value 20. The integer quotient is 0 and is stored in the variable result (the 0 is coerced to 0.0). To obtain the desired value the expression must contain a floating point value. Write the expression as follows result = (num1 + num2) / 20.0; to store the floating point value 0.5 in the variable result. Be very careful with mixed mode arithmetic. We will examine another method for dealing with this problem later. 7-7

Exercises in C++ Arithmetic Expressions What value is stored into the integer variable (num) after each of the following expressions has been evaluated? 1) num = 17 % 3; 2) num = 8 / 3 + 2; 3) num = 6.0 / 12.0 + 5.25; 4. num = 3.75 + 5 * 2; For each of the following indicate whether the expression is valid or invalid. If the expression is valid, indicate whether the result is integer or floating point. 1) 10.0 / 3.0 + 5 * 2 2) 10 / 4 + 6 / 3 3) 10 % 4 + 6 % 3 4) (10.0 / 3.0 % 2) / 3 5. 13.25 + (5.0 (3.0 / 3.5)) 6. -4 * (-5 + 6) 7-8

Assignment Statements and Type Coercion Assignment statements become a little tricky. When examining assignment statements, we will break the process into two parts 1) evaluate the expression on the right side of the assignment operator 2) apply any type coercion based on the data type of the variable on the left side of the assignment operator (=) float n1; float n2; float n3; float n4; int n5; int n6; n1 = 3.2; n2 = 2.0; n3 = 0.4; Evaluate each of the following (show the final value assigned): a) n5 = n1 / n2 * 3 + n3; b) n4 = 5 / 10 * n1; c) n6 = n1 * n3; 7-9

Assignment Statements and Type Casting We defined type coercion as the implicit conversion from one data type to another done by the compiler. Consider the following int age1; int age2; float avgage; age1 = 5; age2 = 6; avgage = (age1 + age2) / 2; In the above statement, all of the operands are of type int. The expression would evaluate as follows (5 + 6) / 2 = 11/2 = 5 Type coercion would take place and the value 5.0 stored in variable avgage. One solution is to divide by the floating point literal constant 2.0. Another approach is to use type casting. Type Casting - the explicit conversion from one data type to another done by the programmer. The statement avgage = float(age1 + age2) / 2; would add the values age1 and age2, convert them to the floating point value 11.0 then perform the division producing the desired result 5.5. avgage = float(age1 + age2) / 2; avgage = (age1 + age2) / float(2); avgage = (age1 + age2) / 2.0; avgage = float( (age1 + age2) / 2 ); // valid // valid // valid // invalid result - why? 7-10

Formula Conversion Worksheet Convert each of the following to proper C++ format. a + b cd p = [s(s-a)(s-b)(s-c)] 2 i - (n (m + c)) 7-11

Simple Sequence Problems These problems deal with the control/logic structure simple sequence and require only cin, cout and the assignment statement. Complete the structure chart, variable list and flowchart for each of the following problems. When it is time to transfer the flowcharts to an actual C++ program be sure to review Chapters 4 and 5. It is important that you adhere to the style required for this course. 1.) Design a program to calculate the average gasoline consumption for a trip. Assign the following values to variables: 15.25 gallons for fill up 1, 12.5 gallons for fill up 2 and 18.75 gallons for fill up 3. The odometer read 10,575 when you left on your trip and 11,363 when you arrived at your destination. Output the average miles per gallon for this trip. Note: This program requires only assignment statements and cout. This program is not interactive. 2.) Make the necessary changes to the program from question 1 to make it interactive. 3.) Design a program to obtain from the user, an annual interest rate, the term of the loan (in years) and the amount of money borrowed. Your program is to calculate and output the monthly payment on this loan using the following formula: rate(1 + rate) term monthlypmt = --------------------------- x loanamt (1 + rate) term 1 Use the following values to test your program. Loan Amount 120000.00 Interest Rate 7.0 Term (years) 30 It is necessary to convert the formula to C++ format. You will recall that there is no exponentiation operator available in C++. We will use a function called pow() for this purpose. GENERAL FORM for pow(x,y) function pow(x,y) where x and y are integer or float values This function returns the result x raised to the power y. Example: pow(3,2) returns the value 9 pow(4,0.5) returns the value 2 7-12

A value-returning function returns a single value. This value may be returned to a variable or an expression. Examples: float result; result = pow(3,2); or or cout << 3 to the power of 2 is << pow(3,2); result = 10 + pow(4,0.5); Write the C++ formula to calculate the payment here. 7-13

Review (Ch. 3-7) Vocabulary: identifier - variable - named constant - literal constant - data type - assignment statement - assignment operator - cin - cout - statement separator - list and define the 3 control/logic structures - 7-14

Basic C++ Concepts Review 1. Given the following: 1. void main(void) 2. { 3. const float DENOM = 2.0; 4. int num1; 5. int num2; 6. float average; 7. 8. cout << "Enter first value: "; 9. cin >> num1; 10. cout << "Enter second value: "; 11. cin >> num2; 12. average = (num1 + num2) / DENOM; 13. cout << "\nthe average is " << average; 14. } num1, num2, main, int, and DENOM are all examples of. num1 is a of type. DENOM in line 12 is an example of a of type. "Enter first value: " in line 8 is an example of a of type and is used to the user for input. The statement on line 12 is called a(n). The ; is used in C++ to. The = in line 12 is called the. >> is called the and is used with a statement and << is called the and is used with a statement. (num1 + num2) / DENOM in line 12 is called an. 7-15

Given the following: int n1, n2; float n3, n4; Show the value stored in the variable after each of the following: a) n4 = 4 / 5 * 1.5; b) n1 = 4 % 5 * 1.5; c) n2 = 1.5 * 3 + 0.4; "a" is an example of a literal constant of type char. T/F For each data type listed below, give an example of a literal constant, the declaration of a variable of that type, and the declaration of a named constant of that type. int float char c-string literal constant variable declaration named constant declaration 7-16

Program Design Process Review Step 1. Make a list of all the necessary variables and named constants for the program. Step 2: Read the program description and identify the control/logic structures. Add any necessary variables you might need. Step 3. Draw the flowchart for the program. Step 4. Perform a desk check looking for any logic problems. Correct these problems before continuing. Step 5. section. Choose an appropriate data type for each variable and write the C++ declaration Recall: char somechar; char name[15]; // somechar is of data type char and may hold one // single alpha-numeric character enclosed in single // quotes ('A', 'x', '!' etc.) // name is of data "type" c-string and may hold multiple // characters enclosed in double quotes. Variable name // may hold 14 characters with the 15th character being // the null terminator (\0). Other examples of cstrings // include "Hello world", "Enter first value", etc. Step 6. Write this program using the following as a guide. FOLLOW YOUR FLOWCHART EXACTLY. Any logic errors should have been found and corrected in step 4. - preprocessor directives - documentation (name, class section, assignment name, due date) - heading for the main function - declaration section - input section - processing section - output section 7-17

C++ Basics T/F T/F The statement const int DAY = 5; is an example of an assignment statement The statement average = (val1 + val2) / 2.0; is an example of an assignment statement Given the following: const char NAME[4] = "Joe"; int num1; char thech; char is a NAME is a of type num1 is a of type int is a "Joe" is a of type 4 is of type thech is a of type Label each of the following as valid or invalid. If invalid, explain why. thech = 'x'; thech = "a"; thech = '5'; thech = c; 7-18

Arithmetic Expressions Given two int locations called n1 and n2, and two float locations called n3 and n4, show the value stored after each of the following expressions has been evaluated. n3 = pow(4, 1/2); n1 = 2.5 + 3.4; n1 = 5 / 8; n2 = 5 % 8; n3 = 3 / 6; n4 = 3.0 / 6.0; n3 = 3 % 6.0; n4 = pow(4, 1/2.0); is the implicit conversion from one data type to another done by the compiler. is the explicit conversion from one data type to another done by the programmer. 7-19

Name Due Date Remaining Balance Homework DO NOT WORK ON THIS ASSIGNMENT WITH ANOTHER STUDENT Suppose you have purchased a car, home etc. You want to keep track of the remaining balance you owe after each monthly payment. Use the calculation for the monthly payment (7-12) in this program. The formula for this remaining balance calculation is as follows: 1 - (1 + i) k-n bal k = pmt ----------------- i where, bal k = balance remaining after kth payment k = payment number (1, 2, 3,...) pmt = amount of the monthly payment i = interest rate per month n = total number of payments Use the following user interface: Original Loan Amount: Monthly Payment: Annual Interest Rate: Term of Loan (Years): Show Balance After Payment #: Balance After Payment # $: (calculated balance displayed here) Flowchart and code the above program. Be sure to use meaningful identifier names (not i, n k etc.) and make any necessary modifications to the user input. We know from the payment program we did in class that the monthly payment on a $120,000 loan at 7% interest for 30 years is $798.36. Using this information, run your program three times and obtain the balance after one year (12th payment), ten years (120th payment), and twenty years. A sample run should look as shown on the next page - use this result to check your program. Be sure your user interface and output look EXACTLY as shown below. Your program will be graded accordingly. 7-20

Original Loan Amount: 120000.00 Monthly Payment: 798.36 Annual Interest Rate: 7.0 Term of Loan (Years): 30 Show Balance After Payment #: 12 Balance After Payment # 12 $: 118780.92 Refer to the style guide in Chapter 5 of the shrink wrap. You are responsible for the style shown. Turn in IN THIS ORDER - this sheet - flowchart (template or software) - listing of the code - 3 runs of your program using data provided STAPLE IN THE UPPER LEFT CORNER 7-21

Name Due Date Remaining Balance Homework EXTRA CREDIT DO NOT WORK ON THIS ASSIGNMENT WITH ANOTHER STUDENT Add the necessary calculations to produce the following output: Original Loan Amount: 120000 Monthly Payment: 798.36 Annual Interest Rate: 7.0 Term of Loan (Years): 30 Show Balance After Payment #: 360 Remaining Balance: $ 0.00 Total Paid to Date: $ 287409.59 Interest Paid To Date: $ 167409.59 Amount Applied to Principle:$ 120000.00 TURN THIS IN AS A SEPARATE ASSIGNMENT - DO NOT COMBINE IT WITH THE BASIC ASSIGNMENT. RUN THIS PROGRAM TWICE. ONCE USING THE DATA PROVIDED ABOVE AND AGAIN USING THE SAME LOAN AMOUNT BUT SHOWING THE BALANCE AFTER PAYMENT #180. Turn in (IN THOS ORDER): - this sheet - flowchart - listing of the code - listing of the output (2 sample runs) 7-22