Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
This is how it works:
The example below uses the weekday number to calculate the weekday name:
Example
int day = 4;
switch (day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");
break;
}
// Outputs "Thursday" (day 4)
A break can save a lot of execution time because it "ignores" the execution of all the rest of the code in the switch block.
The default keyword specifies some code to run if there is no case match:
Example
int day = 4;
switch (day) {
case 6:
printf("Today is Saturday");
break;
case 7:
printf("Today is Sunday");
break;
default:
printf("Looking forward to the Weekend");
}
// Outputs "Looking forward to the Weekend"
Note: The default keyword must be used as the last statement in the switch, and it does not need a break.
The while loop loops through a block of code as long as a specified condition is true:
Syntax
while (condition) {
// code block to be executed
}
In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less than 5:
Example
int i = 0;
while (i < 5) {
printf("%d\n", i);
i++;
}
Note: Do not forget to increase the variable used in the condition (i++), otherwise the loop will never end!
The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
Syntax
do {
// code block to be executed
}
while (condition);
The example below uses a do/while loop. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested:
Example
int i = 0;
do {
printf("%d\n", i);
i++;
}
while (i < 5);
Do not forget to increase the variable used in the condition, otherwise the loop will never end!
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:
Syntax
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
The example below will print the numbers 0 to 4:
Example
int i;
for (i = 0; i < 5; i++) {
printf("%d\n", i);
}
Example explained
This example will only print even values between 0 and 10:
Example
for (i = 0; i <= 10; i = i + 2) {
printf("%d\n", i);
}
10 videos|13 docs|15 tests
|
|
Explore Courses for Class 6 exam
|