The if
statement checks a condition and executes a block of code only if the condition evaluates to true
.
if (condition) {
// code to be executed if condition is true
}
The if-else
statement provides an alternative code block to execute if the condition is false.
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
The else-if
ladder helps to check multiple conditions sequentially.
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if none of the conditions is true
}
The switch
statement allows a variable to be tested for equality against a list of values.
switch (expression) {
case constant1:
// code to be executed if expression equals constant1
break;
case constant2:
// code to be executed if expression equals constant2
break;
// more cases...
default:
// code to be executed if no case matches
}
The for
loop is used when the number of iterations is known beforehand.
for (initialization; condition; update) {
// code to be executed
}
The while
loop repeatedly executes a block of code as long as the condition is true.
while (condition) {
// code to be executed
}
The do-while
loop executes the code block at least once before checking the condition.
do {
// code to be executed
} while (condition);
The break
statement is used to exit a loop or switch statement prematurely.
// used to exit a loop or switch statement prematurely
break;
The continue
statement skips the rest of the code inside the loop for the current iteration and proceeds with the next iteration.
// skips the rest of the code inside the loop for the current iteration and proceeds with the next iteration
continue;
The goto
statement provides an unconditional jump to a labelled statement.
// jumps to the labelled statement
goto label;
label: // labelled statement