File I/O Includes #include <fstream> File I/O Data types ifstream ofstream Opening Files Closing Files cin.good() is equivalent to cin !cin is equivalent to cin.fail() cin.good is true if there is no error condition (unrecoverable or otherwise) and the end-of-file flag is not set. cin.bad is true if there is an unrecoverable error cin.fail is true if there is an unrecoverable error or an "expected" condition, such as a conversion error, or if the file is not found. Processing can often resume after a call to clear with a zero argument. Comparison operators <, <=, >, >=, !=, == bool data type It has only two values – true and false The value of a Boolean expression is true or false bool v = 3 < 5; bool w = 5 < 3 The syntax of one kind of Boolean expression is left expression <comparison operator> right expression “fred” != 17 3.0 != 3 By default the data type of floating point constant is double. One can qualify the data type with a suffix – F for float and D for double 3.0F 3.0D More Boolean expressions 5 5 3 3 5 5 5 < 3 <= 3 <= 5 >=5 >= 3 != 3 == 3 (false) (false) (true) (false) (true) (true) (false) This expression is not a safe Boolean expression. C++ evaluates the expression but describes it as an unsafe expression 10 <= 15 <= 20 The correction version of the expression is 15 >= 10 &&15 <= 20 The meaning of the expression is that 15 is between 10 and 20. In general a value is between two other value if the value is greater than or equal to a lower bound and less than or equal to an upper bound The and operator, &&, combines several Boolean expressions into a compound Boolean expression. The compound Boolean expression is true if all the component expressions are true For example, int a = 3, b = 4, c = 10 a <= b && b <= c is true because both components are true a <= c && c <= b is false because the second component is false The or operator, ||, is not as restrictive as and operator, && 15 >= 10 || 15 <= 20 is true because at least one component istrue 15 <= 10 || 15 <= 20 is true because the second component is true 15 <= 10 || 20 <= 15 is false because both components are false 5 <= 10 || 5 >= 20 is true because the first component is true 5 <= 10 && 5 >= 20 is false because the second component is false 10 <= 5 || 10 >= 20 is false because both components is false 10 <= 5 && 10 >= 20 is false because one of the components is false An An An An And expression is true if all components are true Or expression is true if at least one component is true And expression is false if at least one component is false Or expression is false if both components are false Simple if statement If age < 16 then write ‘you have your sweet 16 party to look forward to’ If 13 <= age and age <= 19 then write ‘you are a teenager now’ Two way if statement If age < 16 then write ‘you still have your sweet 16 to look forward to’ else write ‘you already had your sweet 16’ end if if 13 <= age and age <= 19 then write ‘you are a teenager now’ else write ‘you are not a teenager’ end if Multi-way if statement If age < 13 then write ‘you are not a teenager yet’ else if age < 20 then write ‘you are a teenager now’ else write ‘you are not a teenager any more’ end if Multi-way if statement with mutually exclusive conditions If age < 13 then write ‘you are not a teenager yet’ else if 13 <= age and age <= 19 then write ‘you are a teenager now’ else write ‘you are not a teenager any more’ end if The following is an example of a multi-way if statement. It is called a multi-branch if statement because it has several conditions. If age < 16 then come back when 16 else if age < 18 apply for restricted license else if age < 85 then apply for regular license else apply for restricted license We can write the same conditions using a compound condition. Try to convince yourself that the two if statements produce the same results if age < 16 then come back at 16 else if age < 18 or age >= 85 then apply for restricted license else apply for normal license end If Or conditions let the programmer select one of several paths If state is Alaska or state is Hawaii or state is Puerto Rico then increase taxes by 50% else if state is California then decrease taxes by 50% else increase taxes by 25% end If if statements one-way if statement If(boolean expression) statement e.g. if(3 > 5) cout << “3 > 5” << endl; If the Boolean expression is true then the program executes the statement. If the expression is false then the program does nothing. two way if statement if(boolean expression) t-statement else e-statement If the Boolean expression is true then the program executes the t-statement. If the Boolean expression is false then the program executes the e-statement. if(3 > 5) cout << “3 > 5”; else cout << “5 > 3”; The program displays “5 > 3” operator precedence Arithmetic statements have a higher precedence than relational operators. Relational operators have a higher precedence than logical operators. Logical operators have a higher precedence than the assignment operator. Why? We must evaluate the expression before we can compare it. Hence we do the computations before we compare the results of the computations and we have to evaluate the simple Boolean expressions before we can join them into more complex expressions. bool whatever = state == Alaska || state == Hawaii || state == PuertoRico C++ evaluates the relational operators’ expressions first because the relational operators must operate on values; then the relational operators because the logical operators must operate on Boolean values; finally the logical operators produce a Boolean value – true or false Arithmetic operator precedence The unary negation operator has a very high precedence because the other operators must operate on a number. Look at the expression X = -17 + 3 If the addition operator has a higher precedence than the negation operator then the value of the expression would be -20 instead of -14. Y = 35 – 17 + 3 C++ evaluate 8 + 7 then 4 + 21 and finally 15 < 25 8 + 7 < 4 + 21 15 < 4 + 21 15 < 25 We will write the algorithm 2 ways. The first way tests for a bad number; the second way tests for a good number version 1 prompt to enter number between 0 and 35 if number < 0 or number > 35 then write error message else if number <= 9 then write number else compute letter from number write number and letter end if version 2 prompt to enter number between 0 and 35 if number >= 0 and number <= 35 then if number > 9 then compute letter from number write number and letter else write number end if else write error message end if Look at the 2 versions’ first Boolean expressions number < 0 or number > 35 number >= 0 and number <= 35 The first condition is true whenever the second condition is false The first condition is false whenever the second condition is true That means the first version’s then statement is the second version’s else statement and the first version’s else statement is the second version’s then statement. C++ stores characters as numbers A is 65 Z is 90 number is between 10 and 35 number – 10 is between 0 and 25 ‘A’ ‘A’ ‘A’ ‘A’ + + + + 0 is ‘A’ 1 is ‘B’ 24 is ‘Y’ 25 is ‘Z’ statement blocks Sometimes we want an if statement to control more than one statement. if(boolean expression) { t-statement-1 … t-statement-n } If(boolean expression) { t-statement-1 … t-statement-n } else { e-statement-1 … e-statement-m } Programs to write Write a program that reads 3 numbers and then outputs the numbers in descending order Algorithm read n1 read n2 read n3 if n1 < swap end if if n1 < swap end if if n2 < swap end if n2 then n1 and n2 n3 then n1 and n3 n3 then n2 and n3 How do you swap values? Swap x and y t = x x = y y = t Write a program that generates a random number between 0 and 10 and asks the user the number. The program reads the user’s guess and then tells the user if the guess is too high, too low or equal to the random number. How do you generate random numbers? #include #include #include #include #include <cmath> <iostream> <stdio.h> <stdlib.h> <time.h> using namespace std; int main(int argc, char* argv[]) { srand(unsigned(time(NULL))); int secret_number = rand() % 11; cout << secret_number << endl; return 0; } “time(NULL)” is some form of the current clock time on the computer. It is something like the number of seconds since midnight January 1, 1970. I’m not sure what it is exactly but we don’t really need to know. “srand” initializes the random number generator function. If you want to always generate different sequences of random numbers then make sure srand’s parameter is always different. “time(NULL)” goes a look way to insuring that the program generates different sequences of random numbers. Sometimes you want the program to generate the same sequence of random numbers. Use srand a particular number as its parameter. You will always generate the same sequence of random numbers. Problems Write a program that determines if a meeting room is in violation of fire regulations for the maximum room capacity. The program will read in the maximum room capacity and the number of people to attend the meeting. If the number of people is less than or equal to the maximum room capacity, the program announces that it is legal to hold the meeting and tells how many additional people may legally attend the meeting. If the number of people exceeds the maximum room capacity, the program announces that the meeting cannot be held as planned due to fire regulations and tells how many people must be excluded in order to meet the fire regulations and thereby allow the meeting to take place. Write a program that computes the cost of postage on a firstclass letter according to the following rate scale: 30 cents for the first ounce or faction of an ounce, 11 cents for each additional half ounce, plus a 5-dollar service charge if the customer desires special delivery. An hourly employee is paid at a rate of $9.73 per hour for regular hours worked per week. Any hours over that are paid at the overtime rate of one and one-half times that. From the worker’s gross pay, 6% is withheld for social security tax, 14% is withheld for federal income tax, 5% is withheld for state income tax, and $6 per week is withheld for union dues. If the worker has three or more covered dependents, then an additional $10 is withheld to cover the extra cost of health insurance beyond what the employer pays. Write a program that will take the number of hours worked in a week and the number of dependents as input and then output the worker’s gross pay, each withholding amount, and the net take-home pay for the week.