# Introduction to Programming Introduction to Programming

### Pages to are hidden for

"Introduction to Programming Introduction to Programming"

```					         Introduction to Programming                                                                Introduction to Programming
Summer term 2009
Summer term 2009

5    More Statements

Andreas Hoffmann, Univ. Siegen
andreas.hoffmann@uni-siegen.de
Tel.: 0271/740-4047, Ofﬁce: H-B 8405
Stand: May 15, 2009

¨
Andreas Hoffmann / R. Wismuller / T. Kielmann                                                                                      ¨
Andreas Hoffmann / R. Wismuller / T. Kielmann
Betriebssysteme / verteilte Systeme                          Introduction to Programming     1       Betriebssysteme / verteilte Systeme                     Introduction to Programming   111

Repetition                                                                                          5 More Statements ...

Reminder: Functions                                                                                 Contents:
int maximum(int a, int b);                                                                          ¯ The switch statement                              (a “multi-if”)

int main() {                                                                                        ¯ Loops
int x = 5, y = 10;
¯ An example: prime numbers
cout << "Maximum of " << x << " and " << y << " is ";
cout << maximum(x, y) << endl;                                                                  ¯ Assertions
return 0;
}

int maximum(int a, int b) {
if ( a > b ) { return a; }
else { return b; }
}

¨
Andreas Hoffmann / R. Wismuller / T. Kielmann                                                                                      ¨
Andreas Hoffmann / R. Wismuller / T. Kielmann
Betriebssysteme / verteilte Systeme                          Introduction to Programming   110       Betriebssysteme / verteilte Systeme                     Introduction to Programming   112
5.1 The switch Statement                                                               5.1 The switch Statement ...

A Calculator – Multiple if Statements                                                  General form of a switch Statement
char command;   cin >> command;                                                        switch ( expression ) { // any C++ expression
if ( command == ’+’ ) {                                                                    case constant1 :      // test for equality
}                                                                                               break;           // leave the switch statement
else if ( command == ’-’ ) {                                                                                     // (optional)
subtract();                                                                              case constant2 :
}
case constant3 :
else if ( command == ’*’ ) {
statement-list ;
multiply();
break;
}
else if ( command == ’/’ ) {
default:              // handle everything else
divide();
statement-list ; // (optional)
}
break;
else {
cout << "unknown command\n’’;                                                        }
}
¨
Andreas Hoffmann / R. Wismuller / T. Kielmann                                                                         ¨
Andreas Hoffmann / R. Wismuller / T. Kielmann
Betriebssysteme / verteilte Systeme             Introduction to Programming   113       Betriebssysteme / verteilte Systeme             Introduction to Programming   115

5.1 The switch Statement ...                                                           5.1 The switch Statement ...

A Better Way: The switch Statement                                                     Quiz: What is the output?
char command;                                                                         int number;
cin >> command;                                                                       cin >> number;
switch ( command ) {                                                                  switch ( number ) {
case ’+’:     add();      break;                                                      case 0:
cout << "zero\n";
case ’-’:     subtract(); break;
case 1:
case ’*’:     multiply(); break;                                                      case 2:
case ’/’:     divide();   break;                                                        cout << "one or two\n";
default:                                                                                break;
cout << "unknown command\n’’;                                                       case 3:
break;                                                                                cout << "three\n";
}                                                                                       default:
cout << "not between zero and three\n";
}

¨
Andreas Hoffmann / R. Wismuller / T. Kielmann                                                                         ¨
Andreas Hoffmann / R. Wismuller / T. Kielmann
Betriebssysteme / verteilte Systeme             Introduction to Programming   114       Betriebssysteme / verteilte Systeme             Introduction to Programming   116
5.1 The switch Statement ...                                                           5.2 Loops ...

A Style-Guide for switch                                                               while Loops
¯ Use break (almost) always                                                            ¯ Syntax:
¯ If you do not use break, add a comment to show that you really                                while ( expression ) statement ;
mean it:
¯ Example:
case 1:
cout << "How many hello’s?\n";
do_something();
cin >> number;
// fall through
case 2:
while ( number > 0 ) {
cout << "Hello!\n";
// fall through
number--;
case 3:
}
do_what_is_needed_for_1_2_and_3();

¯ Always use a default clause to handle unforeseen cases                               ¯ Expression is evaluated before the loop body is entered
¯ This helps debugging later on!                                                     ¯ The body may thus not be entered (executed) at all
¨
Andreas Hoffmann / R. Wismuller / T. Kielmann                                                                        ¨
Andreas Hoffmann / R. Wismuller / T. Kielmann
Betriebssysteme / verteilte Systeme             Introduction to Programming   117      Betriebssysteme / verteilte Systeme             Introduction to Programming   119

5.2 Loops                                                                              5.2 Loops ...

Loops                                                                                  do while Loops
¯ Often, we have to repeat a step of an algorithm several times                        ¯ Syntax:
¯ In C++, this is achieved with loops:                                                          do statement ; while ( expression );
¯ while loops                                                                       ¯ Example:
¯ do while loops                                                                             char c;
do {
¯ for loops
cout << "Do it again (y/n)?\n";
¯ Each execution of the loop’s statements (its body) is called an                                 cin >> c;
iteration                                                                                     } while ( c != ’n’ );

¯ Expression is evaluated after the loop body has been executed
¯ The body will always be executed at least once

¨
Andreas Hoffmann / R. Wismuller / T. Kielmann                                                                        ¨
Andreas Hoffmann / R. Wismuller / T. Kielmann
Betriebssysteme / verteilte Systeme             Introduction to Programming   118      Betriebssysteme / verteilte Systeme             Introduction to Programming   120
5.2 Loops ...                                                                                 5.2 Loops ...

Correctness of while and do while                                                             for Loops (2)
¯ The loop expression must eventually become false (0)                                        ¯ for ( statement ; expression ; statement ) statement ;
¯ If not, the loop runs forever!
¯ Some remarks:
¯ This may be non-trivial (e.g., with if/else statements)
¯ All statements may also be empty, e.g.:

¯ Often, we have simple, “counting” loops                                                              int i = 1;
for (; i < 10; ) {
¯ E.g. “do this for all integers from 0 to 9”                                                           cout << "i = " << i << endl;
or “do this 10 times”                                                                             if (i < 5) { i += 1; }
¯ Such a loop typically has some initialization for the counter, a                                      else { i += 2; }
condition, and a “step” statement (like increment or                                          }
decrement)                                                                              ¯ Statements may be complex (bad style!):
for (i = 0; i < 10; cout << "i = " << i++ << endl);

¨
Andreas Hoffmann / R. Wismuller / T. Kielmann                                                                               ¨
Andreas Hoffmann / R. Wismuller / T. Kielmann
Betriebssysteme / verteilte Systeme             Introduction to Programming          121      Betriebssysteme / verteilte Systeme             Introduction to Programming   123

5.2 Loops ...                                                                                 5.2 Loops ...

for Loops                                                                                     Nested Loops
¯ for loops prescribe initialization, loop condition, and step                                ¯ Loops may be inside loops:
¯ Syntax:                                                                                        int i,j;
for ( statement ; expression ; statement ) statement ;                                  for ( i = 0; i < 5; i++ ) {
for ( j = 0; j < 20; j++ ) {
//         initialization condition                  step               body
cout << ’.’;
¯ Example:                                                                                          }
for ( i = 0; i < 10; i++ ) {                                                               cout << endl;
cout << "i = " << i << endl;                                                          }
}
¯ Style: Always use { and } for the loop body!
¯ The variable i is called loop control variable or loop
variable

¨
Andreas Hoffmann / R. Wismuller / T. Kielmann                                                                               ¨
Andreas Hoffmann / R. Wismuller / T. Kielmann
Betriebssysteme / verteilte Systeme             Introduction to Programming          122      Betriebssysteme / verteilte Systeme             Introduction to Programming   124
5.2 Loops ...                                                                          5.3 An Example: Prime Numbers ...

cout << 2 << endl;
Special Statements Inside a Loop Body:                                                  for (number = 3; number < 100; number += 2) {
¯ break;                                                                                    prime = true;
for (factor = 3; factor < number; factor += 2) {
¯ exit the whole loop (without testing the loop expression)
if (number % factor == 0) {
¯ continue;                                                                                         prime = false;
break;
¯ exit the loop body and continue with the next iteration
}
}
if (!prime)
¯ Style Guide:
continue;
¯ Avoid the use of break and especially of continue inside                               cout << number << endl;
loop bodies!                                                                   }
¯ it is (often) easier to understand if you do the same with
number:                  3                    factor:                                 prime:
if / else or exceptions ( 10)
¯ (However, break is nice to use in “search loops”)                                  output:              2
¨
Andreas Hoffmann / R. Wismuller / T. Kielmann                                                                        ¨
Andreas Hoffmann / R. Wismuller / T. Kielmann
Betriebssysteme / verteilte Systeme             Introduction to Programming   125      Betriebssysteme / verteilte Systeme                   Introduction to Programming            127

5.3 An Example: Prime Numbers                                                          5.4 Assertions
// Author: Roland                   ı 1
Wism¨¿ 2 ller
// Print all primes <= 100, using naive algorithm.
#include <iostream>                                                                    ¯ Often, you know that some condition always must (or better:
using namespace std;                                                                     should!) hold at a certain place in your program
int main() {
int number, factor;                                                                ¯ Good practice: include runtime checks of these conditions
bool prime;
cout << 2 << endl;                                                                 ¯ A good way to do this is via assertions
for (number = 3; number < 100; number += 2) {
¯ Use #include <assert.h>
prime = true;
for (factor = 3; factor < number; factor += 2) {                                  ¯ Then use assert( expression ); to check the condition
if (number % factor == 0) {
prime = false;                                                         ¯ Example: assert( Divisor != 0 );
break;
}                                                                          ¯ When the program reaches an assert() statement and the
}
if (!prime)
expression is false (0), the program halts with an error message
cout << number << endl;
¯ Beware: do not use side effects, like: assert(i++ < 10);!
}
}
¨
Andreas Hoffmann / R. Wismuller / T. Kielmann                                                                        ¨
Andreas Hoffmann / R. Wismuller / T. Kielmann
Betriebssysteme / verteilte Systeme             Introduction to Programming   126      Betriebssysteme / verteilte Systeme                   Introduction to Programming            128

```
DOCUMENT INFO
Shared By:
Categories:
Stats:
 views: 21 posted: 6/24/2009 language: English pages: 5