View
222
Download
3
Category
Preview:
Citation preview
Chapter 3- Flow Control
Overview
Why flow control Branches vs. Loops Branch statements Loop Statements Complex loops Boolean variables Review
Why Flow Control
Why Flow Control?
Can perform more complex programs. Can write programs with less code. Sometimes makes it easier to
understand what is going on in the code.
Branches vs. Loops
Branches are used for statements that you want to run conditionally (only on certain input).
Loops are used to repeat statements without having to write the programs over and over and over...
Branches
Branches
Two main types of branches:– if-else (sometimes does not include the
else).– switch (the same thing as multiple if
statements).
if-else statement
if(<condition>){
<statements>;}else{
<statements>;}
Don’t put a semicolon at the end of these statements.
Can be one or more statements here.
If only doing one statement, don’t need curly braces({ or }), but it doesn’t hurt to have them there either.
You don’t need to include theelse section if you don’t want.
Conditions
Some sort of inequality: == (equal), !=(not equal), >=(greater than or equal), <=(less than or equal), >(greater than), <(less than).
The above only work on primitives, for using class objects, you use .equals()
string1.equals(“Hello there”);string1.equals(string2);
Ands and Ors
You can also combine multiple conditions with either the AND operator “&&” or the OR operator “||” (that’s two “pipes” which are usually located above the backslash character “\”).
Examplesif((char1==‘y’) || (char1==‘n’)) //if y or nIf(int1 >0 && int1 < 100) //if between 0 and 100
Boolean Logic
AND logic– True && True =
True– True && False =
False– False && True =
False– False && False =
False
OR logic– True || True = True– True || False =
True– False || True =
True– False || False =
False
An if-else example
...System.out.println(“Please enter y or n.”);char letter = SavitchIn.readLineNonwhiteChar();if(letter == ‘y’) //if they pressed y{
System.out.println(“You entered ‘y’”);}else //if they didn’t press y{ //NOTE- this doesn’t mean they pressed n //They could have pressed g or something
System.out.println(“You didn’t enter ‘y’”);} ...
More on if-else statements
Be careful that what you do in your else statement is truly for the negation of the if condition(as in the last example).
Can nest them(put an if-else statement as one of the statements inside another if-else statement), just be careful when doing this.
More complicated examplechar char1= SavitchIn.readLineNonwhiteChar();if(char1 == ‘a’){ System.out.println(“You pressed a.”);}else if(char1 == ‘b’) {
System.out.println(“You pressed b.”); } else
System.out.println(“You pressed garbage.”);
Nested if-else statements. Note, each if-else statement counts as a single statement, so we don’t really need curly braces around the second if-else statement(it is the “single” statement for the elsepart.
switch statements
Use when you would have multiple if statements checking the condition of the same variable.
For large cases it is easier to read and easier to alter.
The format of switchswitch(<variable>){ case <value1>:
<statements>;break;
case <value2>:<statements>;break;...
case <valueI>:<statements>;break;
default:<statements>;break;
}
Some integer or characterexpression (can’t use String or any other type).
One or more statements(don’tneed curly braces in switches,but it won’t hurt either)
Always, always, always enda case with a break. Else the program will continue runninginto other cases.
What the computer does if thevariable doesn’t match any ofthe above values.
Alternate way of doing ‘a’, ‘b’ examplechar char1=SavitchIn.readLineNonwhiteChar();switch(char1){ case ‘a’:
System.out.println(“You pressed a.”);break;
case ‘b’:System.out.println(“You pressed b.”);break;
default:System.out.println(“You pressed garbage”);break;
}
Loops
Loops
Loops help us repeat steps over and over without us having to write the code over and over.
There are three main kinds of loops:– while statements– do-while statements– for statements
while statements
Repeats the body of the statement until the condition is false. Will loop zero or more times.
Looks like:
while(<condition>){
<statements>;}
Some sort of boolean expression(like equality).Just like with if-else.
Note, again there is nosemicolon at the end of the line. Don’t put one there.
Again, like the branch statements, this can be one or more lines.If it is only one statement, you can remove the curly braces.
Two while examples(what does the following print to the screen?):...int max = 10, count = 1;while(count <= max){
System.out.println(count);count++;
}
while(count<=max){
System.out.println(max);count++;
}
...
What they print to the screen:...int max = 10, count = 1;while(count <= max){
System.out.println(count);count++;
}
while(count<=max){
System.out.println(max);count++;
}
...
123…910
Nothing, count is already bigger thanmax(that is how it gotout of the last loop).
do-while statement The do while statement is similar to the
while statement, except it is executed at least once(while statement can sometimes execute 0 times).
Looks like:
do{ <statements>;} while(<condition);
The do-while statement is theonly, I repeat only, looping or branch statement that requiresa semi-colon at the end of the statement.
Do-while example(what is output?)...int max = 10, count = 1;do{
System.out.println(count);count++;
} while(count <= max);
do{
System.out.println(max);count++;
} while(count<=max)
...
What they print to the screen:123…910
10, as do-whiles alwaysexecute at least once
...int max = 10, count = 1;do{
System.out.println(count);count++;
} while(count <= max);
do{
System.out.println(max);count++;
} while(count<=max)
...
The mighty for statement!
The for loop is another repeating loop that makes it really easy to specify a range in which the loop repeats.
Looks like:
for(<initializers>;<condition>;<updaters>){
<statements>;}
Again, no semicolon at the end!
The for statement dissectedfor(<initializers>;<condition>;<updaters>){
<statements>;}
Initializers- Optional. Any statements placed in this area will be executed once before entering the loop(or any testing of conditions).
Condition- Required. Some boolean expression just like in while statements. While it is true, the statements in the loop are executed. When it is false, the computer skips over the for loop and continues on with the program.
Updaters- Optional. Any statements in this area will be run whenever the for-statement finished all of the instructions in the statements section.
A for example
...for(int count = 1; count <= 4; count++)
System.out.println(“Howdy: “ + count);...
Output:Howdy: 1Howdy: 2Howdy: 3Howdy: 4
Another for example
...int counter = 1;for(; count <= 4; ){
System.out.println(“Howdy: “ + count);count++;
}...
Output:Howdy: 1Howdy: 2Howdy: 3Howdy: 4
A for statement withoutinitializers or updaters is basically awhile loop
More than one initializer or updater. You can have more than one initializer or
updater. Just use a comma “,” between each
statement in the section (why not a semicolon like usual?).
Do NOT use a comma for the condition, use && or || to combine multiple parts.
Like so:
for(int i=0, int j=0; i<=3; j++, i+=j)System.out.println(i);
What will this output (look carefully):
...for(int i=0, int j = 1; i<=4; j++)
System.out.println(j);...
What is output:
...for(int i=0, int j = 1; i<=4; j++)
System.out.println(j);...
123456...
INFINITE LOOP!!!!
Infinite loop-constant danger Infinite loops are common when
programming while, do-while, and for statements.
Always, always, always make sure that your condition will eventually fail(make sure you increment variables). Else your program will continue forever.
To kill infinite loops, close the window or press ctrl-c or sometimes ctrl-z.
Which of these have infinite loops?…………………………………………………………………int j = 1;while(j>=1);{ System.out.println(j);
j++;}…………………………………………………………………int k = 1;do{ System.out.println(k);
k+=2;} while(k != 6);…………………………………………………………………for(int i=1;i>=1;i++)
System.out.println(i);
Answer: All of them!…………………………………………………………………int j = 1;while(j<=10);{ System.out.println(j);
j++;}…………………………………………………………………int k = 1;do{ System.out.println(k);
k+=2;} while(k != 6);…………………………………………………………………for(int i=1;i>=1;i++)
System.out.println(i);
Semicolon stops anything from happening in while loop, including the increment of j.
Starts off as 1, an odd number. Always adding 2 so k will stay odd. So k willnever be even and won’t be6. It will skip right over it.
Starts off as 1 and increases, so will never be less than 1, so the conditionwill never be false.
Sentinels and loops for user input
A “sentinel” is a special character or number specified by you to end a loop of user input.
When using sentinels, you will test the user input against the sentinel in the condition area of you loop.
A sentinel example
Write a loop that will ask a user for a list of non-negative integers. You will produce the sum of all the integers. The user signifies the end of their list by entering a sentinel value that is a negative number(any negative number will do).
Sentinel example- For loop....int sum = 0, userInput;System.out.println(“Enter a number(neg. to quit):”);userInput = SavitchIn.readLineInt();while(userInput >= 0){
sum += userInput //sum = sum + userInputSystem.out.println(“Enter another number: “);userInput = SavitchIn.readLineInt();
}System.out.println(“The sum is: “ + sum);...
Other rules about loops
You should never declare a variable inside the body of a looping statement.
Watch out for infinite loops! Off-by-one errors are common. Test
often. When making any changes to a loop,
always retest the whole thing. You may have broken something else in your fix.
Complex Loops
Complex loops.
Single loops are relatively easy to grasp, but there are things that can happen that make them much more difficult
An exit or break statement can end a loop prematurely.
Nested loops can also be very useful, but can also be very confusing.
break and exit
break will jump you directly out of any loop(or switch). It will jump you out only one level(if you have things nested). It won’t work with if-else statements though.
System.exit(0) will exit completely out of the Java program.
break and exit examples...int i = 0;while(i<=10){
System.out.println(i);i++;break;
}System.out.println(i);...int k = 0;while(k<=10){ System.out.println(k);
I++;System.exit(0);
}System.out.println(k);...
Output of examples...int i = 0;while(i<=10){
System.out.println(i);i++;break;
}System.out.println(i);...int k = 0;while(k<=10){ System.out.println(k);
k++;System.exit(0);
}System.out.println(k);...
12
1
Nesting loops
Good for doing two dimensional (or more dimensions) things, tables of information, basic ASCII art, etc.
2-D: Usually use the outer loop to control the rows and the inner loops to control the columns.
A nested loop example
int i,j;for(i=1; i<=4;i++){ for(j=1; j<=i; j++)
System.out.print(“*”); System.out.println(“ “);}
A nested loop example output
int i,j;for(i=1; i<=4;i++){ for(j=1; j<=i; j++)
System.out.print(“*”); System.out.println(“ “);}
**********
Make 4 rows
For each column up tothe ith column do thefollowing
Write a single asterisk(no new line)
After writing out all the columnsfor a row, put in a new line.
Boolean Variables
Boolean Variables
A boolean is a primitive type that can only have the values true and false
Can be used wherever a Boolean expression is required (like a condition in an if-else or for statement).
Can make code easier to read sometimes.
boolean variable form
boolean <variable>;
<variable>=<booleanExp>;
if(<boolean_variable>)
boolean AOK, isLastNum;
isLastNum = true;AOK = (temperature>32)
&& (sunlight > 6);
If(AOK){
System.out.println( “All systems go.”);}
Guides for expressionsWhen working with complicated Boolean expressions (lots of &&s and ||s) or complicated arithmetic expressions (lots of math symbols) put parentheses around the parts of the expression you want evaluated first. Or see the precedence table (p. 194).
(4+5)*(6+7) = 117 4+5*6+7 = 41(true || false) && false = false true || false && false = true
Review
Review Branches for conditional execution
– What are the names of the statements?– What symbol should never come at the
end of an if-else statement? Loops are for repeated execution
– What are the names of the statements?– What things should you be careful of in
loops? Boolean variables can be used in the
place of Boolean expressions
Recommended