1 / 71

C++ Programming I Lecture 2

C++ Programming I Lecture 2. MIS160 Instructor – Larry Langellier. Outline

leena
Télécharger la présentation

C++ Programming I Lecture 2

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. C++ Programming I Lecture 2 MIS160 Instructor – Larry Langellier

  2. Outline 2.1Introduction2.2Algorithms 2.3Pseudocode 2.4Control Structures 2.5 The if Selection Structure 2.6The if/else Selection Structure 2.7The while Repetition Structure 2.8 Formulating Algorithms: Case Study 1(Counter-Controlled Repetition)2.9Formulating Algorithms with Top-Down,Stepwise Refinement:Case Study 2 (Sentinel-Controlled Repetition) 2.10 Formulating Algorithms with Top-Down, Stepwise Refinement:Case Study 3 (Nested Control Structures)2.11 Assignment Operators 2.12 Increment and Decrement Operators 2.13 Essentials of Counter-Controlled Repetition Lecture 2 - Control Structures

  3. Introduction • Before writing a program: • Have a thorough understanding of problem • Carefully plan your approach for solving it • While writing a program: • Know what “building blocks” are available • Use good programming principles

  4. Algorithms • All computing problems • can be solved by executing a series of actions in a specific order • Algorithm • A procedure determining the • Actions to be executed • Order in which these actions are to be executed • Program control • Specifies the order in which statements are to executed

  5. Pseudocode • Pseudocode • Artificial, informal language used to develop algorithms • Similar to everyday English • Not actually executed on computers • Allows us to “think out” a program before writing the code for it • Easy to convert into a corresponding C++ program • Consists only of executable statements

  6. Control Structures • Sequential execution • Statements executed one after the other in the order written • Transfer of control • When the next statement executed is not the next one in sequence • Bohm and Jacopini: all programs written in terms of 3 control structures • Sequence structure • Built into C++. Programs executed sequentially by default. • Selection structures • C++ has three types - if, if/else, and switch • Repetition structures • C++ has three types - while, do/while, and for

  7. Control Structures • C++ keywords • Cannot be used as identifiers or variable names.

  8. Control Structures • Flowchart • Graphical representation of an algorithm • Drawn using certain special-purpose symbols connected by arrows called flowlines. • Rectangle symbol (action symbol) • Indicates any type of action. • Oval symbol • indicates beginning or end of a program, or a section of code (circles). • single-entry/single-exit control structures • Connect exit point of one control structure to entry point of the next (control-structure stacking). • Makes programs easy to build.

  9. The if Selection Structure • Selection structure • used to choose among alternative courses of action • Pseudocode example: If student’s grade is greater than or equal to 60 Print “Passed” • If the condition is true • print statement executed and program goes on to next statement • If the condition is false • print statement is ignored and the program goes onto the next statement • Indenting makes programs easier to read • C++ ignores whitespace characters

  10. The if Selection Structure (cont.) • Used to choose between two alternatives • Syntax 1: if (condition) statement; • Syntax 2: if (condition) { statement1; statement2; statement3; } • Example – ifdemo.cpp

  11. The if Selection Structure • Translation of pseudocode statement into C++: if ( grade >= 60 ) cout << "Passed"; • Diamond symbol (decision symbol) • indicates decision is to be made • Contains an expression that can be true or false. • Test the condition, follow appropriate path • if keyword is followed by a test expression (in parenthesis) • The body executes once if the test expression is true - and not at all if it is false. • Multiple Statements in the if body are contained in braces • Example – if2.cpp

  12. A decision can be made on any expression. zero - false nonzero - true Example: 3 - 4 istrue true false print “Passed” grade >= 60 The if Selection Structure • Flowchart of pseudocode statement

  13. Let’s Do It Together! Write a temperature conversion program that gives the user the option of converting Fahrenheit to Celsius or Celsius to Fahrenheit. Then carry out the conversion. Use floating-point numbers. Interaction with the program might look like this: Type 1 to convert Fahrenheit to Celsius 2 to convert Celsius to Fahrenheit: 1 Enter temperature in Fahrenheit: 70 In Celsius that’s 21.111111

  14. Pseudocode Sample Prompt the user to select a conversion type If the user enters a “1” Input a Fahrenheit temperature Convert from Fahrenheit to Celsius Print the converted result If the user enters a “2” Input a Celsius temperature Convert from Celsius to Fahrenheit Print the converted result

  15. Sample Solution // ex3_2.cpp #include <iostream> int main() { int response; double temper; std::cout << "\nType 1 to convert fahrenheit to celsius,“ << "\n 2 to convert celsius to fahrenheit: "; std::cin >> response; if (response == 1) { std::cout << "Enter temperature in fahrenheit: "; std::cin >> temper; std::cout << "In celsius that's " << 5.0/9.0*(temper-32.0); } if (response == 2) { std::cout << "Enter temperature in celsius: "; std::cin >> temper; std::cout << "In fahrenheit that's " << 9.0/5.0*temper + 32.0; } std::cout << endl; return 0; }

  16. The if/else Selection Structure • if • Only performs an action if the condition is true • if/else • A different action is performed when condition is true and when condition is false • Psuedocode if student’s grade is greater than or equal to 60print “Passed” else print “Failed” • C++ code if ( grade >= 60 ) cout << "Passed";else cout << "Failed";

  17. false true print “Passed” print “Failed” grade >= 60 The if/else Selection Structure • Ternary conditional operator (?:) • Takes three arguments (condition, value if true, value if false) • Our pseudocode could be written: cout << ( grade >= 60 ? “Passed” : “Failed” );

  18. The if…else Statement • Do one thing if a condition is true, another if false • Syntax 1: Syntax 2: if (condition)if (condition) statement; { elsestatement; statement; statement; } else { statement; statement; } • Example – ifelse.cpp

  19. The if/else Selection Structure • Nested if/else structures • Test for multiple cases by placing if/else selection structures inside if/else selection structures. if student’s grade is greater than or equal to 90 Print “A”else if student’s grade is greater than or equal to 80 Print “B” else if student’s grade is greater than or equal to 70 Print “C” else if student’s grade is greater than or equal to 60 Print “D” else Print “F” • Once a condition is met, the rest of the statements are skipped

  20. The if/else Selection Structure • Compound statement: • Set of statements within a pair of braces • Example: if ( grade >= 60 ) cout << "Passed.\n"; else { cout << "Failed.\n"; cout << "You must take this course again.\n";} • Without the braces, cout << "You must take this course again.\n"; would be automatically executed • Block • Compound statements with declarations • Examples • adifelse.cpp • Matching the else – badelse.cpp • The else…if construction – adelseif.cpp

  21. The if/else Selection Structure • Syntax errors • Errors caught by compiler • Logic errors • Errors which have their effect at execution time • Non-fatal logic errors • program runs, but has incorrect output • Fatal logic errors • program exits prematurely

  22. Just Do It! Create the equivalent of a four-function calculator. The program should request the user to enter a number, an operator, and another number. (Use floating-point.) It should then carry out the specified arithmetic operation: adding, subtracting, multiplying, or dividing the two number. Use if/else statements to select the operation. Finally, display the result. Some sample interaction with the program might look like this: Enter first number, operator, second number: 10 / 3 Answer = 3.333333

  23. Sample Pseudocode Prompt the User for Input Read the Input If operator is ‘+’ answer = num1 + num2 Else if operator is ‘-’ answer = num1 – num2 Else if operator is ‘*’ answer = num1 * num2 Else answer = num1 / num2 Print answer

  24. Sample Solution // ex3_4.cpp #include <iostream> int main() { double n1, n2, ans; char oper, ch; std::cout << "\nEnter first number, operator, second number: "; std::cin >> n1 >> oper >> n2; if (oper == '+') ans = n1 + n2; else if (oper == '-') ans = n1 - n2; else if (oper == '*') ans = n1 * n2; else if (oper == '/') ans = n1 / n2; std::cout << "Answer = " << ans; return 0; }

  25. The while Repetition Structure • Repetition structure • Programmer specifies an action to be repeated while some condition remains true • Psuedocode while there are more items on my shopping list Purchase next item and cross it off my list • while loop repeated until condition becomes false. • Example int product = 2; while ( product <= 1000 ) product = 2 * product;

  26. true product <= 1000 product = 2 * product false The while Repetition Structure • Flowchart of while loop

  27. The while Repetition Structure • Use when you don’t know in advance how many times a loop needs to execute • Executes as long as the test expression is true • Example – endon0.cpp • Syntax 1: while (test_expression) statement; • Syntax 2: while (test_expression) { statement1; statement2; statement3; }

  28. Multiple Statements in Loop Body • Delimited by braces – ‘{ }’ • Multiple statements are contained within the braces, each ends with a ; • Example – cubelist.cpp • Variables contained with a block of code (a loop body with several statements enclosed by braces) are visible only within the block • Example – while4.cpp

  29. Indentation and Loop Style • Loop body should be indented right (3-4 spaces) • Typical Style: int numb=1; while (numb <=10) { std::cout << setw(4) << numb; int cube = numb * numb * numb; std::cout << setw(6) << cube << endl; numb++; }

  30. Formulating Algorithms (Counter-Controlled Repetition) • Counter-controlled repetition • Loop repeated until counter reaches a certain value. • Definite repetition • Number of repetitions is known • Example A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz.

  31. Formulating Algorithms (Counter-Controlled Repetition) • Pseudocode for example: Set total to zero Set grade counter to one While grade counter is less than or equal to ten Input the next grade Add the grade into the total Add one to the grade counter Set the class average to the total divided by tenPrint the class average • Following is the C++ code for this example

  32. 1 // Fig. 2.7: fig02_07.cpp 2 // Class average program with counter-controlled repetition 3 #include <iostream> 4 5 using std::cout; 6 using std::cin; 7 using std::endl; The counter gets incremented each time the loop executes. Eventually, the counter causes the loop to end. 8 9 int main() 10 { 11 int total, // sum of grades 12 gradeCounter, // number of grades entered 13 grade, // one grade 14 average; // average of grades 15 16 // initialization phase 17 total = 0; // clear total 18 gradeCounter = 1; // prepare to loop 19 20 // processing phase 21 while ( gradeCounter <= 10 ) { // loop 10 times 22 cout << "Enter grade: "; // prompt for input 23 cin >> grade; // input grade 24 total = total + grade; // add grade to total 25 gradeCounter = gradeCounter + 1; // increment counter 26 } 27 28 // termination phase 29 average = total / 10; // integer division 30 cout << "Class average is " << average << endl; 31 32 return 0; // indicate program ended successfully 33 } 1. Initialize Variables 2. Execute Loop 3. Output results

  33. Enter grade: 98 Enter grade: 76 Enter grade: 71 Enter grade: 87 Enter grade: 83 Enter grade: 90 Enter grade: 57 Enter grade: 79 Enter grade: 82 Enter grade: 94 Class average is 81 Program Output

  34. Just Do It! Write a program that calculates how much money you’ll end up with if you invest an amount of money at a fixed interest rate, compounded yearly. Have the user furnish the initial amount, the number of years and the yearly interest rate in percent. Some interaction with the program might look like this: Enter initial amount: 3000 Enter number of years: 10 Enter interest rate (percent per year): 5.5 At the end of 10 years, you will have 5124.43 dollars At the end of the first year you have 3000 + (3000 * 0.055), which is 3165. At the end of the second year you have 3165 + (3165 * 0.055), which is 3339.08. Do this as many times as there are years. A while loop makes the calculation easy.

  35. Sample Pseudocode Prompt for and get the initial amount, number of years and interest rate While current year is less than total number of years Add interest to the current total Increment the current year Print the final amount

  36. Sample Solution // interest.cpp // calculates final amount if initial amount invested // at simple interest 'rate' for 'years' years #include <iostream> int main() { float amount=0.0, rate; int years; std::cout << "Enter initial amount: "; std::cin >> amount; std::cout << "Enter number of years: "; std::cin >> years; std::cout << "Enter rate (percent per year): "; std::cin >> rate; int p=0; while (p<years) { amount += amount*rate/100; p++; } std::cout << "Final amount is " << amount << endl; return 0; }

  37. Formulating Algorithms with Top-Down, Stepwise Refinement (Sentinel-Controlled Repetition) • Suppose the problem becomes: Develop a class-averaging program that will process an arbitrary number of grades each time the program is run. • Unknown number of students - how will the program know to end? • Sentinel value • Indicates “end of data entry” • Loop ends when sentinel inputted • Sentinel value chosen so it cannot be confused with a regular input (such as -1 in this case)

  38. Formulating Algorithms with Top-Down, Stepwise Refinement (Sentinel-Controlled Repetition) • Top-down, stepwise refinement • begin with a pseudocode representation of the top: Determine the class average for the quiz • Divide top into smaller tasks and list them in order: Initialize variables Input, sum and count the quiz grades Calculate and print the class average

  39. Formulating Algorithms with Top-Down, Stepwise Refinement • Many programs can be divided into three phases: • Initialization • Initializes the program variables • Processing • Inputs data values and adjusts program variables accordingly • Termination • Calculates and prints the final results. • Helps the breakup of programs for top-down refinement. • Refine the initialization phase from Initialize variables to Initialize total to zero Initialize counter to zero

  40. Formulating Algorithms with Top-Down, Stepwise Refinement • Refine Input, sum and count the quiz grades to Input the first grade (possibly the sentinel) While the user has not as yet entered the sentinel Add this grade into the running total Add one to the grade counter Input the next grade (possibly the sentinel) • Refine Calculate and print the class average to If the counter is not equal to zero Set the average to the total divided by the counter Print the average Else Print “No grades were entered”

  41. 1 // Fig. 2.9: fig02_09.cpp 2 // Class average program with sentinel-controlled repetition. Data type double used to represent decimal numbers. 3 #include <iostream> 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 using std::ios; 9 10 #include <iomanip> 11 12 using std::setprecision; 13 using std::setiosflags; 14 15 int main() 16 { 17 int total, // sum of grades 18 gradeCounter, // number of grades entered 19 grade; // one grade 20 double average; // number with decimal point for average 21 22 // initialization phase 23 total = 0; 24 gradeCounter = 0; 25 26 // processing phase 27 cout << "Enter grade, -1 to end: "; 28 cin >> grade; 29 30 while ( grade != -1 ) { 1. Initialize Variables 2. Get user input 2.1 Perform Loop

  42. 31 total = total + grade; static_cast<double>() - treats total as a double temporarily. Required because dividing two integers truncates the remainder. gradeCounter is an int, but it gets promoted to double. 32 gradeCounter = gradeCounter + 1; 33 cout << "Enter grade, -1 to end: "; 34 cin >> grade; 35 } setiosflags(ios::fixed | ios::showpoint)- stream manipulator ios::fixed - output numbers with a fixed number of decimal points. ios::showpoint - forces decimal point and trailing zeros, even if unnecessary: 66 printed as 66.00 | - separates multiple option. 36 37 // termination phase 38 if ( gradeCounter != 0 ) { setprecision(2)- prints only two digits past decimal point. Programs that use this must include <iomanip> 39 average = static_cast< double >( total ) / gradeCounter; 40 cout << "Class average is " << setprecision( 2 ) 41 << setiosflags( ios::fixed | ios::showpoint ) 42 << average << endl; 43 } 44 else 45 cout << "No grades were entered" << endl; 46 47 return 0; // indicate program ended successfully 48 } 3. Calculate Average 3.1 Print Results Program Output Enter grade, -1 to end: 75 Enter grade, -1 to end: 94 Enter grade, -1 to end: 97 Enter grade, -1 to end: 88 Enter grade, -1 to end: 70 Enter grade, -1 to end: 64 Enter grade, -1 to end: 83 Enter grade, -1 to end: 89 Enter grade, -1 to end: -1 Class average is 82.50

  43. Type Conversion • C++ will automatically convert numbers of different types – lower will be converted to higher – when used in mathematic operations (+, -, *, /, etc.) and assigning values to variables • Data Type Order • long double Highest • double • float • long • int • short • char Lowest • Example - mixed.cpp

  44. Casts • A cast is a data conversion specified by the programmer • Also known as coercion • Syntax static_cast<data_type>(aVar) • Example char aCharVar; int anIntVar; aCharVar = static_cast<char>(anIntVar); • Example - cast.cpp

  45. Output Formatting • Formatting Numbers • In past labs we’ve seen some manipulators for formatting numeric output • setiosflags(ios::fixed) – don’t show exponential notation • setiosflags(ios::showpoint) – show the decimal point • setprecision(2) – always two decimal places • These manipulators can be chained to a cout with the insertion operator (<<) and should be done BEFORE you output the number to be formatted • Once set, the setting remain until changed • To turn a setting off, use resetiosflags

  46. Let’s Do It Together! Write another version of the prior “Let’s Do It Together!” Instead of finding the final amount of your investment, you tell the program the initial amount, the final amount and the annual interest rate and it figures out how many years it will take to reach this amount.

  47. Sample Pseudocode Prompt for the initial amount, final amount and interest rate Read User Inputs While the current amount is less than the target amount Add interest increment the number of years Print the number of years

  48. Sample Solution // periods.cpp #include <iostream> int main() { float initial, final, amount, rate; int years =0 ; std::cout << "Enter initial amount: "; std::cin >> initial; std::cout << "Enter final amount: "; std::cin >> final; std::cout << "Enter rate (percent per year): "; std::cin >> rate; amount = initial; while (amount < final) { amount += amount*rate/100; years++; } std::cout << "Number of years is " << years << endl; return 0; }

  49. Nesting ifs Inside Loops • Nesting means one statement is contained within another • ifs inside loops • Loops inside ifs • ifs inside ifs • Loops inside loops • Example – prime.cpp • Library Function – exit(retval) • Causes the program to terminate • Returns it’s single value to the operating system • 0 typically indicates successful termination

  50. Nested control structures • Problem: A college has a list of test results (1 = pass, 2 = fail) for 10 students. Write a program that analyzes the results. If more than 8 students pass, print "Raise Tuition". • We can see that • The program must process 10 test results. A counter-controlled loop will be used. • Two counters can be used—one to count the number of students who passed the exam and one to count the number of students who failed the exam. • Each test result is a number—either a 1 or a 2. If the number is not a 1, we assume that it is a 2. • Top level outline: Analyze exam results and decide if tuition should be raised

More Related