Decision-making structures require that the programmer specify one or more conditions to be evaluated or tested by the program.
It is the simplest decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not.
if (condition) {
// block of code to be executed if the condition is true
}
The if statement alone tells us that if a condition is true it will execute a block of statements. If the condition is false, we can use else to execute a different block.
if (condition) {
// executes if condition is true
} else {
// executes if condition is false
}
An if or else statement inside another if or else statement is called nested if.
[Image of nested if-else flowchart]Used when we have multiple conditions to check. The compiler checks conditions from top to bottom. As soon as a true condition is found, the statement associated with it is executed.
if (condition1) {
// code
} else if (condition2) {
// code
} else {
// code if no conditions are true
}
The switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.
Rule: The expression used in a switch statement must have an integral or enumerated type (int or char).
switch (expression) {
case value1:
// statement
break;
case value2:
// statement
break;
default:
// default statement
}
Loops are used to repeat a block of code a specific number of times or until a certain condition is met.
This is an entry-controlled loop. The condition is checked before entering the loop body.
while (condition) {
// statements
}
This is an exit-controlled loop. The body of the loop is executed at least once before the condition is checked.
do {
// statements
} while (condition);
Used when the number of iterations is known in advance. It includes initialization, condition, and increment/decrement in one line.
for (initialization; condition; increment/decrement) {
// statements
}
These statements are used to alter the flow of a loop or switch statement.
break; in a switch case, "fall-through" occurs, executing all subsequent cases until a break or the end of the switch is found.while(1)) is an infinite loop. Be careful with increment/decrement steps!if(cond); or for(...);. This terminates the logic prematurely.if (a = 5) instead of if (a == 5). The first one assigns 5 to 'a' and is always treated as true.while(condition); in a do-while loop.Q: Can we use float in switch case?
A: No, switch expressions must result in an integer or character constant.
Q: When is a for loop better than a while loop?
A: Use a for loop when you know the exact number of iterations. Use a while loop when you need to repeat something until a specific event/condition occurs.