1 / 58

CS208 C++ Programming

CS208 C++ Programming. Part 2. Boolean Expressions. A boolean expression is a condition in which a relational operator tests the relationship between two expressions and returns a boolean (TRUE or FALSE) result. Syntax for condition: (<expr> <relop> <expr>).

owen-ross
Download Presentation

CS208 C++ Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CS208 C++ Programming Part 2

  2. Boolean Expressions A boolean expression is a condition in which a relational operator tests the relationship between two expressions and returns a boolean (TRUE or FALSE) result. • Syntax for condition: (<expr> <relop> <expr>)

  3. Algebraic vs C++Equality & Relational Operators NOTE that “=“ is for assignment and “==“ is for equality comparison

  4. Decisions • Boolean expressions are used to make decisions • The expression is evaluated to TRUE or FALSE • Example: • Given the boolean expression: ( num < 5 ) • When num = 1, the expression evaluates to TRUE • When num = 25, the expression evaluates to FALSE

  5. The if Statement Syntax: One Alternative if (condition) statementT; //do the statement if condition is TRUE Two Alternatives if (condition) statementT; // do only this if TRUE else statementF ;// do only this if FALSE

  6. The condition must be a boolean expression. It must be enclosed in parentheses. It must evaluate to either true or false. if is a C++ reserved word The statement is indented. If the condition is TRUE, the statement is executed. If it is FALSE, the statement is skipped. One Alternative if Statement if ( condition ) statement;

  7. grade over 60? true display "Passed" false One Alternative if Control Structure English: if student’s grade is greater than 60, display "Passed" Code:if (grade > 60) cout << "Passed";

  8. One Alternative if Examples if (age < 18) cout << "Minor"; if (divisor != 0) answer = num / divisor; if (num < 10) num = num + 1;

  9. One Alternative if Program Description • Modify previous Age program (from part 1) to take into account the current MONTH, as well as the current YEAR. • Read in the user’s birth MONTH and birth YEAR • Calculate and display the user’s age

  10. Age Program Design • What are the program inputs? • Year and Month of Birth needs variables • What are the program outputs? • Age needs a variable • Are there any values the programmer will set? • Current year and month needs constants

  11. Age Program Algorithm • Pseudocode: • Prompt for and read in user’s year of birth • Prompt for and read in user’s month of birth • Compute user’s age • If birth month has not yet passed, • Subtract one from user’s age • Display user’s age

  12. Age Program Code #include <iostream> using namespace std; int main() { const int NOW_YR = 2006; const int LAST_MON = 8; int birthYr, birthMon, age; cout << "Enter 4-digit year of birth: "; cin >> birthYr; cout << "Enter numeric month of birth: "; cin >> birthMon; age = NOW_YR - birthYr; if (birthMon > LAST_MON) age = age – 1; cout << "Your age is " << age; return 0; }

  13. Memory age: birthYr: birthMon: NOW_YR: 2006 LAST_MON: 8 Age Program Explanation (1/3) const int NOW_YR = 2006; const int LAST_MON = 8; /* declare two constants, NOW_YR and LAST_MON */ int birthYr, birthMon, age; /* declare 3 integer variables, birthYr, birthMon and age */

  14. Memory age: birthYr: birthMon: NOW_YR: 2006 LAST_MON: 8 Age Program Explanation (2/3) cout << "Enter 4-digit year of birth: "; cin >> birthYr; /* display prompt, and read value entered into birthYr */ Screen: Enter 4-digit year of birth: 1962 Enter numeric month of birth: 9 cout << "Enter numeric month of birth: "; cin >> birthMon; /* display prompt, and read value entered into birthMon */ 1962 9

  15. Memory age: 1962 birthYr: 9 birthMon: Screen: Enter 4-digit year of birth: 1962 NOW_YR: 2006 9 LAST_MON: 8 Age Program Explanation (3/3) age = NOW_YR - birthYr; /* subtract value in birthYr from value in NOW_YR; store result into variable age */ 43 44 if (birthMon > LAST_MON) age = age – 1; /* test to see if birthMon is greater than LAST_MON if so, subtract 1 from value in variable age */ cout << "Your age is " << age; // display message and calculated age Enter numeric month of birth: Your age is 43

  16. The condition must be a boolean expression. It must be enclosed in parentheses. It must evaluate to either true or false. If the condition is TRUE, only statementT is executed. If it is FALSE, only statementF is executed. Two Alternative if Statement if ( condition ) statementT; else statementF;

  17. true grade over 60? false display “Failed” display “Passed”; Two Alternativeif-else Control Structure English: if students' grade is greater than 60, display "Passed“, otherwise display “Failed” Code:if (grade > 60) cout << "Passed"; else cout << "Failed";

  18. Two alternative if Examples if (num >= 0) cout << "Positive"; else cout << "Negative"; if (temp < 50) heater = 1; else heater = 0; if (MorD == 'M') cout << "Hi Mom!";else cout << "Hi Dad!";

  19. Two AlternativeProgram Example Description • At a gas station, there are two kinds of gas: regular unleaded and premium. Regular is $1.89 per gallon, and premium is $1.98 per gallon. • Design a program to read the type of gas and number of gallons from the user. The program should display the customer’s total bill for the gas.

  20. Gas Program Design • What are the program inputs? • Type of gas purchased needs a variable • Number of gallons purchased needs a variable • What are the program outputs? • Total cost needs a variable • Are there any values the programmer will set? • Regular price per gallon needs a constant • Premium price per gallon needs a constant • How do we calculate the output value? • Total cost = price per gallon X number of gallons formula

  21. Gas Program Algorithm • Pseudocode: • Prompt for and read in Type of Gas • Prompt for and read in Number of Gallons • If Type of Gas is Regular, • Compute Total using Regular Price • Otherwise • Compute Total using Premium Price • Display Total Cost

  22. Gas ProgramExample Code #include <iostream> using namespace std; int main() { const double REG = 1.89; const double PREM = 1.98; char gasType; double gallons, total; cout << "What type of gas (r/p)?: "; cin >> gasType; cout << "How many gallons? "; cin >> gallons; if (gasType == 'r') total = REG * gallons; else total = PREM * gallons; cout << "Total is " << total; return 0; }

  23. Memory gasType: gallons: total: REG: 1.89 PREM: 1.98 Gas Program Explanation (1/3) char gasType; double gallons, total; /* declare one character variable and two double variables */ const double REG = 1.89; const double PREM = 1.98; /* declare two constants */

  24. Memory gasType: gallons: total: REG: 1.89 PREM: 1.98 Gas Program Explanation (2/3) cout << " What type of gas (r/p)? "; cin >> gasType; /* display prompt, and read value entered into gasType */ Screen: What type of gas (r/p)? p How many gallons? 11.3 cout << " How many gallons? "; cin >> gallons; /* display prompt, and read value entered into gallons */ ‘p’ 11.3

  25. Memory ‘p’ 11.3 gasType: gallons: total: REG: 1.89 Screen: PREM: 1.98 What type of gas (r/p)? p How many gallons? 11.3 Gas Program Explanation (3/3) if (gasType == 'r') total = REG * gallons; else total = PREM * gallons; /* Test condition (gasType == ‘r’) In the example, the condition is FALSE, so the else statement is executed: Multiply value in constant PREM by value in variable gallons and store result in variable total */ 22.374 Total is 22.374 cout << "Total is " << total; // display message and the value in variable total

  26. Gas Program Modification • Problem -- The gas program output was: Total is 22.374 • But dollars and cents should be rounded to 2 decimal places • Add the following include statement at the top of the program: #include <iomanip> • And add the following line BEFORE the cout output statement: cout << fixed << setprecision(2); • The output will now be: Total is 22.37

  27. if Exercise Exercise: Write a program that reads in 2 integers and outputs the smallest. Sample Run: Enter 2 numbers: 99 8 Smallest number is 8 (Answer on next slide – try writing program yourself before looking at the answer)

  28. If Exercise Answer #include <iostream> using namespace std; int main() { int num1, num2; cout << "Enter 1st number: "; cin >> num1; cout << "Enter 2nd number: "; cin >> num2; if (num1 < num2) cout << "Smallest number is " << num1; else cout << "Smallest number is " << num2; return 0; }

  29. Compound Statements • A compound statement is more than one statement enclosed in { } • Branches of if-else statements often need to execute more that one statement • Example: if (boolean expression) {true statements} else { false statements}

  30. Loop Statements • Loop statements allow us to execute a program statement (or statements) multiple times • They are often simply referred to as loops • Like conditional if statements, they are controlled by boolean expressions • C++ has four kinds of loop statements, but in this class we will study only ONE of them: • the while loop

  31. The conditional while Loop Syntax:while (boolean-expression) { statement1; : statementN; } NOTE: - The curly braces {} are not needed if there is only ONE statement in the loop body

  32. The condition must be a boolean expression. It must be enclosed in parentheses. It must evaluate to either true or false. while is a C++ reserved word The statement(s) must be indented. If the condition is TRUE, the statement(s) within the curly braces are executed. If FALSE, the program skips to the statement FOLLOWING the loop statement(s). The while Statement while ( condition ) { statement1; : statementN; }

  33. amount under 100? true Add 1 to amount false while control structure English: while the amount is under 100, add 1 to the amount Code:while (amount < 100) amount = amount + 1;

  34. while Loop Example Example #1: Display a count by two’s to 100. #include <iostream> using namespace std; int main() { int num = 2; while (num <= 100) { cout << num << endl; num = num + 2; } cout << "Done!"; return 0; }

  35. Memory num: 2 Count by Twos Explanation (1/9) int num = 2; /* declare an integer variable, num, and initialize its value to 2 */

  36. Memory num: 2 Count by Twos Explanation (2/9) while (num <= 100) // Test the condition (num <= 100) /* In the example num is currently 2, so the condition is TRUE, meaning we will execute the statements between the curly braces. */

  37. Memory num: 4 Count by Twos Explanation (3/9) Execute the statements within the curly braces: cout << num << endl; /* Display value in variable num to screen Then output a newline, so the next output will appear on the next line*/ Screen: 2 num = num + 2; /* Add 2 to the value currently stored in variable num. Store the result back into the variable num*/ 2

  38. Memory num: 4 Count by Twos Explanation (4/9) Loop back to the top of the while loop: /* In the example num is currently 4, so the condition is still TRUE, meaning we will execute the statements between the curly braces again */ while (num <= 100) // Test the condition (num <= 100)

  39. Screen: 2 Memory num: 6 Count by Twos Explanation (5/9) Execute the statements within the curly braces: cout << num << endl; /* Display value in variable num to screen Then output a newline, so the next output will appear on the next line*/ 4 num = num + 2; /* Add 2 to the value currently stored in variable num. Store the result back into the variable num*/ 4

  40. Memory num: 100 Count by Twos Explanation (6/9) The program will continue looping back to the top of the while loop, testing the condition and executing the statements, UNTIL the condition evaluates to FALSE. So on the LAST loop: while (num <= 100) // Test the condition (num <= 100) /* In the example num is currently 100, so the condition is still TRUE, meaning we willexecute the statements between the curly braces again */

  41. Screen: 2 4 6 : 96 98 Memory num: 100 102 Count by Twos Explanation (7/9) Execute the statements within the curly braces: cout << num << endl; /* Display value in variable num to screen Then output a newline, so the next output will appear on the next line*/ 100 num = num + 2; /* Add 2 to the value currently stored in variable num. Store the result back into the variable num*/

  42. Memory num: 102 Count by Twos Explanation (8/9) Loop back to the top of the while loop: while (num <= 100) // Test the condition (num <= 100) /* In the example num is currently 102, so the condition is now FALSE, meaning we will SKIP the statements between the curly braces and exit the loop */

  43. Screen: 2 4 6 : 96 98 100 Count by Twos Explanation (9/9) Execute the statement after the while loop: cout << "Done!"; // Display Done! to the screen Done! return 0; Program Terminates.

  44. int num; cout << "Enter a positive number: "; cin >> num; while (num < 0) { cout << "Invalid entry. Try Again." << endl << endl; cout << "Positive number: "; cin >> num; } cout << "You entered " << num; Loop Example #2 Example #2: Error check a positive number is entered.

  45. Example #2 Output -1 Enter a positive Number: Invalid entry. Try again. -3 Positive Number: Invalid entry. Try again. Positive Number: 5 You entered 5

  46. while loop conditions • If the condition of a while loop is initially false, the loop statements in the loop are never executed • Therefore, the body of a while loop will execute zero or more times

  47. Example #2 Output Revisited 20 You entered 20 Enter a positive Number: In this case, the while loop condition: (num < 0) was initially FALSE because the user entered a positive number as the first number. So the while loop statements did NOT execute.

  48. Infinite Loops • The statements of a while loop must do something to eventually make the condition evaluate to false • If it doesn’t, you will have an infinite loop, which will execute until the user interrupts the program (with Ctrl-C ) • This is a common type of logical error • You should always double check to ensure that your loops will eventually terminate!

  49. Sample Run: Number? (or zero to end): 10 Number? (or zero to end): 20 Number? (or zero to end): 0 Total is 30 (Answer on next slide – Try first, then view answer) while Loop Exercise Exercise: Write a WHILE loop that will add a series of positive integers as they are entered by the user. Stop adding and display the total when the user enters a zero.

  50. while Loop Exercise Solution int num, sum; sum = 0; cout << "Number? (or zero to end): "; cin >> num; while (num >= 0) { sum = sum + num; cout << endl << "Number? (or zero to end): "; cin >> num; } cout << endl << "Total is " << sum;

More Related