One of the hallmarks of imperative programming is the ability to disrupt the default sequential flow of execution by providing of instructions that modify which instruction should be executed next. The three principle ways this can be done are selection, iteration, and escapes.
Most languages provide 1-way, 2-way, and multi-way conditionals to select one of several alternative actions. For example:
if (!valid(input)) throw new Exception("Invalid input") // one-way selection
if (x < y) max = x else max = y // 2-way selection
switch(op) // multi-way selection
{
case '+': result = arg1 + arg2; break;
case '*': result = arg1 * arg2; break;
case '-': result = arg1 - arg2; break;
case '%': result = arg1 % arg2; break;
case '/':
if (arg2) result = arg1 / arg2;
else System.err.println("can't divide by
0");
break;
default: System.err.println("unrecognized operator " +
op);
}
Iteration allows programmers to execute a block of code a fixed number of times or until some condition fails:
for(int i = 0; i < n; i++) result = result + i;
for(String word: doc) if (!dictionary.contains(word)) spellingErrors++;
while(!done) done = num % ++factor == 0;
Escape instructions allow control to dramatically leap from end of a program to another.
if (done) return result;
if (!valid(input)) throw new Exception("Invalid input")
if (result < 100) goto done;
while(!done) {
result--;
if (result % 3 == 0) continue;
if (result < 0) break;
done = (num % 5) == 0;
}