Beruflich Dokumente
Kultur Dokumente
Flowcharting If statements
If statement without an else will trigger the no condition either way If-then-else will only trigger the no as the else
Loops
There are three types of loops
While Loop Do Loop For Loop
While Loop
A while loop is sort of like an if statement in that it will only execute if the condition is true It will continue to loop until the condition is false
Do Loop
A do loop does something, then loops to do it again while a condition is true Loop will be executed at least once! goToBar(); do { haveADrink(); } while (havingFun()); goHome();
For Loop
Used to loop through a block of code for a specific number of times. Can shorten the code of a while loop:
int i=1; while (i <= 10){ doSomething(); i++; } for (int i=1; i<=10; i++){ doSomething(); }
For Loop
Use when you know a specific count
Braces
The same rules apply to loops that apply to if statements Braces are not needed if there is a single line of code in the loop However, braces can still be used either way.
Variable Scope
//visible: none, Not visible: a, b, c, d int a = 10; //visible: a, not visible: b,c,d for (int b=0; b<10; b++) { //visible: a, b, not visible: c, d while (b<5) { int c = a * b; //visible: a, b, c, not visible: d } while (b > 5) { int d = b - a; //visible: a, b, d, not visible: c } //visible: a, b, not visible: c, d } //visible: a, not visible: b, c, d
Questions
If x is an int where x =1, what will x be after the following loop terminates: while (x < 100) x*=2; If x is an int where x =0, what will x be after the following loop terminates: for (int i=0; i<6; i++) x += i;
More questions
How many times will these loops execute?
int x=5; while (x > 0) { System.out.println(x); x--; } int x=5; do { System.out.println(x); x--; } while (x > 0);
More questions
How many times will these loops execute?
int x=0; while (x < 0) { System.out.println(x); x++; } int x=0; do { System.out.println(x); x++; } while (x < 0);
5 common mistakes
Wrong: if (x > y && z) Wrong: if (x = y) Wrong: if (A || B && C || D)
Evaluate to see what happens with an example
Wrong: Unmatched braces (usually caught by compiler, unless the count matches, but they are in the wrong place)