Programming C++
Programming C++
Programming C++
// custom countdown using while #include <iostream> int main () { int n; cout << "Enter the starting number > "; cin >> n; while (n>0) { cout << n << ", "; --n; } cout << "FIRE!\n"; return 0; }
// do while loop #include <iostream> int main () { unsigned long n; do { cout << "Enter number (0 to end): "; cin >> n; cout << "You entered: " << n << "\n"; } while (n != 0); }
12/2/2011
It works in the following way: 1. initialization is executed. Generally it is an initial value setting for a counter variable. This is executed only once. 2. condition is checked. If it is true the loop continues, otherwise the loop ends and statement is skipped (not executed). 3. statement is executed. As usual, it can be either a single statement or a block enclosed in braces { }. 4. finally, whatever is specified in the increase field is executed and the loop gets back to step 2.
// countdown using a for loop #include <iostream> int main () { for (int n=10; n>0; n--) { cout << n << ", "; } cout << "FIRE!\n"; return 0; }
EXERCISE
1. Write a program that asks the user to type an integer and writes "YOU WIN" if the value is between 56 and 78 (both included). In the other case it writes "YOU LOSE". 2. Write a program that asks the user to type the integers between 8 and 23 (both included). 3. Write a program that asks the user to type 10 integers and writes the sum of these integers. 4. Write a program that asks the user to type 10 integers and writes the smallest value.
12/2/2011
6. Alter above program so that if "another_age" works out to be more than 150, the screen output is: Sorry, but you'll probably be dead by [year]!
Jump statements
The break statement Using break we can leave a loop even if the condition for its end is not fulfilled.
// break loop example #include <iostream.h> int main () { int n; for (n=10; n>0; n--) { cout << n << ", "; if (n==3) { cout << "countdown aborted!"; break; } } return 0; }
12/2/2011
The selective structure: switch. Its objective is to check several possible constant values for an expression.
switch (expression) { case constant1: group of statements 1; break; case constant2: group of statements 2; break; . . . default: default group of statements } switch example switch (x) { case 1: cout << "x is 1"; break; case 2: cout << "x is 2"; break; default: cout << "value of x unknown"; } if-else equivalent if (x == 1) { cout << "x is 1"; } else if (x == 2) { cout << "x is 2"; } else { cout << "value of x unknown"; }