Else Expression
In the previous task, we mentioned what the program should do if our statement is true, but what to do if we need to specify actions if the condition is also false? For such situations in C++ exists the else statement.
The syntax is the following:
if (condition) {
// code here will be executed if the condition is true
} else {
// code here will be executed if the condition is false
}
Letβs define if the number is even (can be divided by 2 into two equal numbers) or not, using the else statement:
int num;
cin >> num;
if (num % 2 == 0) {
cout << "The number is even!";
} else {
cout << "The number isn't even!";
}
The code accepts a number from the user. If the number by division by 2 gives 0 as the remainder (for example 6/2 = 3 the remainder is 0) then the condition is true and the user printed an even number, otherwise, the number is not even.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Ask me questions about this topic
Summarize this chapter
Show real-world examples
Awesome!
Completion rate improved to 3.7
Else Expression
Swipe to show menu
In the previous task, we mentioned what the program should do if our statement is true, but what to do if we need to specify actions if the condition is also false? For such situations in C++ exists the else statement.
The syntax is the following:
if (condition) {
// code here will be executed if the condition is true
} else {
// code here will be executed if the condition is false
}
Letβs define if the number is even (can be divided by 2 into two equal numbers) or not, using the else statement:
int num;
cin >> num;
if (num % 2 == 0) {
cout << "The number is even!";
} else {
cout << "The number isn't even!";
}
The code accepts a number from the user. If the number by division by 2 gives 0 as the remainder (for example 6/2 = 3 the remainder is 0) then the condition is true and the user printed an even number, otherwise, the number is not even.
Thanks for your feedback!