Presentation is loading. Please wait.

Presentation is loading. Please wait.

Statements and flow control

Similar presentations


Presentation on theme: "Statements and flow control"— Presentation transcript:

1 Statements and flow control
Iteration statements (loops) We have already seen most of these: While loops: void ouch(int n) { int x = 1; while (x <= n) { printf("n = %d x = %d\n",n,x); printf("Ouch! Stop it!!\n"); x++; } } We could have also written this command as: void ouch(int n) { int x = 1; do { printf("n = %d x = %d\n",n,x); printf("Ouch! Stop it!!\n"); x++; } while (x <= n); } What’s the difference???

2 Statements and flow control
The while command is an entry-condition loop; the do-while command is an exit-condition loop. For loops: int expo(int b, int p) { int result = 1, passno; for (passno = 1; passno <= p; passno++) result = result * b; return (result); } Nested For loops: #include "stdafx.h" void main() { int i, j, pp2array[4][2] = {{2,4},{3,9},{5,25},{7,49}}; for (i=0; i<4; i++) for (j=0; j<2; j++) printf("%d ", pp2array[i][j]); printf("\n"); }

3 Statements and flow control
The output of the nested loop should appear as:

4 Statements and flow control
If - Else Statements Consider a simple if statement: if(1 == 1) { //Stuff to do if the condition is true (which in this case, it always is! 1 is always 1!) } If else statement (enter, compile and run this code): int main() { int input = 1; char instring[5]; while (input != 0) { cout << "\nEnter an integer (enter 0 to quit): "; cin >> instring; input = atoi(instring); if (input == 0) return(1); else if (input % 2 == 0) cout << endl <<"The integer is even"<< endl; else if (input % 2 == 1) cout << endl <<"The integer is odd"<< endl; }

5 Statements and flow control
The output should appear as:

6 Statements and flow control
Rewrite (compile and Execute) your program so it appears as: #include "stdafx.h" #include <iostream> using namespace std; int main() { int input = 1, modinput; char instring[5]; while (input != 0) { cout << "\nEnter an integer (enter 0 to quit): "; cin >> instring; input = atoi(instring); if (input == 0) return 0; modinput = input % 2; switch(modinput) { case 0: cout << "The Number is even" << endl; break; case 1: cout << "The Number is odd" << endl; break; }

7

8

9

10

11

12

13

14

15

16


Download ppt "Statements and flow control"

Similar presentations


Ads by Google