Module 2a and 2b
Module 2a and 2b
FE (PSP)
Branching structures
01 02 03
Use if to specify a block Use else if to specify a Use switch to specify
of code to be executed, new condition to test, if many alternative blocks
if a specified condition the first condition of code to be executed
is true. Use else to is false
specify a block of code
to be executed, if the
same condition is false
If Statement
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
Example
• int x = 20;
int y = 18;
if (x > y) {
printf("x is greater than y");
}
• Output
• x is greater than y
Use the else statement to specify a block of code to be executed
if the condition is false.
The if-else
Statement Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Example
} else {
// Statements to execute if condition1 is false
}
Example
• Problem Statement:
• Determine the grade of a student based on their score.
If the score is above 90, it's an ‘A+’.
• If the score is between 80 and 90, check if it's above 85
for an 'A' or else 'B’.
• Below 80, if it's above 70, it's a 'C', otherwise, it's a 'D'.
Example
code
• Instead of writing many if..else statements, you can use
the switch statement.
• The switch statement selects one of many code blocks to be
Switch executed:
• switch (expression) {
Statement case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Example
Looping
structures
Part 2B
Break
int i;
Continue • Example
Statement
• int i;
• int i = 0;
Continue in }
}
printf("%d\n", i);
i++;
While Loop
• When you know exactly how many times
you want to loop through a block of code,
use the for loop instead of a while loop:
For Loop
• for (expression 1; expression 2; expression
3) {
// code block to be executed
}
int main() {
int i;
return 0;
}
Nested Loops
// Outer loop
for (i = 1; i <= 2; ++i) {
printf("Outer: %d\n", i);
// Executes 2 times
// Inner loop
for (j = 1; j <= 3; ++j) {
printf(" Inner: %d\n", j);
// Executes 6 times (2 * 3)
}
}
Loops
Syntax
while (condition) {
// code block to be executed
}
Example of While loop
do while loop