Download presentation
Presentation is loading. Please wait.
1
Control Statement tsenghy
2
3 Control structures Sequential
Selection (Alternative) ( if-then-else ) if (expr) stat-1; else stat-2; switch(expr) { case expr-1: stat-1; break; … } Repetition (Loop) for loop while loop do while
3
If Statements if ( CONDITION_1 ) { DO_ACTION_A }
else if ( CONDITION_2 ) DO_ACTION_B else DO_SOMETHING_ELSE
4
Switch-case switch ( condition ) { case A: case B: DO_ACTION_1; break;
case C: DO_ACTION_2; case D: DO_ACTION_3; default: DO_SOMETHING_ELSE; }
5
Example: GPA Calculator
// Example program #include <iostream> using namespace std; int main() { int grade = 'A'; int GPA; if ( grade == 'A' ) GPA = 4; else if ( grade == 'B' ) GPA = 3; else if ( grade == 'C' ) GPA = 2; else if ( grade == 'D' ) GPA = 1; else GPA = 0; cout << "GPA=" << GPA; }
6
Example: GPA Calculator
// Example program #include <iostream> using namespace std; int main() { int grade = 'A'; int GPA; switch ( grade ) case 'A': GPA = 4; break; case 'B': GPA = 3; case 'C': GPA = 2; case 'D': GPA = 1; default: GPA = 0; } cout << "GPA=" << GPA;
7
for Loop vs. while Loop i=1; do for(i=1 ; i<= 9 ; i++) { {
/* Loop body */ i++; } while ( i<= 9 ); for(i=1 ; i<= 9 ; i++) { /* Loop body */ } i=1; for( ; i<= 9 ; ) { /* Loop body */ i++; } i=1; while( i<= 9 ) { /* Loop body */ i++; }
8
Flow of for/while Loop ; while( ) { ; ; } for( ; ; ) {
}; Get a plate ; while( ) { ; ; } no Space? Yes Find the food you want Put it in your plate
9
Example: all you can eat
// Example program #include <iostream> using namespace std; int main() { int space; for(space = 10; space > 0; space--) cout << "space left: " << space << endl; cout << "put some potatoes in your plate" << endl; } cout << "check space: " << space << endl;
10
Example: all you can eat
// Example program #include <iostream> using namespace std; int main() { int space = 10; while(space > 0) cout << "space left: " << space << endl; cout << "put some potatoes in your plate" << endl; space--; } cout << "check space: " << space << endl;
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.