Chapter 3

30
Chapter 3 Reading a Set of Data

description

Chapter 3. Reading a Set of Data. Reading a Set of data. A Simple Payroll Program Problem: Write a complete C++ program to do the following: Read in data containing information about an employee of a company. - PowerPoint PPT Presentation

Transcript of Chapter 3

Page 1: Chapter 3

Chapter 3

Reading a Set of Data

Page 2: Chapter 3

CIS 1.5 Introduction to Computing with C++ 3-2

Reading a Set of dataA Simple Payroll Program Problem: Write a complete C++ program to do the following:

Read in data containing information about an employee of a company. The data will contain the employee's ID, hours worked in a week, and rate of pay per hour. Compute the employee's pay for the week. Print the relevant information about this employee. Then repeat the same steps for the next employee until all employees have been processed. Count the number of employees processed and print the total at the end.

Typical Data1234 35.0 14.202345 11.3 5.87

Pseudocode for the Program:do the following for each employee

read idread hours workedread ratecalculate pay = hours * rateprint relevant informationcount this employee

print total number of employees

Page 3: Chapter 3

CIS 1.5 Introduction to Computing with C++ 3-3

The while Statement The while statement (or while loop) repeats a

group of statements while a given condition is true.

The while Statement:while (condition)

body (statement) of the loop

CPU action when reaching while statement: It evaluates condition which can be TRUE or FALSE. If condition is TRUE, then:

the CPU executes the body of the loop. when the CPU completes the body of the loop, it jumps back to the

while statement and starts the procedure all over again. If condition is FALSE, the CPU jumps to the statement

following the loop statement.

Page 4: Chapter 3

CIS 1.5 Introduction to Computing with C++ 3-4

The while Statement

n = 1;

while (n < 10)

n *= 2;

cout << "The smallest power of 2 greater than 10 is " <<n << endl;

n = 0;

while (n != 20) {

cout << "Learning C++ is fun!" << end;

n++;

}

n = 1;

while (n <= 10) {

cout << "Enter a value for x:” << endl;

cin >> x;

y = x * 2;

cout << "y = “ << y << endl;

n++;

}

//comparison using a for statement

for (n = 1; n <= 10; n++) {

cout << "Enter a value for x:” << endl;

cin >> x;

y = x * 2;

cout << "y = “ << y << endl;

}

Page 5: Chapter 3

CIS 1.5 Introduction to Computing with C++ 3-5

While loop trace Trace the values of the variables

n and x./* program loop */#include <iostream>using namespace std;int main(){ int n,x; x = 1; n = 0; while (n != 3) { x *= 2; n++; } cout << x; return 0;}

n x

? ?

Initialize 0 1

n != 3 - True 1 2

n != 3 - True 2 4

n != 3 - True 3 8

n != 3 - False 4

Screen 8

Page 6: Chapter 3

CIS 1.5 Introduction to Computing with C++ 3-6

Using a while Loop To find the last employee, we can make up a fake ID to

represent the last employee and test for that in a while loop. (Let us assign the ID for the fake employee is -1.)

Pseudocode for the Program:int id;while (id != -1) {

read idread hours workedread ratecalculate pay = hours * rateprint relevant informationcount this employee

}print total number of employees

Page 7: Chapter 3

CIS 1.5 Introduction to Computing with C++ 3-7

Interactive Data Entry The cin statement syntax:

cin >> item1 >> item2 >> ... >> itemN; where << is the extraction operator and each item is a variable

identifier.

Question: How does the operator know what to enter?

Prompts & Interactive Programming:int id;double hours,rate;cout << "Please enter an ID: ";cin >> id;cout << "Please enter the hours worked: ";cin >> hours;cout << "Please enter the rate of pay: ";cin >> rate;

Page 8: Chapter 3

CIS 1.5 Introduction to Computing with C++ 3-8

Reading Multiple Data Values Example

cout << "Please enter an ID, hours, and rate: ";cin >> id >> hours >> rate;

To enter data for this call, the user types in three separate values followed by the ENTER key.

e.g., 1234 10.5 4.65 (ENTER)

The values themselves may be separated by any number of blanks, TABs, or ENTERs, but not by commas.

Note: If a real value is entered, where an integer is expected, the value will be truncated. e.g., 1234.5 10.5 4 (ENTER)

Note: If an alphabetic character is entered when a number is expected, the variable awaiting input will keep its old value.

e.g., 1234 10.5 XYZ (ENTER)e.g., WXYZ 10.5 4.65 (ENTER)

Page 9: Chapter 3

CIS 1.5 Introduction to Computing with C++ 3-9

Revised Payroll Program/* payroll program */#include <iostream>using namespace std;int main(){

int id;double hours,rate,pay;while (id != -1) {

cout << "Please enter an ID (enter -1 to stop): ";cin >> id;cout << "Please enter the hours worked: ";cin >> hours;cout << "Please enter the rate of pay: ";cin >> rate;pay = hours * rate;cout << “Employee “ << id << “ worked “ << hours << “ hours at a rate of pay of $” << rate << “ earning $” << pay << endl << endl;count this employee

}print total number of employeesreturn 0;}

FATAL FLAW IN WHILE LOOP!!! What happens the first time we reach the while loop?

Page 10: Chapter 3

CIS 1.5 Introduction to Computing with C++ 3-10

Another Revision/* payroll program */#include <iostream>using namespace std;int main(){

int id;double hours,rate,pay;cout << "Please enter an ID (enter -1 to stop): ";cin >> id;while (id != -1) {

cout << "Please enter the hours worked: ";cin >> hours;cout << "Please enter the rate of pay: ";cin >> rate;pay = hours * rate;cout << “Employee “ << id << “ worked “ <<hours << “ hours at a rate of pay of $” << rate<< “ earning $” << pay << endl << endl;count this employee

}print total number of employeesreturn 0;}

! WE STILL HAVE A FLAW!!!

Page 11: Chapter 3

CIS 1.5 Introduction to Computing with C++ 3-11

Yet Another Revision/* payroll program */#include <iostream>using namespace std;int main(){

int id;double hours,rate,pay;cout << "Please enter an ID (enter -1 to stop): ";cin >> id;while (id != -1) {

cout << "Please enter the hours worked: ";cin >> hours;cout << "Please enter the rate of pay: ";cin >> rate;pay = hours * rate;cout << “Employee “ << id << “ worked “ <<hours << “ hours at a rate of pay of $” << rate << “ earning $” << pay << endl << endl;count this employeecout << "Please enter an ID (enter -1 to stop): ";cin >> id;

}print total number of employeesreturn 0;}

Page 12: Chapter 3

CIS 1.5 Introduction to Computing with C++ 3-12

Counting the Number of Employees Set up a counting variable to keep track of the number of employees processed.int main(){

int id; //employee iddouble hours,rate,pay;int numemp; //count the employeesnumemp = 0; //initialize the countercout << "Please enter an ID (enter -1 to stop): ";cin >> id; //read IDwhile (id != -1) { //check for fake ID

cout << "Please enter the hours worked: ";cin >> hours; //read hours workedcout << "Please enter the rate of pay: ";cin >> rate; //read rate of paypay = hours * rate; //calculate paycout << “Employee “ << id << “ worked “ <<hours << “ hours at a rate of pay of $” << rate << “ earning $” << pay << endl << endl;numemp++; //increment countercout << "Please enter an ID (enter -1 to stop): ";cin >> id; //read new ID

}cout << "\nWe have processed “ << numemp << “ employees” << endl;return 0;

}

Page 13: Chapter 3

CIS 1.5 Introduction to Computing with C++ 3-13

One step variable declaration and initialization

The statements int numemp;

numemp = 0;

Can be replaced with one statement

int numemp=0;

Page 14: Chapter 3

CIS 1.5 Introduction to Computing with C++ 3-14

Printing Numbers Neatly Field Width & Decimal Precision By default, C++ will print real numbers with up to six digits of precision. The number of digits appearing to the right of the decimal point is

determined by how many positions are available after printing the integer portion of the number.

For real numbers, we can specify how many positions are to be printed to the right of the decimal point. This is called the decimal precision.

To specify the decimal precision to be printed, add the following statements to your program:

cout.setf(ios::fixed,ios::floatfield);cout.precision(integer_value);

A call to cout.setf() and cout.precision() stays in effect for the rest of the program, until changed.

If you leave out the call to cout.setf(), then the call to cout.precision() will specify the number of significant digits printed. 154.5 with a precision of 3 will print as 155 with no decmial place. The integer

part (significant digits) uses up the 3 positions allotted. With a precison of 2 it will print as 1.5e+002

Page 15: Chapter 3

CIS 1.5 Introduction to Computing with C++ 3-15

Printing Numbers Neatly Field Width & Decimal Precision

To print a value occupying a specific number of print positions, we define its field width. This is possible both for real numbers and for integers.

To specify the exact number of character positions a value should occupy when it is printed, use a call to cout.width(integer_value). A call to cout.width() only applies to the next value to

be printed. It does not even apply to two values printed in the same cout.

Left and Right Alignment (Justification) Normally, numbers are printed right justified within

their field width. To left justify a number, insert the statement: setf(ios::left);

Page 16: Chapter 3

CIS 1.5 Introduction to Computing with C++ 3-16

Payroll with output formatting/* payroll program */#include <iostream>using namespace std;int main(){ int id; //employee id double hours,rate,pay; int numemp = 0; //count the employees cout.setf(ios::fixed,ios::floatfield); cout.precision(2); //set decimal precision cout << "Please enter an ID (enter -1111 to stop): "; cin >> id; //read ID while (id != -1111) { //check for fake ID cout << "Please enter the hours worked: "; cin >> hours; //read hours worked cout << "Please enter the rate of pay: "; cin >> rate; //read rate of pay pay = hours * rate; //calculate pay cout << "Employee " << id << " worked " << hours << " hours at a rate of pay of $" << rate << " earning $" << pay << endl << endl; numemp++; //increment counter cout << "Please enter an ID (enter -1111 to stop): "; cin >> id; //read new ID } cout << "\nWe have processed " << numemp << " employees" << endl; system("pause"); return 0;}

Please enter an ID (enter -1111 to stop): 1234Please enter the hours worked: 35Please enter the rate of pay: 12.50Employee 1234 worked 35.00 hours at a rate of pay

of $12.50 earning $437.50

Please enter an ID (enter -1111 to stop): 1010Please enter the hours worked: 56.5Please enter the rate of pay: 45.89Employee 1010 worked 56.50 hours at a rate of pay

of $45.89 earning $2592.78

Please enter an ID (enter -1111 to stop): -1111

We have processed 2 employeesPress any key to continue . . .

Page 17: Chapter 3

CIS 1.5 Introduction to Computing with C++ 3-17

Specifying Field Width#include <iostream>using namespace std;int main(){double gpa,result;cout<<"\t\t\tTable of Function Values"<<endl<<endl;cout << "Grade Point Average\tValue of Formula\tStatus"<< endl;for (gpa = 0.00; gpa <= 4.00; gpa = gpa + 0.50){ result=(gpa*gpa*gpa+7*gpa-1)/(gpa*gpa-(gpa+5)/3); cout.width(19); cout << gpa; cout.width(21); cout << result; if (result >= 0) cout << "\tAdmit"; cout << endl;}cout << endl << "The table is finished" << endl;system("pause");return 0;}

Table of Function ValuesGrade Point Average Value of Formula Status

0 0.6 Admit

0.5 -1.65789

1 -7

1.5 154.5 Admit

2 12.6 Admit

2.5 8.56667 Admit

3 7.42105 Admit

3.5 7.04867 Admit

4 7 Admit

The table is finished

Press any key to continue . . .

Page 18: Chapter 3

CIS 1.5 Introduction to Computing with C++ 3-18

Specifying Left Justification#include <iostream>using namespace std;int main(){double gpa,result;cout<<"\t\t\tTable of Function Values"<<endl<<endl;cout << "Grade Point Average\tValue of Formula\tStatus"<< endl;for (gpa = 0.00; gpa <= 4.00; gpa = gpa + 0.50){ result=(gpa*gpa*gpa+7*gpa-1)/(gpa*gpa-(gpa+5)/3); cout.setf(ios::left); cout.width(19); cout << gpa; cout.width(21); cout << result; if (result >= 0) cout << "\tAdmit"; cout << endl;}cout << endl << "The table is finished" << endl;system("pause");return 0;}

Table of Function Values

Grade Point Average Value of Formula Status

0 0.6 Admit

0.5 -1.65789

1 -7

1.5 154.5 Admit

2 12.6 Admit

2.5 8.56667 Admit

3 7.42105 Admit

3.5 7.04867 Admit

4 7 Admit

The table is finished

Press any key to continue . . .

Page 19: Chapter 3

CIS 1.5 Introduction to Computing with C++ 3-19

Specifying Field Width and Decimal Precision

#include <iostream>using namespace std;int main(){double gpa,result;cout.setf(ios::fixed,ios::floatfield);cout.precision(2); //set decimal precisioncout<<"\t\t\tTable of Function Values"<<endl<<endl;cout << "Grade Point Average\tValue of Formula\tStatus"<< endl;for (gpa = 0.00; gpa <= 4.00; gpa = gpa + 0.50){ result=(gpa*gpa*gpa+7*gpa-1)/(gpa*gpa-(gpa+5)/3); cout.width(19); cout << gpa; cout.width(21); cout << result; if (result >= 0) cout << "\tAdmit"; cout << endl;}cout << endl << "The table is finished" << endl;system("pause");return 0;}

Table of Function Values

Grade Point Average Value of Formula Status

0.00 0.60 Admit

0.50 -1.66

1.00 -7.00

1.50 154.50 Admit

2.00 12.60 Admit

2.50 8.57 Admit

3.00 7.42 Admit

3.50 7.05 Admit

4.00 7.00 Admit

The table is finished

Press any key to continue . . .

Page 20: Chapter 3

CIS 1.5 Introduction to Computing with C++ 3-20

The if-else (Conditional) Statement The if-else (Conditional) Statement:

if (condition)statement_1

elsestatement_2

Alternate Forms:if (condition){

compound_statement_1}else{

compound_statement_2}

Example:Find the maximum of x and y.a)max = y;if (x > y) max = x;cout << max;

b)if (x > y) max = x;if (x <= y) max = y;cout << max;

c)if (x > y)

max = x;else

max = y;cout << max;

Page 21: Chapter 3

CIS 1.5 Introduction to Computing with C++ 3-21

More Complex Payroll Program

Assume that tax is to be deducted from employee's gross pay.

For employees that earn less than $300 a week, the tax rate is 15% of gross.

For all other employees, the tax rate is 28%.

Modify the payroll program to compute each employee's net pay (which is the gross pay less the tax).

Page 22: Chapter 3

CIS 1.5 Introduction to Computing with C++ 3-22

More Complex Payroll Program

cout << "Please enter an ID (enter -1111 to stop): ";cin >> id; //read IDwhile (id != -1111) { //check for fake ID

cout << "Please enter the hours worked: ";cin >> hours; //read hours workedcout << "Please enter the rate of pay: ";cin >> rate; //read rate of paypay = hours * rate; //calculate pay

if (pay < 300) //calculate the tax tax = 0.15 * pay;else tax = 0.28 * pay;netpay = pay - tax; //calculate the net pay

cout << “Employee “ << id << “ worked “ << hours <<“ hours at a rate of pay of $” << rate << “ earning $”<< pay << endl;

cout << “tax withheld was $“ << tax << “ leaving net pay”<<“ of $” << netpay << endl << endl;numemp++; //increment countercout << "Please enter an ID (enter -1 to stop): ";cin >> id; //read new ID

}cout << "\nWe have processed “ << numemp << “ employees” << endl;return 0;

Please enter an ID (enter -1 to stop): 1234Please enter the hours worked: 35Please enter the rate of pay: 12.50Employee 1234 worked 35.00 hours at a rate of pay of

$12.50 earning $437.50tax withheld was $122.50 leaving net pay of $315.00

Please enter an ID (enter -1 to stop): 9876Please enter the hours worked: 10Please enter the rate of pay: 14Employee 9876 worked 10.00 hours at a rate of pay of

$14.00 earning $140.00tax withheld was $21.00 leaving net pay of $119.00

Please enter an ID (enter -1 to stop): -1111

We have processed 2 employeesPress any key to continue . . .

Page 23: Chapter 3

CIS 1.5 Introduction to Computing with C++ 3-23

The Conditional (?:) Operator C++ allows statements of the following form:

variable = conditional expression; where a conditional expression is of the form: expr1 ? expr2 : expr3

expr1 is a condition that evaluates to true or false,if expr1 is true expr2 is the value of the conditional expressionelse expr3 is the value of the conditional expression

Example:if (x > y)

max = x; else

max = y;

can be written as: max = (x > y) ? x : y;

Page 24: Chapter 3

CIS 1.5 Introduction to Computing with C++ 3-24

Using the Conditional Operator

The conditional if statementif (pay < 300)

tax = 0.15 * pay;

else

tax = 0.28 * pay;Can be replaced with the conditional

operator statement tax = (pay < 300) ? 0.15 * pay : 0.28 * pay;

Page 25: Chapter 3

CIS 1.5 Introduction to Computing with C++ 3-25

Using the Conditional Operator

The conditional if statementif (pay < 300)

tax = 0.15 * pay;

else

tax = 0.28 * pay;Can be replaced with the conditional

operator statement tax = (pay < 300) ? 0.15 * pay : 0.28 * pay;

Page 26: Chapter 3

CIS 1.5 Introduction to Computing with C++ 3-26

File input and output#include <iostream>

#include <fstream>

using namespace std;

int main()

{

int id; //employee id

double hours,rate,pay,tax,netpay;

int numemp = 0; //count the employees

//un-comment to redirect cin to a file

ifstream cin("c:\\Temp\\prob3in.txt");

// ifstream cin(“con”);

// open output file

ofstream outfile("c:\\Temp\\prob3out.txt");

//ofstream outfile("con"); //un-comment for debugging

outfile.setf(ios::fixed,ios::floatfield);

outfile.precision(2); //set decimal precision

cout << "Please enter an ID (enter -1111 to stop): ";

cin >> id; //read ID

while (id != -1111) { //check for fake ID

cout << "Please enter the hours worked: ";

cin >> hours; //read hours worked

cout << "Please enter the rate of pay: ";

cin >> rate; //read rate of pay

pay = hours * rate; //calculate pay

tax = (pay < 300) ? 0.15 * pay : 0.28 * pay; //calculate tax

netpay = pay - tax; //calculate the net pay

outfile<< "Employee " << id << " worked " << hours

<< " hours at a rate of pay of $" << rate

<< " earning $" << pay << endl;

outfile<< "tax withheld was $" << tax

<< " leaving net pay of $" << netpay << endl << endl;

numemp++; //increment counter

cout << "Please enter an ID (enter -1111 to stop): ";

cin >> id; //read new ID

}

outfile << "\nWe have processed " << numemp<< " employees" << endl;

cin.close();

outfile.close(); //close output file

return 0;

}

Page 27: Chapter 3

CIS 1.5 Introduction to Computing with C++ 3-27

Contents of input and output files

prob3in.txt

1111

200.00

10.00

9999

10.00

15.00

-1111

prob3out.txtEmployee 1111 worked 200.00 hours at a rate of pay of $10.00 earning $2000.00

tax withheld was $560.00 leaving net pay of $1440.00

Employee 9999 worked 10.00 hours at a rate of pay of $15.00 earning $150.00

tax withheld was $22.50 leaving net pay of $127.50

We have processed 2 employees

Page 28: Chapter 3

CIS 1.5 Introduction to Computing with C++ 3-28

Payroll Program

The following program contains these features Input from a file or the consoleOutput to a file or the consoleCollecting information on the total netpayComputing the average net payDetermining the largest net pay and the id

of the employee with the largest net pay

Page 29: Chapter 3

CIS 1.5 Introduction to Computing with C++ 3-29

Payroll Program#include <iostream>#include <fstream>using namespace std;int main(){ int id; //employee id double hours,rate,pay,tax,netpay; int numemp = 0; //count the employees int largestID; double totalNetPay=0; double largestNetPay=-1; //un-comment to redirect cin to a file ifstream cin("c:\\Temp\\prob3in.txt"); // ifstream cin(“con”); // open output file // ofstream outfile("c:\\Temp\\prob3out.txt"); ofstream outfile("con"); //un-comment for debugging outfile.setf(ios::fixed,ios::floatfield); outfile.precision(2); //set decimal precision

Page 30: Chapter 3

CIS 1.5 Introduction to Computing with C++ 3-30

cout << "Please enter an ID (enter -1111 to stop): "; cin >> id; //read ID while (id != -1111) { //check for fake ID cout << "Please enter the hours worked: "; cin >> hours; //read hours worked cout << "Please enter the rate of pay: "; cin >> rate; //read rate of pay pay = hours * rate; //calculate pay tax = (pay < 300) ? 0.15 * pay : 0.28 * pay; //calculate tax netpay = pay - tax; //calculate the net pay totalNetPay=totalNetPay+netpay; outfile<< "Employee " << id << " worked " << hours << " hours at a rate of pay of $" << rate << " earning $" << pay << endl; outfile<< "tax withheld was $" << tax << " leaving net pay of $" << netpay << endl << endl; // comparing to determine the largest netpay of all employees if (largestNetPay < netpay) { largestNetPay = netpay; largestID = id; }

numemp++; //increment counter

cout << "Please enter an ID (enter -1111 to stop): ";

cin >> id; //read new ID

}

outfile << "\nWe have processed " << numemp<< " employees" << endl;

outfile << "\nThe total net pay is " << totalNetPay<< " dollars" << endl;

outfile << "\nThe average net pay is " << totalNetPay/numemp<< " dollars" << endl;

outfile<<"Employee "<<largestID<<" has the largest net pay of "<<largestNetPay<<endl;

cin.close(); outfile.close(); //close output file system("pause"); return 0;}