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
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
using the while loop for input validation
counters
do while loop
do while loop format
do {
statement;
} while (expression);
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
running total
accumulated sum of numbers from each repetition of loop
accumulator
variable that holds running total
sentinel
deciding which loop to use
1) the while loop is a conditional pretest loop
- iterates as long as a certain condition exits
- validating input
- reading lists of data terminated by a sentinel
2) the do-while loop is a conditional posttest loop
- always iterates at least once
- repeating a menu
3) the for loop is a pretest loop
- built-in expressions for initializing, testing, and updating
- situations where the exact number of iterations is known
nested loops
nested for loop format
for (initialization; test; update) { // outer loop
for (initialization; test; update) { // inner loop
statement;
}
statement;
}
files
steps for using files
file stream types