PIC10A Lecture 6

Reading

p61-63. p73-76

Switch

switch(expression) {
     case constant1:
          statements1;
          ..............
           break;
     case constant2:
          statements2;
          ............
          break;
             .
             .
     default:
          default_statements;
}


#include<iostream>
using namespace std;

int main(){
double num1, num2; // 2 numbers
char op; // an operator, +,-,* or /
cout << "Please enter an arithmetic expression: ";
cin >> num1 >> op >> num2;

switch(op) {
case '+':
cout << "The result is " << num1+num2 << ".\n";
break;
case '-':
cout << "The result is " << num1-num2 << ".\n";
break;
case '*':
cout << "The result is " << num1*num2 << ".\n";
break;
case '/':
cout << "The result is " << num1/num2 << ".\n";
break;
default:
cout << "Sorry, I don't understand the operator "
<< op << ".\n";
}
cout << "Bye!\n";
return 0;
}

Output

Please enter an arithmetic expression: 21.3*16.22
The result is 345.486.
Bye!

Please enter an arithmetic expression: 7%6.2
Sorry, I don't understand the operator %.
Bye!

break

#include<iostream>
using namespace std;

int main() {
int num ;
cout << "Input a number: ";
cin >> num;
switch(num) {
case 1:
cout << "You input 1.\n";
case 2:
cout << "You input 2.\n";
break;
case 3:
cout << "You input 3.\n";
case 4:
cout << "You input 4.\n";
break;
}
return 0;
}

Output

Input a number: 3
You input 3.
You input 4.

for loop

for(initialization; condition; update) {
statements;
}

Example

#include<iostream>
using namespace std;

int main() {
int num;
for(num = 10; num >= 1; num--) {
cout << num << " bottles of beer on the shelf.\n";
}
cout << "No more beer!\n";
return 0;
}

Output

10 bottles of beer on the shelf.
9 bottles of beer on the shelf.
8 bottles of beer on the shelf.
7 bottles of beer on the shelf.
6 bottles of beer on the shelf.
5 bottles of beer on the shelf.
4 bottles of beer on the shelf.
3 bottles of beer on the shelf.
2 bottles of beer on the shelf.
1 bottles of beer on the shelf.
No more beer!

Example

#include<iostream>
using namespace std;

int main() {
for(int i=0; i < 5; i++) {
cout << "Hello ";
}
cout << endl;
return 0;
}

Output

Hello Hello Hello Hello Hello

When the program encounters the for loop. It
  1. executes the initialization. It usually gives the initial value of some variables.
  2. tests the condition.
    If the condition is true, If the condition is false:

Infinite loop

while(true) {
cout << "Hello!\n";
}