Chapter 5 Flashcards
Increment Operator
prefix: val++;
postfix: ++val;
- adds one to a variable
- can be used in expressions: (result = num1++ + –num2)
- can be used in relational expressions (pre/postfix operations will cause different comparisons)
Decrement Operator
prefix: –val;
postfix: val–;
- subtracts one from a variable
- can be used in expressions: (result = num1++ + –num2)
- can be used in relational expressions (pre/postfix operations will cause different comparisons)
prefix vs postfix
prefix mode: increments or decrements then returns the value of the variable
postfix mode: returns the value, then increments or decrements
Loop
- a control structure that causes a statement or statements to repeat
while loop format
while (expression) {
statement;
statement;
}
how does the while loop work
expression is evaluated before the loop executes
- if true, then statement is executed, and expression is evaluated again
- if false, then the loop is finished and program statements following statement execute
things to watch out for in loops
- loop must contain code to make expression become false; otherwise, the loop will have no way of stopping - called an infinite loop because it will repeat an infinite number of times
using the while loop for input validation
- the while loop can be used to create input routines that reject invalid data, and repeat until valid data is entered.
- general approach in pseudocode
read an item of input
while the input is invalid
display an error message
read the input again
end while
counters
- a variable that is incremented or decremented each time a loop repeats
- can be used to control execution of the loop (AKA: loop control variable)
- must be initialized before entering loop
do while loop
- a posttest loop, execute the loop, then test the expression
- always executes at least once
- execution continues as long as expression is true, stops repeating when expression becomes false
- useful in menu-driven programs to bring user back to menu selection
do while loop format
do {
statement;
} while (expression);
for loop
- useful for counter-controlled loop
- pretest loop: tests its test expression before each iteration
- can have multiple statements in the initialization expressions
- can have multiple statements in the test expression
- can omit the initialization expression if var has already been initialized
- can declare variables in the initialization expression: then. the scope of the variable is the for loop
how the for loop works
1) perform initialization
2) evaluate test expression
- if true, execute statement
- if false, terminate loop execution
3) execute update, then re-evaluate test expression
for loop format
for (initialization; test; update) {
statement;
}
when to use the for loop
in any situation that clearly requires
- an initialization
- a false condition to stop the loop
- an update to occur at the end of each iteration