Selection structures allow you to execute different code based on conditions. The primary selection structures in C++ are:
The if statement allows you to execute a block of code only if a specified condition is true.
Syntax:
if (condition) {
// code to be executed if condition is true
}
#include <iostream>
using namespace std;
int main()
{
int number = 10;
if (number > 5)
{
cout << "Number is greater than 5" << endl;
}
return 0;
}
Output:
Number is greater than 5
The if-else statement allows you to execute one block of code if a condition is true and another block of code if the condition is false.
Syntax:
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
#include <iostream>
using namespace std;
int main()
{
int number = 3;
if (number > 5)
{
cout << "Number is greater than 5" << endl;
} else
{
cout << "Number is not greater than 5" << endl;
}
return 0;
}
Output:
Number is not greater than 5
The else-if chain is used to test multiple conditions. If one of the conditions is true, the corresponding block of code is executed, and the rest of the Chain is skipped.
Syntax:
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 are true
}
#include <iostream>
using namespace std;
int main()
{
int number = 7;
if (number > 10)
{
cout << "Number is greater than 10" << endl;
} else if (number > 5)
{
cout << "Number is greater than 5" << endl;
} else
{
cout << "Number is 5 or less" << endl;
}
return 0;
}
Output:
Number is greater than 5
The switch statement allows you to select one of many code blocks to be executed.
Syntax:
switch (expression)
{
case constant1:
// code to be executed if expression equals constant1
break;
case constant2:
// code to be executed if expression equals constant2
break;
// you can have any number of case statements
default:
// code to be executed if expression doesn't match any case
}
#include <iostream>
using namespace std;
int main()
{
int day = 4;
switch (day)
{
case 1:
cout << "Monday" << endl;
break;
case 2:
cout << "Tuesday" << endl;
break;
case 3:
cout << "Wednesday" << endl;
break;
case 4:
cout << "Thursday" << endl;
break;
case 5:
cout << "Friday" << endl;
break;
case 6:
cout << "Saturday" << endl;
break;
case 7:
cout << "Sunday" << endl;
break;
default:
cout << "Invalid day" << endl;
}
return 0;
}
Output:
Thursday
#include <iostream>
directive in a C++ program.
main()
function in a
C++
program?return 0;
statement
in the
main()
function.