if-else expresses decisions
else part is optional
if (expression)
statement1
else
statement2
expression returns a numerical value0 is considered FALSE, any other value is TRUE:::: {.columns}
::: {.column}
By default, the else is associated with the inner if
if (i >= 0)
if (i < 5)
a = b;
else
a = c;
:::
::: {.column}
Use braces to remove ambiguity
if (i >= 0) {
if (i < 5)
a = b;
} else
a = c;
:::
::::
Useful for expressing multi-way decisions
if (expression)
statement
else if (expression)
statement
else if (expression)
statement
else
statement
:::: {.columns}
::: {.column width=”40%”}
switch (expression) {
case const-expr:
statements
case const-expr:
statements
default:
statements
}
:::
::: {.column width=”60%”}
Used to express multi-way decision
Matches the result of an expression to one of several integer constants
break statement causes exit from the switchbreak all statements after the matching case are executed till the end of the switch block:::
::::
The while loop executes as long as expression is TRUE (not 0)
while (expression) {
statements
}
The loop has three parts
for (expr1; expr2; expr3) {
statements
}
expr1 is an initialization expressionexpr2 is a relational expression, andexpr3 is the increment expressionThe loop executes as long as expr2 is TRUE (not 0)
All three expressions can be empty which leads to an infinite for loop
The do loop executes at least once before expression is evaluated
do {
statements
} while (expression);
The loop executes as long as expression is TRUE (not 0)
for, while or do-while) or switch blockcontinue statement causes a loop to begin the next iteration, the statements following continue are not executedthe goto statement causes execution to jump to the statements after the label
goto label;
statements
label:
statements
goto is not recommended as it results in spaghetti code
Write a program that converts 1 to 50 mile(s) into kilometers
NOTE 1 mile = 1.609344 kilometers
Print the result in tabular form
01 mile(s) = 01.609344 km 02 mile(s) = 03.218688 km
03 mile(s) = 04.828032 km 04 mile(s) = 06.437376 km