Download presentation
Presentation is loading. Please wait.
1
Flow of Control October 16, 2017
2
Constants A declared constant is a variable whose value cannot be changed by the program. A constant is declared using the modifier const: const int WEEKDAYS = 5; const double PI = ; const string INITIALS = "BSC"; Standard practice is to write the name of a constant in all caps.
3
Arithmetic Shortcuts Some shortcuts besides x++ and x--:
x += 2; is the same as x = x + 2; x -= 3; is the same as x = x - 3; x *= 5; is the same as x = x * 5; x /= 4; is the same as x = x / 4; x %= 2; is the same as x = x % 2;
4
Switch Statements A switch statement is similar to a series of if-else statements, but in some cases is a simpler implementation. Every switch statement can be converted to an if-else statement, but not every if-else statement can be converted to a switch statement. A switch statement is declared with the syntax switch (variable), where variable is the name of a variable, followed by curly braces. Do not put a semicolon after switch (variable)! The different possibilities (branches) are denoted using case.
5
break Statements The break statement can also be used to exit a loop.
For instance, a break statement can end a loop if improper input is detected. Consider a program that asks the user to enter 10 negative numbers. A break statement can be used to end the loop if the user enters zero or a positive number.
6
break Statements int number, sum = 0, count = 1; while(count <= 10) { cin >> number; if(number >= 0) cout << "ERROR! Zero or positive number entered.\n"; break; } The break; statement above terminates the loop if a nonnegative number is entered.
7
Sentinel Values One way to allow the user to end a loop is through the use of a sentinel value. This refers to a value added at the end of a list that is distinct from the other possible values in the list.
8
Sentinel Values int number, sum = 0; cout << "Please enter a list of nonnegative integers.\n" << "Place a negative integer after the list.\n"; cin >> number; while(number >= 0) { sum = sum + number; }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.