× Home (CS 111) Lectures Assignments Review Ryba's Website

Conditionals

Statements are executed in order, but some statements, such as conditional statements, cause execution to jump to another point in the code.

Boolean expressions

A boolean expression is an expression that evaluates as true or false. There are two types of operators that evaluate as true/false: relational operators and logical operators. They are listed below, together with arithmetic and assignment.

Precedence Operator Description Associativity
1 ! logical NOT right-to-left
2 * / % multiplication, division, modulo left-to-right
3 + - addition, subtraction left-to-right
4 < <= > >= relational <, ≤, >, ≥ left-to-right
5 == != relational =, ≠ left-to-right
6 && logical AND left-to-right
7 || logical OR left-to-right
8 = assignment right-to-left

img1

Conditional statements

A conditional statement uses a condition to decide whether or not to execute a block of code. The condition must be a boolean expression. A block is a group of statements surrounded by {}.

if

img2

if-else

img3 img4

Nested conditionals

A block may include a conditional statement. This allows you to chain if-else statements.

img5

Loops

A loop repeats a block of code as long as a condition is true. If the block contains only 1 statement, the {} are optional.

while

img6

for

Any while-loop can be written as a for-loop. for-loops are often used to repeat a loop a specific number of times. The two loops below are equivalent.

img7

Incrementing is often done with operators.

img8

In the first example, each time you evaluate the condition, i has a different value. The 11th time you evaluate the condition, i is 11, so the condition is false and the loop ends.

break and continue

break exits from a loop. continue takes you back to the beginning of a loop. while (true) loops will usually include a break statement to avoid an infinite loop.


Problems involving loops

Digits

Problems involving digits can often be solved with the following strategy. The number of digits in x will be the number of times that the loop repeats, because after removing the last digit that many times, x will be 0.

img9