Presentation is loading. Please wait.

Presentation is loading. Please wait.

# ACS 168 Structured Programming Using the Computer Chapter 2 Spring 2002 Prepared by Shirley White.

Similar presentations


Presentation on theme: "# ACS 168 Structured Programming Using the Computer Chapter 2 Spring 2002 Prepared by Shirley White."— Presentation transcript:

1 # ACS 168 Structured Programming Using the Computer Chapter 2 Spring 2002 Prepared by Shirley White

2 2 2.4 Simple Flow of Control A simple branching mechanism The order in which statements are executed is often called flow of control. There are two flow control types: selection and looping. Selection chooses between alternative actions. Looping repeats an action for some period of time. (Looping will be discussed later.)

3 3 Selection Syntax and Example if (expression) Control Expression returns a bool value action1; Affirmative clause. Executed if bool is true else action2; Negative clause. Executed if bool is false Example: if (num_elements > 10) cout<<“There are more than 10 elements in the set.\n”; else cout<<“The set has 10 or fewer elements.\n”;

4 4 Comparison Operators C++ provides comparison operators for making decisions in computer programs. These operators return a value of type bool: true or false. Math C++ C++ Math Symbol English Notation Sample Equivalent = equal to == x + 7 == 2 * y x + 7 = 2y  not equal to != ans != ‘n’ ans  ‘n’ < less than < count < m + 3 cout < m + 3  less than <= time <= limit time  limit or equal to > greater than > time > limit time > limit  greater than >= age >= 21 age  21 or equal to

5 5 Logical Operators The ‘and’ operator && Syntax: (Comparison_1) && (Comparison_2) Example, in an assignment to a bool variable: bool in_range; in_range = (0 < score) && (10 < score); The ‘or’ operator || Example -- in an if-else statement if ( (x ==1) || (x == y) ) cout << “x is 1 or x equals y. \n”; else cout < “x is neither 1 nor equal to y.\n”;

6 6 PITFALL: strings of inequalities Suppose x, y and z are integer values. if (x < y < z) // Unfortunately, this is WRONG BUT IT COMPILES. cout << “y is between x and z” ; Here is why the expression is WRONG. In mathematics x < y < z is short hand for x < y && y < z. In C++, this is not true. It is still valid C++, but isn’t what you expect from the mathematics. In C++ the precedence rules require x < y < z be evaluated like this: (x < y) < z The parenthesized expression returns a bool value. The < requires the same type on both sides. The bool value gets converted to the int value 0 (for false) or 1 (for true). Then 0 <z or 1 < z compiles. And gives (most of the time) a wrong answer!

7 7 PITFALL: using = instead of == if (x = 12) // Note: The = should have been == cout << “x is equal to 12”; else cout << “x is not equal to 12”; The second expression is NEVER executed, regardless of the value of x before this statement is encountered. WORSE, after this if statement executes, the expression x = 12 HAS ASSIGNED the value 12 to x. Why? The expression x = 12 returns the value 12, which is converted to the bool value true, which is used by the if. Either write x == 12 or 12 == x: if (12 == x) // Compiler will issue warning “non-lvalue on left” cout << “x is equal to 12”; else cout << “x is not equal to 12”;

8 8 Simple Loop Mechanisms Most programs include a mechanism to repeat a block of code multiple times: 30 Students: grade program receives 30 grades on each assignment; 100 workers: pay check generator runs 100 times each pay period C++ provides loops named while for do while The piece of code the loop executes is called the body. Each loop execution of the body is called an iteration.

9 9 Display 2.10 A while loop #include using namespace std; int main( ) { int count_down; cout << "How many greetings do you want? "; cin >> count_down; while (count_down > 0) { cout << "Hello "; count_down = count_down - 1; } cout << endl; cout << "That's all!\n"; return 0; }

10 10 Display 2.13 A do-while loop #include using namespace std; int main( ) { char ans; do { cout << "Hello\n"; cout << "Do you want another greeting?\n" << "Press y for yes, n for no,\n" << "and then press return: "; cin >> ans; } while (ans == 'y' || ans == 'Y'); cout << "Good-Bye\n"; return 0; }

11 11 Pitfall: Stray semicolons Loop body with several statements while(bool expression) Do not put a semicolon here { This usually causes an several statements infinite loop. (Next section) } Loop body with one statement while(bool expression) statement;

12 12 Pitfall: Stray semicolons Loop body with several statements do { several statements } while(bool expression); Don’t forget the semicolon here. Loop body with one statement do statement; while(bool expression); Don’t forget the semicolon here.

13 13 PITFALL: Infinite Loops Any loop in which the Boolean control expression remains true will never terminate. A loop that does not terminate is called an infinite loop. Infinite loops cause errors that can be hard to find. Examples: This loop terminates: This is an infinite loop: x = 2; x = 1; while (x != 12) { cout << x << endl; cout << x << endl; x = x + 2; x = x + 2; } WHY?

14 14 Display 2.14 Charge Card Program #include using namespace std; int main( ) { double balance = 50.00; int count = 0; cout << "This program tells you how long it takes\n" << "to accumulate a debt of $100, starting with\n" << "an initial balance of $50 owed.\n" << "The interest rate is 2% per month.\n"; while (balance < 100.00) { balance = balance + 0.02 * balance; count++; } cout << "After " << count << " months,\n"; cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); cout << "your balance due will be $" << balance << endl; return 0; }

15 15 2.5 Programming Style: Comments Learning to properly comment code is not as easy as it seems. A comment should always tie the code to the problem being solved. In some circumstances, a comment could explain ‘tricky’ code. (It is better to write clear code and omit the comment.) /* comment in this style */ may span more than one line. // these comments run from the // to the end of the line. The text uses the // style comments exclusively. If you do this too, then you can use /*comments*/ to comment out code while developing programs.

16 16 Indenting Elements considered a group should be indented to look like a group. if-else, while, and do-while loops should be indented as in the sample code. The affirmative clause and negative clause of if-else statements should be indented more than surrounding code. The body of loops should be indented more than surrounding code. CONSISTENCY of style is more important than any particular style standard.

17 17 Program header comments Comments should be placed at the start of the program that describes the essential information about the program: The file name The author The address or other means to contact the author The purpose of the program What the program does The date written or version number

18 18 Naming Constants Do not hard-code numbers into your program that are likely to change. Example: You are writing a program that calculates sales tax on purchases. If the tax rate is 4% (0.04) today, it will go up. When it does increase, you have to search the entire program for each use of 0.04, decide if it is a tax rate, then replace it by the new tax rate, 0.05. This is very time consuming. If you use declared constants the change will only be required in ONE place (the declaration). Constants can be declared in two ways: const int BRANCH_COUNT = 10; or #define BRANCH_COUNT 10

19 19 Summary (1 of 2) Use meaningful names for variables. Check that variables have been declared before use, and have the correct data type. Be sure each variable has a value before use. This can be done by initialization at definition, or by assigning a value before first use. Use enough parentheses to make the order of operations clear. Remember, code is meant to be read, which implies writing for an audience. Always have your program prompt the user for expected input. Always echo user’s input. An if-else statement chooses between two blocks of code to execute. An if statement chooses whether to execute a block of code.

20 20 Summary (2 of 2) A do-while always executes its body at least once. A while loop may not execute its body at all. Numeric constants should be given meaningful names to be used instead of the numbers. Use the const modifier to do this within the code or #define in the global area. Use indenting, spacing, and line break patterns similar to the sample code to group sections of code such as the body of a while statement, or the affirmative and negative clauses of an if-else statement. Insert commentary to explain major subsections of your code, or to explain any unclear part of your program. Make your code clear. Remember, a program is meant to be read by programmers, not just compilers.


Download ppt "# ACS 168 Structured Programming Using the Computer Chapter 2 Spring 2002 Prepared by Shirley White."

Similar presentations


Ads by Google