Quick Index
4: More Math What We Will Cover Announcements Please silence all cell phones and pagers Sit at a computer station, start your computer and login When class is over, please shut down your computer. Remember that you lose any files not saved in the student folder. Continuations 4.1: More Math and Variables 4.1.1: Review of Arithmetic 4.1.2: Constants and Magic Numbers 4.1.3: Assignment Variations 4.1.4: Arithmetic Precision and Range 4.1.5: Type Casting 4.1.6: Summary Exercise 4.1 4.2: Making Selections 4.2.1: Flow of Control 4.2.2: The Value of a Relationship 4.2.3: Using if Statements 4.2.4: Using if-else Statements 4.2.5: Summary Exercise 4.2 4.3: More About Selection 4.3.1: Test Conditions and Boolean Values 4.3.2: Comparing Characters 4.3.3: Nested if Statements 4.3.4: Testing Multiple Conditions 4.3.5: Conditional Pitfalls 4.3.6: Summary Exercise 4.3 4.4: Repetition (Loops) 4.4.1: Introduction to Loops 4.4.2: Coding while Statements 4.4.3: Example Application: Play Again Program 4.4.4: Understanding the Main Loop 4.4.5: Summary Exercise 4.4 Wrap Up Due Next: A3: Conversions (3/1/07) Exercise 3 and CodeLab Lesson 3 (3/1/07) A4: Clothing Sizer (3/8/07) Exercise 4 and CodeLab Lesson 4 (3/8/07) Continuations Homework Questions? A3: Conversions (3/1/07) Exercise 3 and CodeLab Lesson 3 (3/1/07) How To Submit Homework Assignments Questions from last class? What would cout display for the value of degreesC after the following statements execute? Why? cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(1); int degreesC, degreesF; degreesF = 122; degreesC = 5 / 9 * (degreesF - 32); 0 0.0 50 50.0 Homework Discussion Questions (Thursday) What is the formula for the following statement? Assume that the lethal dose for a mouse is directly proportional to a lethal dose for a human being. Did you need to use the getline() function to input the dieter's name? Did you need to use cin.ignore(1000, '\n') in your program? Why or why not? Do you think this program provides an adequate solution to the problem? What improvements do you suggest for the problem solution? ^ top 4.1: More Math and Variables Objectives At the end of the lesson the student will be able to: Rewrite assignment statements into shortcut alternatives Diagnose problems with arithmetic precision and range and formulate solutions Generate code to convert data from one type to another ^ top 4.1.1: Review of Arithmetic Recall that C++ uses the following operators for arithmetic + for addition - for subtraction * for multiplication / for division % for modulus (remainder) The dash (minus sign) is also used for negation Arithmetic expressions are combinations of numbers, variables, constants and operators double area = 0.0, radius = 4.5; const double PI = 3.14159265; area = PI * radius * radius; Operators have the same precedence as in algebra Parenthesis: ( ) Function calls Unary operators: +, - Multiplication, division, modulus: *, /, % Addition, subtraction: +, - Also recall that the results of integer division are truncated You must use modulus operator (%) to get the remainder value In addition, you use mathematical functions for more complex operations cout << sqrt(3.0 * 3) << endl; ^ top 4.1.2: Constants and Magic Numbers A constant variable (or constant) is a variable that cannot change after being assigned a value Sounds oxymoronic, but is actually quite useful To declare a constant, use the keyword: const const int MY_CONST = 1; Note that you must assign a value when the constant is declared Also note that the name is all uppercase letters with an underscore separator This is a common coding convention that you must follow Magic Numbers Imagine that you are a programmer hired to modify a payroll program You come across the following section of code: double pay; pay = hours * 7.5 + (hours / 40) * (hours - 40) * 7.5 * 0.5; The numbers are important to the program, but what do they mean? Numbers like these are called "magic numbers" They are magic because the value or presence is unexplainable without more knowledge Often, no one knows what they mean after 3 months, including the author A programmer can often infer the meaning of numbers after reading the code carefully Much better coding style is to use named constants rather than literal numbers For example: const double WAGE = 7.5; const double OVERTIME_ADDER = 0.5; const int HOURS_PER_WEEK = 40; double pay; pay = hours * WAGE + (hours / HOURS_PER_WEEK) * (hours - HOURS_PER_WEEK) * WAGE * OVERTIME_ADDER; Now it is much easier to understand the code And see any problems or limitations Another reason to use named constants is that it is easier to change the value of the number In the above example, we can easily change the WAGE without making errors in other parts of our code Programming Style: Constant Variables and Magic Numbers Since the meaning of literal ("magic") numbers is hard to remember, you should declare constants instead const int FEET_PER_YARD = 3; const double PI = 3.14159265; const double WAGE = 7.5; const double OVERTIME_ADDER = 0.5; const int HOURS_PER_WEEK = 40; Note that the name is all uppercase letters with an underscore word-separator This is a common coding convention that you must follow More Information No Magic Numbers: from "How To Document and Organize Your C++ Code" Magic number (programming): about magic numbers in code from Wikipedia ^ top 4.1.3: Assignment Variations Unlike math, you can have the same variable on both sides of an equals sign int sum = 25; // initialize sum to 25 sum = sum + 10; // add to sum Note that the value of the variable is changed in the second line Reading variables from memory does not change them Values placed into a variable replace (overwrite) previous values Abbreviated Assignment Expressions Any statement of form: variable = variable <op> (expression); May be written in an abbreviated form: variable <op>= expression; <op> is one of: +, -, *, /, or % For example: sum = sum + 10; Can be written as: sum += 10; Increment and Decrement Operators Another arithmetic shortcut is the increment and decrement operators The increment operator (++) adds 1 to a variable's value Preincrement adds 1 before returning the value of a variable ++sum; Post-increment returns the current value of variable then adds 1 sum++; The decrement operator works like the increments operator, except it subtracts 1 from the variable For instance: --sum sum-- Pre- and post- increment matters when the operation is part of a larger expression For example, consider the code: int x = 5; int y = x++; cout << "x=" << x << " y=" << y; You may expect y to be 6 after this code executes Instead, y has the value of 5 The reason is that ++ after a variable (post-increment) is equivalent to: y = x; x = x + 1; On the other hand, ++ before a variable (pre-increment) is equivalent to: x = x + 1; y = x; ^ top 4.1.4: Arithmetic Precision and Range There are only a finite set of numbers in numerical data types This can lead to problems for the unwary Integer Overflow What happens when an integer is too big for its type? cout << "Big number: "; cout << 2147483647 + 1 << endl; cout << "Small number: "; cout << -2147483647 - 2 << endl; Wraps around from the highest number to the lowest You must be careful that your program will not go beyond the range of its data types Floating-Point Precision and Range Floating-point numbers are not exact representations of real numbers Rounding errors occur in repeated calculations Type double has about twice the precision of type float However, even type double can have rounding errors cout.precision(17); cout << .8F + .1F << endl; cout << .8 + .1 << endl; When floating point numbers get too large, they are set to inf cout << 2E38F + 2E38F << endl; Similarly, when numbers are too small they are set to 0.0 The Moral Integer and floating-point data types work well most of the time However, if you work with large positive or negative numbers, you must be sure you do not exceed the range of the data type Also, floating-point numbers have limited precision When math operations are performed repeatedly, they can become less precise You must be careful of precision when using floating-point numbers ^ top 4.1.5: Type Casting Cast: change the data type of the returned value of an expression Recall that different data types are stored in different forms Sometimes you need to change from one form to another Example: arithmetic adding a double and an int value C++ will automatically cast one value to another Also known as implicit casting May not know how to convert some values May not cast how the programmer wants Programmers can also explicitly cast data types Explicit casting changes the data type for a single use of the variable Precede the variable name with the new data type in parentheses: (dataType) variableName Data type is changed only for the single use of the returned value For example: int n; double x = 2.0; n = (int) x; Value of x is converted from type double to integer before assigning the value to n New Style Casting C++ has many styles of casting Newer style of casting is of the form: static_cast<toType>(expression) For example: int x = 9; int y = 2; double ans = x / static_cast<double>(y) Truncation When Casting Floating-Point to Integer type Converting (casting) a floating-point to integer type does not round -- it truncates Fractional part is lost (discarded, ignored, thrown away) For example: int n; double x = 3.99999; n = (int) x; // x truncated Value of n is 3 Example Application Using Casting 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 #include <iostream> using namespace std; int main() { double input; cout << "Enter hours: "; cin >> input; int hours = (int) input; // prevents warning int minutes = (int) ((input - (int) input) * 60); cout << "In hours and minutes, this is " << hours << ":" << minutes << endl; return 0; } ^ top 4.1.6: Summary Constants are a variable that cannot change after it is first assigned a value Constants are often used to apply meaningful names to numbers Another reason to use named constants is that it is easier to change the value of the number C++ has assignment variations of the form: variable <op>= expression; Not all numbers can be represented accurately by primitive C++ types Integer values have a limited range If your program assigns values too high or too low, integers wrap around Floating-point numbers usually have enough range However, they often suffer from lack of precision cout.precision(17); cout << .8F + .1F << endl; cout << .8 + .1 << endl; Type double has about twice the precision of type float When floating point numbers get too large, they are set to inf Similarly, when too small they are set to 0.0 C++ will automatically cast data of one type to another when necessary However, you can explicitly cast values to a different type. You must explicitly cast when C++ does not perform as you want. Check Yourself What is the code to declare a constant double named BIG_NUM and assign it a value of 100,000? How many ways can you add the integer 1 to a variable named index? List each way. What happens when you increase the value of an integer number beyond its range? How many digits that can be accurately stored in a float? double? Which is a valid typecast? a(int) int:a; (int)a; to(int, a); How do you truncate the decimal part of double variable? ^ top Exercise 4.1 The following code does not display the correct value of degreesC. 1 2 3 4 5 6 7 8 9 10 11 #include <iostream> using namespace std; int main() { double degreesC, degreesF; degreesF = 122; degreesC = 5 / 9 * (degreesF - 32); cout << degreesC << endl; return 0; } Specifications Save the code as degrees.cpp Use a cast to correct the code and obtain the correct output. Submit your program as the solution to this exercise. ^ top 4.2: Making Selections Objectives At the end of the lesson the student will be able to: Formulate relational expressions to produce boolean values Generate selection statements ^ top 4.2.1: Flow of Control The term flow of control refers to the order in which a computer executes instructions All programs can be written with just three control-flow elements: Sequence - continue with the next instruction All programs continue with the next instruction by default To make the program do something else, you code either a selection or repetition (looping) statement Selection - a choice between at least two options Either execute some instruction based on a condition Or continue with the next instruction if if-else Repetition - a loop (repeat a block of code)At the end of the loop: Either go back and repeat the block of code Or continue with the next instruction after the block for do-while while We will first consider selection statements ^ top 4.2.2: The Value of a Relationship To make a selection or repetition statement, you need to code a test condition The computer uses the condition to decide whether or not to execute the statement One way to code a test condition is to use a relational expression Relational Expressions In addition to arithmetical operations, all computers can compare numbers Many decisions can be reduced to choosing between two numbers Comparing numbers can make computers seem "intelligent" Expressions that compare numbers are called conditions or relational expressions Simple conditions have one relational operator comparing two values A condition always evaluates to either true or false The relational operators are: Math Name C++ Example Result = Equal to == 5 == 102 == 2 falsetrue ≠ Not equal to != 5 != 102 != 2 truefalse < Less than < 5 < 105 < 55 < 2 truefalsefalse ≤ Less than or equal to <= 5 <= 105 <= 55 <= 2 truetruefalse > Greater than > 5 > 105 > 55 > 2 falsefalsetrue ≥ Greater than or equal to >= 5 >= 105 >= 55 >= 2 falsetruetrue You may use relational operators with any numerical data ^ top 4.2.3: Using if Statements The simplest selection statement is an if statement This statement executes a section of code only if a condition is true If the test condition is false, the computer skips the code if (condition) { // execute statements only if true } For clarity: Write the if on a different line than the executed block Indent statements that are within the curly braces For Example What is new about the following code? What is the test condition? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 #include <iostream> using namespace std; int main() { int guess; cout << "I'm thinking of a number between" << " 1 and 10.\nCan you guess it?\n"; cin >> guess; if (guess == 7) { cout << "*** Correct! ***" << endl; } return 0; } About those Curly Braces Technically, the if statement affects only the single statement that follows We use curly braces to make that one statement into a block of statements This allows us to put any number of statements within the block Curly braces are not always required, but the best practice is to always include them ^ top 4.2.4: Using if-else Statements The if statement executes a block of code only if the conditional expression evaluates to true It does nothing if the conditional expression evaluates to false Sometimes we want to choose between two actions If a condition is true then do this Otherwise it is false so do something else General syntax: if (condition) { // evaluates to true // execute statements only if true } else { // execute statements only if false } Note that there is no test condition for the else clause The decision on which set of statements to use depends on only one condition For clarity, write the if and else on different lines than the other statements Also, indent the other statements For Example What do you notice that is different about the following code? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 #include <iostream> using namespace std; int main() { int guess; cout << "I'm thinking of a number between" << " 1 and 10.\nCan you guess it?\n"; cin >> guess; if (guess == 7) { cout << "*** Correct! ***\n"; } else { cout << "Sorry, that is not correct.\n"; } return 0; } Programming Style: Placement of Braces Different groups have different practices for placing curly braces in if and if-else statements In practice, you should use the style dictated by your group's policy Or your professor's instructions For the acceptable styles for this course see: Curly Braces ^ top 4.2.5: Summary Flow of control refers to the order in which a computer executes statements There are only three types of flow of control Sequence: continue with the next instruction Selection: a choice between at least two options Repetition: repeat a block of code (loop) To make a selection or repetition statement, you need to code a test condition The computer uses the condition to decide whether or not to execute the statement One way to code a test condition is to use a relational expression Relational operators include: == != < <= > >= Selection is a choice between at least two options Selection statements include: if if-else Check Yourself What is meant by the term "flow of control"? What is the default flow-of-control" operation after a statement finishes executing? What is the value of x after the following code segment? int x = 5; if (x > 3) { x = x - 2; } else { x = x + 2; } Does the syntax for an else clause include a test condition? ^ top Exercise 4.2 In this exercise we explore the use of relational operators with mathematical expressions. Specifications For the values: int a = 5, b = 2, c = 4, d = 6; Determine which of the following conditions are true and which are false. a > b a != b d % b == c % b a * c != d * b b % c * a != a * b Save your answers in a file named relationships.txt. Submit the relationships.txt file as the solution to this part of the exercise. As a final part of this exercise, save the following code as testscore.cpp 1 2 3 4 5 6 7 8 9 10 11 12 #include <iostream> using namespace std; int main() { int score; cout << "Enter your test score: "; cin >> score; // Insert statements here return 0; } Add code that tests if the score entered by the user is greater than or equal to 60. If so then print, "You passed!"; otherwise print, "Sorry, you failed" Submit the testscore.cpp file as the solution to this part of the exercise. ^ top 4.3: More About Selection Objectives At the end of the lesson the student will be able to: Construct test conditions that evaluate to a boolean value Use logical operators to assemble complex conditions Avoid some common pitfalls when creating test conditions ^ top 4.3.1: Test Conditions and Boolean Values All selection and loop statements have a test condition This test condition controls the operation of the statement You must construct test conditions so they always evaluate to a boolean value Boolean Values Boolean types have just one of two values: either true or false bool truth = true, lies = false; Recall that an expression is part of a statement that returns a value Thus, a boolean expression is some code that returns either true or false For example: true false 2 < 5 a == b We use boolean expressions like these to control selection and looping statements What is Truth? "What is truth?" may seem more appropriate for philosophy than programming However, in programming we need to know how the computer understands true and false The answer is that C++ stores boolean values numerically: true as 1 and false as 0 cout << true << endl; cout << false << endl; cout << boolalpha; // show output as true or false cout << true << endl; cout << false << endl; ^ top 4.3.2: Comparing Characters Character data can be evaluated using relational operators For these comparisons, char values are automatically changed into int values These conversions are done using ASCII codes Letters nearer to the start of the alphabet have lower numerical values Thus a numerical comparison can decide the alphabetical order of characters For example: cout << boolalpha; // show output as true or false cout << ('A' < 'C') << endl; cout << ('A' > 'C') << endl; cout << ('A' <= 'Z') << endl; cout << ('X' >= 'Y') << endl; cout << ('X' == 'X') << endl; cout << ('X' != 'X') << endl; More Information ASCII Table (7-bit) Binary Number System ^ top 4.3.3: Nested if Statements Note that you can include if statements within other if statements Each inner if statement is evaluated only if the outer condition is met For Example What do you notice that is different about the following code? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 #include <iostream> using namespace std; int main() { double temp = 0; cout << "Enter a temperature: "; cin >> temp; if (temp > 65) { if (temp > 75) { cout << "That's too hot!\n"; } else { cout << "That's just right.\n"; } } else { cout << "That's cold!\n"; } return 0; } Nesting if statements inside of if statements can be confusing when too deep Rule of thumb: no more than three deep Nesting in the else Clause You can also nest if statements in the else clause Unlike nesting in the if clause, you can next in else clauses as deep as you like For example, what do you notice that is different about the following code? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 #include <iostream> using namespace std; int main() { double temp = 0; cout << "Enter a temperature: "; cin >> temp; if (temp > 75) { // first condition cout << "That's too hot!\n"; } else if (temp > 65) { // next condition cout << "That's just right.\n"; } else { // default condition cout << "That's cold!\n"; } return 0; } Note the alignment of the nested statements Instead of: if (temp > 75) { // first condition cout << "That's too hot!\n"; } else { if (temp > 65) { // next condition cout << "That's just right.\n"; } else { // default condition cout << "That's cold!\n"; } } We use: if (temp > 75) { // first condition cout << "That's too hot!\n"; } else if (temp > 65) { // next condition cout << "That's just right.\n"; } else { // default condition cout << "That's cold!\n"; } This structure clearly shows the operation of the code Also, it prevents indentations cascading to the right ^ top 4.3.4: Testing Multiple Conditions One reason to use nested if statements is for testing multiple conditions Often a better way is to combine conditions using conditional operators Conditional operators allow you to consider multiple cases when deciding on what code to execute AND Operation One such operator is "and", which is spelled && in C++ For example, the following is true if temp >= 65 and temp <= 75 (temp >= 65) && (temp <= 75) When two boolean expressions are connected using && the whole expression is true only if both conditions are true However, if either condition is false the whole expression is false OR Operation Also, you can combine two boolean expressions using the "or" operator, spelled || in C++ For example, the following is true if temp < 65 or temp > 75 (temp < 65) || (temp > 75) When two boolean expressions are connected using || the whole expression is true if either condition is true Only if both conditions are false is the entire expression false NOT Operation Additionally, you can negate any expression using ! operator To use it, place the entire expression in parenthesis and place the ! operator in front For example, to get a temp between 65 and 75, we can negate our previous example: !((temp < 65) || (temp > 75)) Parenthesis Remember that a boolean expression in an if statement must be enclose in parenthesis Thus, an if statement that uses an && operator with two comparisons looks like: if ((temp >= 65) && (temp <= 75)) { Also note that relational operators have a higher precedence than logical operators Thus, you can remove the inner parenthesis without affecting the meaning if (temp >= 65 && temp <= 75) { However, if using parenthesis is clearer to you then use the extra parenthesis For Example #include <iostream> using namespace std; int main() { double temp = 0; cout << "Enter a temperature: "; cin >> temp; if (temp >= 65 && temp <= 75) { cout << "That's just right.\n"; } else { cout << "That's uncomfortable!\n"; } return 0; } ^ top 4.3.5: Conditional Pitfalls Unfortunately, you can write many things in C++ that should be incorrect but end up working for some obscure reason This means that you can code something that should create an error message but does not Thus, a program may compile and run with no error messages but still be wrong Since you may not realize that it is wrong, it can be hard to find and correct these types of errors Using = Instead of == One common mistake is to use = when you meant to use == For example, look at the test condition in the following code: if (guess = 7) { cout << "*** Correct! ***\n"; } else { cout << "Sorry, that is not correct.\n"; } Notice that the condition is really an assignment statement and not a test You would think that it would fail to compile -- but it does not However, it will not work as you might expect Note that if you compile with all the options that I suggest, that the compiler will display a warning: guess.cpp: In function `int main()': guess.cpp:10: warning: suggest parentheses around assignment used as truth value Another way to prevent this type of problem is to reverse the order of your test condition if (7 = guess) { Now the compiler will give you an error message and your code will not compile guess.cpp: In function `int main()': guess.cpp:10: error: non-lvalue in assignment However, if you correctly use == then your code will compile if (7 == guess) { Strings of Inequalities Do not use a string of inequalities like the following: int a = 5, b = 1, c = 10; if (a < b < c) { cout << "b is between a and c\n"; } else { cout << "b is NOT between a and c\n"; } Your code will probably compile and run but give incorrect results Instead, the correct way is to use && as follows: int a = 5, b = 1, c = 10; if (a < b && b < c) { cout << "b is between a and c\n"; } else { cout << "b is NOT between a and c\n"; } Strings of Logical Operators Logical expressions often read like "normal" English. However, C++ requires more detail than English For example, the following code will compile and run but give wrong results int guess; cout << "Enter a guess: "; cin >> guess; if (guess == 7 || 8) { cout << "*** Correct! ***\n"; } else { cout << "Sorry, that is not correct.\n"; } Instead, the correct way is to use || as follows: int guess; cout << "Enter a guess: "; cin >> guess; if (guess == 7 || guess == 8) { cout << "*** Correct! ***\n"; } else { cout << "Sorry, that is not correct.\n"; } ^ top 4.3.6: Summary All selection and repetition statements have a test condition This test condition controls the operation of the statement You must construct test conditions so they always evaluate to a boolean value Boolean types have just one of two values: either true or false A boolean expression is any expression that returns either true or false You can compare letters as well as numbers since letters are stored as numbers Used to alphabetize letters and words in a computer program Nested if statements are legal but often confusing Best to avoid nesting if statements in the if clause In contrast, nesting if statements in the else clause is fine When you need to compare several conditions, you use logical operators ! && || For example: (temp >= 65) && (temp <= 75) (temp < 65) || (temp > 75) !((temp < 65) || (temp > 75)) Unfortunately, you can write things in C++ that should be incorrect but end up working for some obscure reason These types of errors are often very difficult to find One common mistake is to use = when you mean to use == if (guess = 7) { Another problem is trying to use a string of inequalities without a logical operator separating each condition if (a < b < c) { Which should be written as: if (a < b && b < c) { Another error is trying to use logical operators without enough operand if (guess == 7 || 8) { Which should be written as: if (guess == 7 || guess == 8) { Check Yourself What two values can a boolean variable contain? Why can you compare character data using a relational expression? What is the effect of having an if statement nested in an if statement? What is the effect of having an if statement nested in an else statement? When does an AND (&&) of two or more conditions evaluate to true? When does an OR (||) of two or more conditions evaluate to false? What is the effect of the NOT (!) operator? ^ top Exercise 4.3 In this exercise we use multiple test conditions in a program. Specifications A student's letter grade is calculated according to the following table: Numerical Grade Letter Grade greater than or equal to 90 A less than 90 but greater than or equal to 80 B less than 80 but greater than or equal to 70 C less than 70 but greater than or equal to 60 D less than 60 F Save the following code as grader.cpp Change the code to: Convert the score entered by the user to a letter grade Display the letter grade Submit your program as the solution to this exercise. #include <iostream> using namespace std; int main() { double score; cout << "Enter a score: "; cin >> score; // Insert statements here return 0; } ^ top 4.4: Repetition (Loops) Objectives At the end of the lesson the student will be able to: Use while statements to repeat sections of code Apply commonly-used looping patterns Avoid common looping problems ^ top 4.4.1: Introduction to Loops Loops are used to repeat sections of code General loop structure: Initialization code Loop termination condition Loop body C++ has 3 loop statement while do-while for However, you can use any loop statement and achieve the same result Thus, I am only going to teach one loop statement at this time Later on we will look at the other loop statements ^ top 4.4.2: Coding while Statements The while loop is one of the simplest loop Use a while loop to repeat a section of code The repetition continues as long as the test condition remains true while loop Syntax: //Initialization ... while (condition) { //loop termination condition //loop body ... } Initialization statements usually precede the while loop Tests the (condition) at start of every loop iteration Continues as long as condition evaluates to true Note that if the loop condition is false at first then the loop body never executes The loop body can be a single statement or a block You can put any legal statement in the body of the loop Including if statements and other loop statements Diagram of while Loop Operation ^ top 4.4.3: Example Application: Play Again Program The following application simulates the play of an exciting game Note the 3 important parts of the loop Loop body -- statements to execute repeatedly Loop condition Loop initialization 1 2 3 4 5 6 7 8 9 10 11 12 13 14 #include <iostream> using namespace std; int main() { char answer = 'y'; while (answer == 'y') { cout << "\nPlaying an exciting game!\n"; cout << "Do you want to play again? (y/n) "; cin >> answer; } cout << "\nThanks for playing!\n"; return 0; } Which statement initializes the loop variables? Which part is the loop condition? Which part is the loop body? Loops of this type are often called the main programming loop Formatting the Code It is important to format the loop code correctly Note how the repeated code is indented inside the loop This lets us know visually what code is repeated and which is not Also note the placement of curly braces Different groups have different practices for placing curly braces in a loop statement For the acceptable styles for this course see: Curly Braces ^ top 4.4.4: Understanding the Main Loop We can generalize the main loop of our example Implementation can be different from one program to another However, the basic structure is the same for most programs Program Flow with a Main Loop Notes on the Program Flow Set Up (statements before the loop) Declare and initialize variables Provide instructions Repeated steps (loop body) Get User Input Update Variables Update Display Program Done? Check if the program is completed Often the user decides to exit Change variables in the test condition of the loop Shut Down (statements after the loop) Provide the user any final information End the program ^ top 4.4.5: Summary Loops are used to repeat sections of code General loop structure: Initialization code Loop condition -- evaluated during the loop Loop body The while loop is a simple repetition statement Syntax: //Initialization ... while (condition) { //loop termination condition //loop body ... } Most programs have a main loop Statements inside the loop repeat until the program exits Check Yourself What are the three parts of any loop? How do you code a while statement? What is the purpose of a loop test condition? What is meant by the term main programming loop? ^ top Exercise 4.4 In this exercise we use a loop to allow a user to repeat a program. Specifications Save the following code as add.cpp. Update the code to let the user repeat the program as long as they enter a 'y' or a 'Y'. Decide which statements need to repeat Write the while loop with a condition for exiting the loop Initialize the loop variables so the loop can run at least once Submit your program as the solution to this exercise. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 #include <iostream> using namespace std; int main() { double num1, num2; cout << "First number: "; cin >> num1; cout << "Second number: "; cin >> num2; cout << num1 << " + " << num2 << " = " << num1 + num2 << endl; return 0; } ^ top Wrap Up Reminders Due Next: A3: Conversions (3/1/07) Exercise 3 and CodeLab Lesson 3 (3/1/07) A4: Clothing Sizer (3/8/07) Exercise 4 and CodeLab Lesson 4 (3/8/07) When class is over, please shut down your computer You may complete unfinished exercises at the end of the class or at any time before the next class. ^ top Home | Blackboard | Announcements | Day Schedule | Eve Schedule Course info | Help | FAQ's | HowTo's | Links Last Updated: April 08 2007 @17:33:25
if
if-else
while
What would cout display for the value of degreesC after the following statements execute? Why? cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(1); int degreesC, degreesF; degreesF = 122; degreesC = 5 / 9 * (degreesF - 32); 0 0.0 50 50.0
cout
degreesC
cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(1); int degreesC, degreesF; degreesF = 122; degreesC = 5 / 9 * (degreesF - 32);
0
0.0
50
50.0
Assume that the lethal dose for a mouse is directly proportional to a lethal dose for a human being.
getline()
cin.ignore(1000, '\n')
^ top
At the end of the lesson the student will be able to:
+
-
*
/
%
double area = 0.0, radius = 4.5; const double PI = 3.14159265; area = PI * radius * radius;
( )
+, -
*, /, %
cout << sqrt(3.0 * 3) << endl;
const
const int MY_CONST = 1;
double pay; pay = hours * 7.5 + (hours / 40) * (hours - 40) * 7.5 * 0.5;
const double WAGE = 7.5; const double OVERTIME_ADDER = 0.5; const int HOURS_PER_WEEK = 40; double pay; pay = hours * WAGE + (hours / HOURS_PER_WEEK) * (hours - HOURS_PER_WEEK) * WAGE * OVERTIME_ADDER;
const int FEET_PER_YARD = 3; const double PI = 3.14159265; const double WAGE = 7.5; const double OVERTIME_ADDER = 0.5; const int HOURS_PER_WEEK = 40;
int sum = 25; // initialize sum to 25 sum = sum + 10; // add to sum
variable = variable <op> (expression);
variable <op>= expression;
<op>
sum = sum + 10;
sum += 10;
++
++sum;
sum++;
--sum sum--
int x = 5; int y = x++; cout << "x=" << x << " y=" << y;
y = x; x = x + 1;
x = x + 1; y = x;
cout << "Big number: "; cout << 2147483647 + 1 << endl; cout << "Small number: "; cout << -2147483647 - 2 << endl;
cout.precision(17); cout << .8F + .1F << endl; cout << .8 + .1 << endl;
inf
cout << 2E38F + 2E38F << endl;
Cast: change the data type of the returned value of an expression
(dataType) variableName
int n; double x = 2.0; n = (int) x;
x
double
integer
n
static_cast<toType>(expression)
int x = 9; int y = 2; double ans = x / static_cast<double>(y)
int n; double x = 3.99999; n = (int) x; // x truncated
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream> using namespace std; int main() { double input; cout << "Enter hours: "; cin >> input; int hours = (int) input; // prevents warning int minutes = (int) ((input - (int) input) * 60); cout << "In hours and minutes, this is " << hours << ":" << minutes << endl; return 0; }
float
BIG_NUM
100,000
a(int)
int:a;
(int)a;
to(int, a);
The following code does not display the correct value of degreesC.
1 2 3 4 5 6 7 8 9 10 11
#include <iostream> using namespace std; int main() { double degreesC, degreesF; degreesF = 122; degreesC = 5 / 9 * (degreesF - 32); cout << degreesC << endl; return 0; }
degrees.cpp
if if-else
for do-while while
true
false
==
5 == 102 == 2
!=
5 != 102 != 2
<
5 < 105 < 55 < 2
<=
5 <= 105 <= 55 <= 2
>
5 > 105 > 55 > 2
>=
5 >= 105 >= 55 >= 2
if (condition) { // execute statements only if true }
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream> using namespace std; int main() { int guess; cout << "I'm thinking of a number between" << " 1 and 10.\nCan you guess it?\n"; cin >> guess; if (guess == 7) { cout << "*** Correct! ***" << endl; } return 0; }
if (condition) { // evaluates to true // execute statements only if true } else { // execute statements only if false }
else
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream> using namespace std; int main() { int guess; cout << "I'm thinking of a number between" << " 1 and 10.\nCan you guess it?\n"; cin >> guess; if (guess == 7) { cout << "*** Correct! ***\n"; } else { cout << "Sorry, that is not correct.\n"; } return 0; }
== != < <= > >=
int x = 5; if (x > 3) { x = x - 2; } else { x = x + 2; }
In this exercise we explore the use of relational operators with mathematical expressions.
int a = 5, b = 2, c = 4, d = 6;
Determine which of the following conditions are true and which are false.
a > b
a != b
d % b == c % b
a * c != d * b
b % c * a != a * b
relationships.txt
testscore.cpp
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream> using namespace std; int main() { int score; cout << "Enter your test score: "; cin >> score; // Insert statements here return 0; }
bool truth = true, lies = false;
true false 2 < 5 a == b
1
cout << true << endl; cout << false << endl; cout << boolalpha; // show output as true or false cout << true << endl; cout << false << endl;
char
int
cout << boolalpha; // show output as true or false cout << ('A' < 'C') << endl; cout << ('A' > 'C') << endl; cout << ('A' <= 'Z') << endl; cout << ('X' >= 'Y') << endl; cout << ('X' == 'X') << endl; cout << ('X' != 'X') << endl;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream> using namespace std; int main() { double temp = 0; cout << "Enter a temperature: "; cin >> temp; if (temp > 65) { if (temp > 75) { cout << "That's too hot!\n"; } else { cout << "That's just right.\n"; } } else { cout << "That's cold!\n"; } return 0; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream> using namespace std; int main() { double temp = 0; cout << "Enter a temperature: "; cin >> temp; if (temp > 75) { // first condition cout << "That's too hot!\n"; } else if (temp > 65) { // next condition cout << "That's just right.\n"; } else { // default condition cout << "That's cold!\n"; } return 0; }
if (temp > 75) { // first condition cout << "That's too hot!\n"; } else { if (temp > 65) { // next condition cout << "That's just right.\n"; } else { // default condition cout << "That's cold!\n"; } }
if (temp > 75) { // first condition cout << "That's too hot!\n"; } else if (temp > 65) { // next condition cout << "That's just right.\n"; } else { // default condition cout << "That's cold!\n"; }
&&
temp >= 65
temp <= 75
(temp >= 65) && (temp <= 75)
||
temp < 65
temp > 75
(temp < 65) || (temp > 75)
!
temp
!((temp < 65) || (temp > 75))
if ((temp >= 65) && (temp <= 75)) {
if (temp >= 65 && temp <= 75) {
#include <iostream> using namespace std; int main() { double temp = 0; cout << "Enter a temperature: "; cin >> temp; if (temp >= 65 && temp <= 75) { cout << "That's just right.\n"; } else { cout << "That's uncomfortable!\n"; } return 0; }
=
if (guess = 7) { cout << "*** Correct! ***\n"; } else { cout << "Sorry, that is not correct.\n"; }
guess.cpp: In function `int main()': guess.cpp:10: warning: suggest parentheses around assignment used as truth value
if (7 = guess) {
guess.cpp: In function `int main()': guess.cpp:10: error: non-lvalue in assignment
if (7 == guess) {
int a = 5, b = 1, c = 10; if (a < b < c) { cout << "b is between a and c\n"; } else { cout << "b is NOT between a and c\n"; }
int a = 5, b = 1, c = 10; if (a < b && b < c) { cout << "b is between a and c\n"; } else { cout << "b is NOT between a and c\n"; }
int guess; cout << "Enter a guess: "; cin >> guess; if (guess == 7 || 8) { cout << "*** Correct! ***\n"; } else { cout << "Sorry, that is not correct.\n"; }
int guess; cout << "Enter a guess: "; cin >> guess; if (guess == 7 || guess == 8) { cout << "*** Correct! ***\n"; } else { cout << "Sorry, that is not correct.\n"; }
! && ||
(temp >= 65) && (temp <= 75) (temp < 65) || (temp > 75) !((temp < 65) || (temp > 75))
if (guess = 7) {
if (a < b < c) {
if (a < b && b < c) {
if (guess == 7 || 8) {
if (guess == 7 || guess == 8) {
In this exercise we use multiple test conditions in a program.
A student's letter grade is calculated according to the following table:
Numerical Grade Letter Grade greater than or equal to 90 A less than 90 but greater than or equal to 80 B less than 80 but greater than or equal to 70 C less than 70 but greater than or equal to 60 D less than 60 F
grader.cpp
#include <iostream> using namespace std; int main() { double score; cout << "Enter a score: "; cin >> score; // Insert statements here return 0; }
while do-while for
//Initialization ... while (condition) { //loop termination condition //loop body ... }
(condition)
condition
#include <iostream> using namespace std; int main() { char answer = 'y'; while (answer == 'y') { cout << "\nPlaying an exciting game!\n"; cout << "Do you want to play again? (y/n) "; cin >> answer; } cout << "\nThanks for playing!\n"; return 0; }
In this exercise we use a loop to allow a user to repeat a program.
add.cpp
#include <iostream> using namespace std; int main() { double num1, num2; cout << "First number: "; cin >> num1; cout << "Second number: "; cin >> num2; cout << num1 << " + " << num2 << " = " << num1 + num2 << endl; return 0; }
Due Next: A3: Conversions (3/1/07) Exercise 3 and CodeLab Lesson 3 (3/1/07) A4: Clothing Sizer (3/8/07) Exercise 4 and CodeLab Lesson 4 (3/8/07)