Conditional - Selective Constructs
Conditional - Selective Constructs
Learning Outcome(s):
1. Identify the different conditional/selective constructs.
2. Use the different conditional/selective constructs in a program.
CONDITIONAL STATEMENTS
Conditional statements are statements that check an expression then may or may
not execute a statement or group of statements depending on the result of the
condition.
1. if statement
Syntax:
if (condition) {
statements;
}
Example:
#include <iostream>
#include <cstdlib>
int grade;
return 0;
}
Sample Output:
Syntax:
if (condition) {
statements;
}
else {
statements;
}
Note: Only the code associated with the IF or the code that is associated
with the ELSE executes, NEVER both.
Example:
#include <iostream>
int grade;
Sample Output:
Syntax:
if (condition1) {
statements;
}
else if (condition2) {
statements;
}
else if (condition3) {
statements;
}
.
.
.
else if (conditionN) {
statements;
}
else {
statements;
}
Example:
#include <iostream>
#include <cstdlib>
int day;
Sample Output:
Syntax:
if (condition1) {
if (condition2) {
statements;
}
Else {
Statements;
}
}
else {
if (condition3) {
statements;
}
else {
statements;
}
Example:
#include <iostream>
#include <cstdlib>
int a, b, c;
if (a > b){
if (a > c){
cout << "\n\na is the largest!\n";
}
else {
cout << "\n\nc is the largest!\n";
}
}
else {
if (b > c){
cout << "\n\nb is the largest!\n";
}
return 0;
}
Sample Output:
Syntax:
switch (variable) {
case constant1:
statements;
break;
case constant2:
statements;
break;
.
.
.
default:
statements;
}
Example:
#include <iostream>
#include <ctdlib>
using namespace std;
int day;
switch (day){
case 1:
cout << "SUNDAY!\n";
break;
case 2:
cout << "MONDAY!\n";
break;
case 3:
cout << "TUESDAY!\n";
break;
case 4:
cout << "WEDNESDAY!\n";
break;
case 6:
cout << "FRIDAY!\n";
break;
case 7:
cout << "SATURDAY!\n";
break;
default:
cout << "NOT A DAY OF THE WEEK!\n";
}
return 0;
}
Sample Output: