Chapter 2 - I know what I want to do NOW WHAT? Student Learning Outcomes (SLOs)

Similar documents
Chapter 1 - What s in a program?

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 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

The C++ Language. Arizona State University 1

UNIT- 3 Introduction to C++

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

Objectives. In this chapter, you will:

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

LECTURE 02 INTRODUCTION TO C++

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

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

Chapter 2. C++ Basics

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

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

Full file at

BITG 1233: Introduction to C++

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

Chapter 2: Introduction to C++

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

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

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

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

Chapter 2 Basic Elements of C++

VARIABLES & ASSIGNMENTS

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

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

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

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

Expressions, Input, Output and Data Type Conversions

Add Subtract Multiply Divide

CHAPTER 3 Expressions, Functions, Output

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

Basics of Java Programming

Fundamental of Programming (C)

Introduction to Programming using C++

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

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

Maciej Sobieraj. Lecture 1

Programming. C++ Basics

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

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

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

LECTURE 3 C++ Basics Part 2

Computer Programming : C++

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

! A literal represents a constant value used in a. ! Numbers: 0, 34, , -1.8e12, etc. ! Characters: 'A', 'z', '!', '5', etc.

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

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.

Operators. Lecture 3 COP 3014 Spring January 16, 2018

CMPT 125: Lecture 3 Data and Expressions

Engineering Problem Solving with C++, Etter/Ingber

Operators. Java operators are classified into three categories:

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

Unit 3. Constants and Expressions

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

Reserved Words and Identifiers

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

Chapter 2: Overview of C++

Chapter 2: Using Data

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

Lecture 3 Tao Wang 1

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

More Programming Constructs -- Introduction

Unit 3. Operators. School of Science and Technology INTRODUCTION

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

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

Introduction to Programming EC-105. Lecture 2

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

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

Numerical Computing in C and C++ Jamie Griffin. Semester A 2017 Lecture 2

2 nd Week Lecture Notes

CHAPTER 3 BASIC INSTRUCTION OF C++

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.

Fundamentals of Programming

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

Variables and Constants

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

Lecture 4 Tao Wang 1

Creating a C++ Program

Visual C# Instructor s Manual Table of Contents

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Full file at

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

Introduction to C++ Dr M.S. Colclough, research fellows, pgtas

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

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

Fundamentals of Programming CS-110. Lecture 2

2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants

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

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

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

C/C++ Programming for Engineers: Working with Integer Variables

6.096 Introduction to C++ January (IAP) 2009

CS102: Variables and Expressions

C: How to Program. Week /Mar/05

ARG! Language Reference Manual

Lecture 2 Tao Wang 1

Transcription:

Chapter 2 - I know what I want to do NOW WHAT? Student Learning Outcomes (SLOs) a. You should be able to list two significant characteristics for each of the basic data types (bool, int, double, and char). b. You should be able to identify the difference between string structures and characters. c. You should be able to create variables using appropriate identifiers for each of the primary data types d. You should be able to create dynamic string objects. e. You should be able to format output using <iomanip> functions (fixed, setw(), and setprecision() ). f. You should be able to use relational and logical operators to create Boolean expressions. g. You should be able to use if else to create decisions. Demonstration Program Here is a working program in C++. It was written using Microsoft s (MS) Visual Studio. It can be created using other compilers the only MS eccentricity is the use of the stdafx.h. This line can be commented out if necessary. Load and execute program 2.1. This program demonstrates the basic modules of a program input, process, and output. It also incorporates all of the necessary syntax such as include files, a main() module, liberal commenting for internal documentation. Note that the processing module incorporates a decision structure that allows the program decide between options based on data that is entered.

Blow-by-Blow Description 1. The #include statements a. Are generally used to incorporate previously created programming. Specifically they define the utilities that we are using in the program (as noted) b. <iomanip> - defines formatting features used in C++. In this case we are using setw() to create a reserved number of spaces in which we are outputting dat in the output screen. c. <cstdlib> - c standard library defines miscellaneous functions that we use. In this case it defines the system() function d. <string> - defines the dynamic, string class and its associated member functions and stand-alone functions (ie. getline() ). 2. The variable and object creation a. Input strings are preferred for data input. This is because they will accept any character entered from the keyboard (they don t crash your program. This allows you to error check the characters entered. b. The resp string is used over and over again to receive the <ENTER> requested at the bottom of each screen. We do not use resp for any other purpose. c. The numeric variables are used to receive converted data that is or will be used in calculations. Strings are only character sequences and as such do not have a combined numeric value. As you can see in the output screen we convert the number of hours worked which is entered as a string into its numeric equivalent. Then we can use the value in an arithmetic operation. 3. Splash Screen is essentially a series of output (cout) statements. The spacing is taken from the design sample below. Note that the first line is a system call system( cls ). The system() function is a handy utility that allows us to access any DOS command in this case clear screen ( cls ). At this point we are hard coding the spaces into each line. We could have created a utility to automatically center strings for us. For now this technique gets the job done. Some of the cout calls simply are used to create carriage

returns (using endl). Once again there are more elegent ways of accompishing this but this will work for now. 4. Transition to next screen is a utility that is used 3 times in this program. After its initial testing it was simply block and copied as needed. Notice that it incorporates a single output line, a getline() to acquire the user s response, and a call to the OS cls command. 5. Input Screen makes extensive use of basic input and output operations. This is the first of the standard screens in the program. All of the remaining screens will take this general format. The screen is broken into four basic areas: Project and Screen titles, user instruction/information, body of the screen (prompt and input area, and a transition to the next screen, as described in #3, above. The spacing for all of the lines was taken directly from the screen design template. Also notice that I have put the getline() after the prompt. In interactive programs the prompt-response sequence is so often used that this not uncomon practice. I do not advocate this as a general style. To C/C++ these are two independent statements note the semicolons after each. The prompts should be evident to the program user. 6. Transition to next screen is once again invoked. 7. Output Screen is where most of the action happens. a. The first part is the re-statement of the input data. This is fairly important for both the programmer and user to verify that the program is working properly. b. Conversions, decisions, and calculations as the comment suggests this is where most of the work is accomplished. i. The first operation is the conversion of the hrs_worked_str string into a character array (using.data() ) then using atof() to convert the character array into the corresponding numeric value. ii. The program has to decide which of four values to use for the pay rate. Here a nested if-else control structure is used. Note there are four possible values (options) and only three tests (if statements). This is a rule of thumb the number of tests = number of options -1. The first (outer) test is that of the first character of the

Job Status string (the character at the first position in the string, position 0). iii. The third operation is the calculation for total pay. Remember that the total pay has to be calculated before it can be output!! c. Finally there is a third use of the screen transition routine. Programming Concepts 1. Data types are the kinds of data that we can use in a program. There are two broad kinds of data: primary (atomic) data types which are built into the compiler and user-defined types where the programmer specifies the characteristics (properties) of the data (this is sometimes refered to as a complex data type). There are four primary data types that are commonly used today a. Boolean is used for TRUE / FALSE values (only). The data can not be printed or directly input it can only be used (very strange!!!). b. Character is used for single characters (assiming ASCII characters) c. Integer generally is used for whole numbers (but sometimes boolean values later!). d. Double is an expansion of the earlier float type. It is used for numbers with fractional components. The following table presents comparisons between the four data types indicated above.

Characteristic Boolean Character* Integer Double Symbol bool * char int double Memory Used** 1 byte 1 byte 4 bytes 8 bytes Range TRUE/FALSE O 255-2147483648 to +/- 1.7e +/- 308 (~15 Example A-Z, a-z, 0-9, punctuation chars Escape 2147483647-5, 0, +5 (if there is no sign, + is assumed) digits) -1.5e- 300 1.6e+305 1.234-0.00321 characters * Character constants are noted using single quotes ( A or \n ). ** Memory usage will depend on the system used. The values used here are based on a 32-bit system There are actually 9 data types however the types listed are the ones most commonly used. string is not a true data type although we use it as if it were. It is actually a class which means that it not only can contain data but it also has member functions that allow us to look at and manupulate individual characters and sets of characters within the string. The string type is dynamic. That is memory is assigned and removed as you add and delete characters within the string. 2. Identifiers are character sequences that are used to represent the location at which the data is stored. a. The identifier should be descriptive enough to help you remember the purpose of the representated data. Examples from the beginning program pay_rate, tot_pay, f_name, addr, etc. b. The identifier is made up of combinations of numeric and alpha characters and under_score ( _ ). An identifier may

not incorporate punctuation marks, spaces, or special characters. c. An identifier MAY NOT be a reserved word (keyword). d. Identifiers in C/C++ are case sensitive. For example the following are different identifiers pay_rate, pay_rate, PAY_RATE, payrate, etc. e. By convention all variables (and function identifiers) begin with a lower case character. Some programmers will use ALL upper case identifiers to represent constant values. This allows them to be picked out in a crowd. It is becoming more common for C++ programmers to use Java-like or camel case identifiers. In camel case capitol letters are used to highlight words subsequent to the first sequence. For example payrate, tothours, payratestr. It s your call just be consistant. In real-time your boss will define the required style. f. A standard variable can represent only one value at a time. String class identifiers can represent many characters. 3. Creating variables and constants the process allows the compiler to efficiently reserve memory for data and then associates the identifier with the beginning address of the reservation (allocation). a. Syntax data_type identifier; Examples of variables int counter; double balance; string addr; etc. Examples of constants int LIMIT; double TAX_RATE; etc. b. Assigning data to a variable (initialization) the first data assignment is call the initialization. It is a common practice to initialize variables immediately after their creation. c. Assignment operator executes right to left. The basic assignment operatior looks like an equal sign ( = ) but is read gets. For example the next expression - counter = 0; is read, the memory allocation represented by counter gets a zero. Or more simply we say, counter gets zero.

Write out the sentence represented by the following expressions: 1. value = 97; 2. tax_rate = 0.0825; 3. mi = E ; 4. first_name = No data ; There are a number of variations of assignment operators but the basic assignment operator will be adequate for now. i. More assignment examples: counter = 0; balance = 234.56; middleinitial = E ; Note the single quotes around the E. This indicates to the compiler that E is data not an unidentified variable. String data is indicated using double quotes. For example - addr = XXXXX ; ii. Combining variable declaration and initialization: int counter; counter = 0; These can be combined together to form int counter = 0; Another example using the string class: string fname = Edward ; d. Creating true constants you need to use the reserved word const. For example const int LIMIT = 25; const double TAX_RATE = 0.0775; The reserved word const modifies the interpretation of the variable declaration. There are other useful modifiers that may be used with specific data types (ie. unsigned, long, etc.)

Putting It Altogether The following is a scenario that incorporates the use of an IPO chart and associated story board design for a program that prompts a user for a series of numbers, calculates an average, and displays the resulting output. I understand that this is probably over-kill for this kind of program but we are talking about a concept and an approach that will be useful as the projects get more substantial. As conceived, the program is simply a series of output statememts (cout) and input statements (getline() ) that prompt and accept user input (see above). Each screen is composed of 3 parts: Project and screen titles, the body (main presentation), and transition to the next screen. IPO Input (1 st ) Process (3 rd ) Output (2 nd ) Prompt for each value ---------- Allow the user to enter the value Add each input value to a total For each value add 1 to a counter ----------- After all values are entered divide the total by the counter and assign to the average Display the average IPO chart for the calculation of the average for a series of values.

Sample Input Screen for calculating the average of a series of values. Sample Output Screen for calculating the average of a sequence of values.

So now we know the starting positions for each of the lines on each of the screens for this project. This will make the actual programming much less error prone resulting in an increase in programming efficiency (the next phase). At this point it is your turn. You may have been assigned a project or you may wish to choose one of several data base development projects at the end of this chapter. In either event your first task is to determine the basic programming modules. A good starting point is - input, process, and output. Choose the most interesting or useful project to you (or you may have been assigned one) because you will continue to develop this project through out this book. Try your hand at planning the input and output screens. You might want to add an introduction screen (splash screen). The Database Example The following sequence is a description of a process for developing the program that began the chapter. The development description is followed by programming concepts that are incorporated into the code. Often a number of techniques are presented that pertain directly to the project at hand and represent other related techniques that could be incorporated at a later time. Additionally if you want to investigate either the described techniques or related techniques, you can follow the links (references) that are provided. In the following sequence of chapters a data base design and development scenario will be followed for the creation of a database program. A number of alternate scenarios will be suggested in an appendix. Any of the scenarios can be developed in a similar manner. In real-time the data base development would probably not follow the chapter sequence. In the text we are interested in using the development of a database project as an instructional tool and also to present a number of techniques which may or may not be incorporated in a given project, as the situation would dictate.

The Database Scenario (Employee Tracking System) The purpose of the employee tracking system is to keep track of employee data including contact information, date of hire, and position. The company has two categories of employees (for our purposes) managers and sales. Additionally the company has an employment part-time status and a full-time status which are used to calculate pay rates. All data should be entered as dynamic strings (covered in the next chapter) and converted (as necessary) into numeric equivalents. The following data items will be required for each employee: Employee Number (key field) unique values Last Name First Name Address Zip Code Job Position (M/S) Job Status (F/P) Hours Worked Job Position and Job Status will be used to determine the pay rate of the individual employee. The pay rate will be multiplied by the number of hours worked to determine the total pay for this pay period. The pay rates are determined as indicated in the table below. The measure is in dollars per hour. Job Status Job Position Manager Sales Full Time 27.50 17.00 Part Time 19.75 10.50 At this point we are expected to generate an IPO chart, a splash screen design, input screen design, and an output screen design. <The following link displays examples of these documents.>

Input (1 st ) Process (3 rd ) Output (2 nd ) Employee Number Last Name First Name Address Zip Job Position Job Status Hours Worked (no processing) (no processing) (no processing) (no processing) (no processing) (no processing) (no processing) (no processing) Employee Number Last Name First Name Address Zip Job Position Job Status Hours Worked Hours worked * Pay rate Pay for the period IPO Chart for the Employee Tracking System. Figure 4. Sample Splash Screen for the Employee Tracking System.

Figure5. Sample input screen for the Employee Tracking System. Figure 3. Sample output screen for the Employee Tracking System.

Programming/design considerations and Tips 1. IPO chart make sure all input data is listed in the input column; all expected outcomes for this module are indicated in the output column; and all processes are indicated in the process column. 2. Screen design For this project you should be designing for a text screen with 25 rows and 80 characters (columns) in each row. Remember the computer screens are painted from the upper left corner to the lower right corner, one row at a time (at this point no going back). a. Splash Screen try to use the whole screen. In the design template a single character can be in a cell of the worksheet. To quickly figure the center position (assuming a 80-character column) subtract the number of characters in your string from 80. Then divide the result by 2. If rounding is required, it does not really matter if you round up or down just be consistent. DO NOT bunch all of the presentation in the upper left corner of the screen. Include the project title, the developer(s), and other pertinent information. Provide a prompt for the user. b. Input Screen this is the first of the standardized screens. The necessary components are project title, screen title, user instructions, main presentation, user -prompt to continue. In this case the instructions appear after the screen title is printed in anticipation of the data prompts. It is not a good idea to automatically transition to the next screen after the last data item input. c. Output Screen is essentially the same as the input screen. This will be the same for all subsequent screens. The pay will be a result of multiplying the hours worked and the pay rate. The pay rate will be determined using nested ifelse structures (discussed in the next chapter). 3. Programming program in units. a. Pre- splash screen Do all of the #include files, using namespace, and create all of the strings for input and anticipated numeric variables. Remember the strings and variables are at the top of the programming block. Comment at

least the beginning and end of each program section and all ending braces ( } ). b. Splash screen - Create the code (programming) for the splash screen. Make sure it works (compiles and runs). Include the transition code so you can see your results. Make sure you comment the beginning and ending of the splash screen code. This will help in the next chapter. c. Input Screen Be sure to once again comment the beginning and ending of this program section. Code the project and screen titles and the transition code to the next screen, based on the spacing indicated on the screen design. Make sure that this works (it won t look just exactly right but you have not created any instructions and prompts). Now we are ready to code the instructions and input statements. Each prompt is paired with an input statement. These are technically two separate lines of code but you often see them on the same physical line. Using your spacing chart create the prompts inserting as many blank spaces after the opening quote and the first letter as necessary to get the proper indent. Be sure to close the quotes and end with a semi-colon. For example: cout << Enter the Last Name: ; Now the getline(). Note that it incorporates the standard (default) input device and the string object into which you will be saving the data. Now to complete the line: cout << Enter the Last Name: ; getline(cin, last_name); Basically repeat this for each of the input strings. d. Output Screen Comment as before and code the titles and transition first keeping an eye on the screen design diagram. Then code the data that is to be directly output (no processing) based on the spacing in the screen design. Then finally code the conversions, decisions, calculations and output. Now we need to calculate the total pay. What do we need? The hours worked (in numeric format) and the hourly pay rate.

There is no specified order to determine these but both must be determined before we calculate total pay. Now for some new information strings have two aspects (similar to standard data) there are dynamic strings (which has been described) and static strings. Static strings are actually character arrays (a later discussion). The importance at this point is that they are an older data structure than dynamic strings. This is the kind of string that C dealt with in the beginning of time. We are going to use a C utility to convert a string into its numeric equivalent atof(). So we will need to convert our dynamic string into a static string, and finally into a number. atof() is a utility that converts a static string into a double ( in olden times a float atof means ASCII (characters) to float). So we use the hours worked string for this and the sequence is hrs_worked_str.data() converts the dynamic string into a static string atof(hrs_worked_str.data()) converts the static string into the corresponding number For the pay rate we have to make some decisions because we have some choices. Looking at the Job Position and Status chart above, we notice that there are 4 possible values that could be used. To do this we can use if else control structures. The if else control structure introduces us to the basic syntax that is used in 4 out of the 5 control structures that we will use building the program. Please refer to Boolean operations and control structures for information about Boolean expressions (relationships). Boolean expressions are used to generate the TRUE and FALSE values to implement control structures.

if else control structure Syntax diagram: if(condition) { TRUE statements; } else { FALSE statements; } Notice in the syntax there are TRUE statements and FALSE statements. This really means statements that are executed if the condition (a Boolean expression) results in a TRUE value and statements that are executed if the condition results in a FALSE value. Each part of the if else control structure assumes a single line of code. If a single line of code is to be executed, the open and close brace can be eliminated. So assuming there are single executable lines for each option the structure could be reduced to

if(condition) TRUE statement; else FALSE statement; An example: string response = XXXX ; cout << Enter Yes or No and press <ENTER> ; getline(cin, response); if( response == Yes ) { } else { } cout << You responded with ; cout << YES << endl; cout << You did not respond with ; cout << YES << endl; Or we could have said if(response == Yes ) cout << You responded with YES << endl; else cout << You did not respond with YES << endl; OK this gets us past deciding between two values how about four of them??? (Have I got a deal for you!!!) We can nest structures inside of structures. That is we can put an if else structure inside of another if-else structure - in either or both of the result options. For example:

if (condition1) if(condition2) Statement for conditions 1 and 2 being TRUE; else Statement for condition1 being TRUE and condition2 being FALSE; else if(condition2) Statement for condition1 being TRUE; else Statement for conditions 1 and 2 being FALSE; Be careful because indenting has NO effect on the paring of the if and else statements. Work inside out. The first inside if will pair with the first else. When in doubt you can use braces to resolve pairing issues. Now we are getting to our program example. Remember we had four possible options for the pay rate based on two values the Job Position and the Job Status. I simply picked one of the two pieces of data because they are independent. I used Job Position for the outside if-else. The Job Status became the nested if-else. if(j_pos.at(0) == 'M') if(j_stat.at(0) == 'F') else else pay_rate = 27.50; pay_rate = 19.75; if(j_stat.at(0) = 'F') pay_rate = 17.00; else pay_rate = 10.50; Look closely at the conditions I used another string member function,.at(). This allows me to look at a single character in the string. I know that ALL strings start at position 0. So I decided that I could just look at the first character of the string to decide what the user entered. Basically I don t care what else they typed in. So to read this nested if else if the character at position 0 of j_pos (Job Position) the same as the character M (manager). Note the single quotes for a single character (what would the quotes be if I were testing the whole word?). If that is TRUE then

if the character at position 0 of j_stat (Job Status) is the same as the character F (full-time) then pay_rate is assigned 27.50. Otherwise pay_rate is assigned 19.75 (manager; part time). Now the else portion of if(j_pos.at(0) == 'M'). Once again we see the same test for j_stat as above. So this decision would be resolved if j_pos.at(0) is not M that is to say sales. So now we have our two values required for the calculation (pay rate and hourly pay). All that is required is to multiply the two together and assign the result to a variable for future use (displaying). Arithmetic Operations Arithmetic operations are essentially the same as for algebra and math in general. Arithmetic operators like relational and logical operators are typically binary operators (requiring an operand on the left and to the right of the operator). Typically they will return the data type of the most complex operand. In this case both operands are double so the type of variable to assign the result is typically going to be a double. To assign the result to a less complex data type (say an int) may cause the truncation (not rounding) of everything to the right of the decimal (possible loss of data). So the data type of tot_pay is double in the program above. As you build your own programs, be sure to consider the consequences of data types. Generally there are three categories of operators: unary, binary, and tertiary. Arithmetic operators fall into the first two. Unary operators - Negation uses the dash for example -5. This is a unary operator because it only requires a single value after the operator. This symbol is overloaded for the binary subtraction operation. Binary operators- addition - uses + operator, i.e. 54 + 34. It is a binary operator because a value is required before and after the operator subtraction - uses - operator, i.e. 54-34

multiplication - uses * operator, i.e. 54 * 34 division - uses / operator, i.e. 54.0 / 34.1. If the operands are both integers, an integer will be returned (the whole number component of the result); if either of the operands is a double, a double is returned. modulus - uses % operator, i.e. 7%2. This returns the "remainder after the division occurs, in this case the result is 1. Program example: #include < iostream.h > using namespace std; int main(void) { } cout<<"7 + 2 = " << (7+2)< < '\n'; cout<<"7-2 = "<<(7-2)< < '\n'; cout<<"7 / 2 = "<<(7/2)< < endl; cout<<"7 % 2 = "<<(7%2)< < endl; cout<<"7.0 / 2 = "< <(7.0/2)< < endl; What does the endl do?? Order of precedence

Precedence Operation Operator Type Result type Associativity 1 unary - - unary 2 multiplication * binary 2 division / binary double or integer double or integer double or integer right to left left to right left to right 2 modulus % binary integer left to right 3 addition + binary 3 subtraction - binary double or integer double or integer left to right left to right Counters vs Accumulators For convenience addition operations are sometimes put into two categories counters and accumulators. Counting operations occur when the same value is being added to the total each time the expression is executed. For example: counter = counter +1; Note that even though this looks like an algebra expression, this is a series of commands to the computer. Remembering that the assignment operator works right to left, we resolve the part on the right side of the assignment operator then assign the result to the variable (object) to the left, the expression is read, access the value associated with counter in memory, add

one to it (this completes the operations on the right side) then assign the result to the memory allocation associated with counter. So practically speaking we say, counter gets counter plus 1. Accumulators are similar to counters except that a different value could be assigned to the expression each time it is executed. For example: total = total + number; is read, total gets (the value in the memory location associated with) total plus (the value in the memory location associated with) number. Or more directly total gets total plus number. These concepts can be rolled to all of the other arithmetic operations. More examples 1. balance = balance + transaction; 2. balance = balance +(balance * interest_rate); 3. average = total_of_values / numb_of_values; Now back to our program, the arithmetic operation that we use to calculate the employee s total pay is as follows: tot_pay = hrs_worked * pay_rate; This is read, tot_pay gets (the result of) hrs_worked multiplied by the pay_rate. Now it is your turn. Create arithmetic expressions for the following scenarios. Be sure to use parentheses as appropriate.

1. Add one to the contents of an integer variable. 2. Multiply the contents of a variable containing a tax rate (double) by a variable containing an income amount (double). 3. Add two separate income variables (doubles) and multiply the result by a tax rate (double). Now it is time to refer to back to the output screen design. We can use cout statements to output any or all of our derived (determined) values hrs_worked, pay_rate, and tot_pay with appropriate descriptive phrases. Output Formatting- Formatting output in C++ is called output manipulation. In fact it is formatting which means we are changing the appearance rather that the value (contents) of variables (objects). To do this we use the <iomanip> header file. Refer back to the starting program and look at the include files. Along with <iostream> and <string>, the <iomanip> header is one of the files we include as a rule. There are a number of useful formatting utilities included in the <iomanip> header file but the big three are fixed, setwidth(), and setprecision(). setwidth() specifies a fixed field width within which a value will be output. An integer is inserted in the parentheses. The number specifies the field width (in characters). The default is to set the output to the right side of the field, which can be modified. setprecision() can be used to specify the precision to which a double value will be output. The value will be rounded at the specified position. The utility is often used with the fixed utility (described below). A number inserted into the parentheses. The number represents the position, to the right of the decimal point,, where we want to round off to.

fixed is used to force doubles to be in fixed point notation rather than scientific notation. This allows us to more easily represent the fractional component of the value. Examples: cout << setw(10) << value <<endl; Sets a field of 10 characters then prints the contents of value in the field. cout << fixed << setprecision(2) << value << endl; Forces fixed point notation (standard notation) prints the contents of value and rounds to the second place to the right of the decimal point. cout << fixed << setw(10) << setprecision(2) << value << endl; Forces fixed point notation, sets a field width of 10 characters, and sets the precision to the second place to the right of the decimal. It is interesting to note that if the field width is exceeded by the number of required characters to represent the value, the formatting is ignored. Try the following: 1. Output a string within a field. 2. Output a value that exceeds the field width specification. 3. What happens if you set a precision of 0? -1?

Now back to the program. Consider the following statement. Notice that the description is set in a field but the number is not. Notice also that the number (tot_pay) is formatted as a fixed point value and rounded to two places (to the right of the decimal). cout << setw(35) << "Expected Pay for the Period: " << fixed << setprecision(2) << tot_pay << endl; Try your hand at a variety of combinations of fixed, setw(),and setprecision(). Try using integer variables in the place of the integer constants. Does this give you some ideas?? Sometimes we can insert integer expressions in the parentheses. For example we can build an auto centering utility. Lets assume the screen is 80 characters wide, the amount of white-space can be determined by 80 minus the number of characters in the string (value). Half of the white space needs to be to the left of the string and half to the right. So knowing the output is set to the right side of the field, we need to size the field appropriately. The field width then is the sum of the number of characters in the string plus half of the whitespace. Let s put this concept to work. Assume the following: string str = Press <ENTER> to Continue ; It is easier to assign the data to a variable and work with the variable. Calculation for half of the white space: (80 str.length())/2 In this expression,.length() string member returns the number of characters in the string. Subtract the number of characters in the string from the screen (page) width and divide the result by 2. The use of parentheses forces the subtraction to occur prior to the division. Add the space required for the string: ( (80 str.length())/2) + str.length() Now set this into setw() and output the string:

cout << setw( ( (80 str.length()) / 2) + str.length() ) << str << endl; Increment and decrement operators Increment operator - is a unary operator that adds 1 to a variable each time the statement is executed. It may be prefixed of post-fixed. Examples: count++; or ++count; means => count = count + 1; Prefixed means increment then use the variable; post-fixed means use the variable then increment it. If the increment is on a separate line this becomes a moot point because by the time the next line is executed the value will be incremented in either event. Examples: int count = 0; Prefixed Operator int count = 0; Post-fixed Operator cout << ++count; cout << count++; Output: 1 Final Value: 1 Output: 0 Final Value: 1 Decrement Operator - is a unary operator that subtracts 1 from a variable each time the statement is executed. It may be prefixed of post-fixed. Examples: count--; or --count; means => count = count - 1; prefixed means increment then use the variable; post-fixed means use the variable then increment it. The effects are the same as the increment operator.

Examples: Prefixed Operator int count = 10; Post-fixed Operator int count = 10; cout << --count; cout << count--; Output: 9 Final Value: 9 Output: 10 Final Value: 9 Alternate (Compound) Assignment Operators - +=, -=, *=, /=, %= A number of assignment operators have been created to reduce the typing required for creating accumulators of various sorts. Note that the listed operators are only a partial list. However, assignment operators can make the reviewing of code, at times, mysterious. Consider the following code segment string resp = XXX ; double total = 0.0; double value=0.0; cout << Enter a value to add to a total: ; getline(cin, resp); value = atof(resp.data()); total = total + value; cout << total <<endl; // Because we frequently add values to a total (typically in a loop) there is a shortened expression that would look like This means exactly the same as total +=value;

total = total + value; It is read, retrieve the value beginning at the memory location referenced by total; add the value referenced by value; then assign the result to the memory location referenced by total. Another way to read it is, total gets total plus value. It often helps to comment these lines if you use the shortened notation. Similar notation is available for all of the arithmetic operations. The following is a table of the arithmetic assignment operators. Assignment (Compound) Operators Operator Use Meaning += answer += value answer = answer + value -= answer -= value answer = answer - value *= answer *= value answer = answer * value /= answer /= value answer = answer / value %= answer = %= value answer = answer % value Relative Positions on the Hierarchy Table The following shows the relative positions of the various operators with respect to other operators. What does this mean to us? The higher in the table an operator occurs the more likely the operands (numbers associated with the operator) will be resolved first. Hierarchy Table for the Operators Identified to this Point Operator Comment Operation sequence (), casting, ++, -- Post-fixed Left to right ++, --,! Unary operators prefixed Right to left +, - Unary sign operator Right to left *, /, % Arithmetic Multiplicative Left to right

+, - Arithmetic Additive Left to right <<, >> Insertion, Extraction Left to right <, >, <=, >= Relational Left to right ==,!= Relational equivalent Left to right && Logical AND Left to right Logical OR Left to right =, =+, =-, =*, =/, =%, etc Assignment Right to left A simple example of operator hierarchy answer = 5 + 7 * 3 - ( 4 2 ) Looking at the Hierarchy table we see that parentheses are very close to the top so the operations within the parentheses are resolved first. We also note that the assignment operator is located at the bottom of the table and is evaluated last. The expression becomes answer = 5 + 7 * 3 2 Next looking at the table we find that multiplication has a higher position than + or -. So the multiplication is resolved next answer = 5 + 21 2 At this point we find that add and subtract are at the same level so the execution is left to right answer = 26 2 The assignment operator is evaluated answer = 24 Here is another example using nesting parentheses. Here the secret is to resolve the inner expression then work out to the outer parentheses. answer = 5+(4+ (3-2) *5+ (4*6-9) /5))

answer = 5+ (4+1 *5+ (15/5) ) answer = 5 + (4 +1 *5 + 3 ) answer = 5 + ( 4 + 5 + 3 ) answer = 5 + 12 answer = 17 Your Turn Resolve the following expressions to a single value. It is suggested that you do these in steps remembering that certain operations will naturally occur prior to others. 1. Answer = 5+4/2*6-2/(5%2) 2. Answer = 5 * (3 + 2 ) (7 + ( 4 6 ) ) II. Program implementation concepts The actual code is based on the sequencing of the screen designs. After the sequencing has been set the actual code is relatively easy. Because you can refer to the location of the beginning of the text in each line, creation of spacing is streight-foreward. As indicated above, the execution of statements is sequential.