Ch 5 - Control Statements Flashcards
What do control statements do?
Causes flow of execution to advance and branch
What are the two main types of control statements and what do they do?
Selection: choose different paths of execution based on outcome of an expression
Iteration: repeat statements
What are the two types of selection statements?
if and switch
What is an if statement?
Binary program flow control
based on a condition
what is the switch statement and why would you use it?
A multi-path flow control.
The value is compared to each of the values in the case statements and executed when it matches.
Switch (i) {
case 0: {
do something
break; }
case 1: {
do something else
break;
}
default: neither
}
Can a switch statement evaluate any boolean expression or just equals?
Just equals.
Need to us if for other evaluations (>, <, etc)
Is a switch statement usually more efficient than nested if statements?
yes
Name the 3 iteration statements?
for, while, do-while
Why use a do-while?
Want it to run at least once
Explain for loops
for (initialization; condition; iteration)
initialize the loop control variable
condition is evaluated
Iteration looped
Can a for loop have multiple statements in the initialization and iteration portions?
for (initialization; condition; iteration)
Yes
for (int a=1, b=2; a < b; a++, b–)
Can a for loop have empty statements ?
for (initialization; condition; iteration)
yes, can do following which is infinite loop that runs forever.
for ( ; ; )
What is a for-each style loop?
cycles through a collection of objects, like an array.
int nums[] = {1, 2, 3, 4, 5, 6,7, 8};
int sum = 0;
for ( int x: nums) sum += x;
Why would you use a for-each style loop?
To compare to a collection of items.
Useful for search. Can find where in a unsorted set a value is present.
True or false: Multidimensional arrays consist of arrays of arrays.
True