C++ conditions are used to control the flow of a program. They allow you to execute different code blocks depending on whether a condition is true or false.
There are a number of different conditional statements in C++, including:
Examples
The following example shows how to use an if statement:
int age = 25;
if (age >= 18) {
std::cout << "You are an adult." << std::endl;
} else {
std::cout << "You are not an adult." << std::endl;
}
Output:
You are an adult.
The following example shows how to use an else if statement:
int grade = 85;
if (grade >= 90) {
std::cout << "You got an A." << std::endl;
} else if (grade >= 80) {
std::cout << "You got a B." << std::endl;
} else if (grade >= 70) {
std::cout << "You got a C." << std::endl;
} else {
std::cout << "You got an F." << std::endl;
}
Output:
You got a B.
The following example shows how to use a switch statement:
char grade = 'B';
switch (grade) {
case 'A':
std::cout << "You got an A." << std::endl;
break;
case 'B':
std::cout << "You got a B." << std::endl;
break;
case 'C':
std::cout << "You got a C." << std::endl;
break;
default:
std::cout << "You got an F." << std::endl;
}
Output:
You got a B.
C++ conditions are a powerful tool that allow you to control the flow of your program. By using conditional statements, you can execute different code blocks depending on the values of variables or the results of expressions.