Conditional statements are used to make decisions in programming based on certain conditions. They allow you to specify different actions to be taken depending on whether a condition is true or false.
In C++, the most common type of conditional statement is the if
statement. The syntax of an if
statement is as follows:
TEXT/X-C++SRC
1if (condition) {
2 // code to be executed if condition is true
3} else {
4 // code to be executed if condition is false
5}
Here's an example that uses an if
statement to check if a person is eligible to vote based on their age:
TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4int main() {
5 int age;
6
7 cout << "Enter your age: ";
8 cin >> age;
9
10 if (age >= 18) {
11 cout << "You are eligible to vote." << endl;
12 } else {
13 cout << "You are not eligible to vote." << endl;
14 }
15
16 return 0;
17}
In this example, the program prompts the user to enter their age. If the age is greater than or equal to 18, the program displays the message "You are eligible to vote." If the age is less than 18, the program displays the message "You are not eligible to vote."
xxxxxxxxxx
17
using namespace std;
int main() {
int age;
cout << "Enter your age: ";
cin >> age;
if (age >= 18) {
cout << "You are eligible to vote." << endl;
} else {
cout << "You are not eligible to vote." << endl;
}
return 0;
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment