The if statement & The switch statement
An if statement has the following form:
if (condition)
{
// code to execute if condition is true
}
else
{
// code to execute if condition is false
}
Here is an example:
#include <iostream.h>
int main() {
int a = 5;
int b = 7;
if (a> b) {
cout << "a is greater than b" << endl;
}
else {
cout << "a is less than b" << endl;
}
return 0;
}
An switch statement allows you to compound a group of if statements.
An switch statement has the following syntax:
switch(integer_val){
case val_1:
// code to execute if integer_val is val_1
break;
...
case val_n:
// code to execute if integer_val is val_n
break;
default:
// code to execute if integer_val is none of the above
}
Let's see an example:
switch (color) {
case 1:
cout << "red" << endl;
break;
case 2:
cout << "blue" << endl;
break;
default:
cout << "white" << endl;
} |