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.
Danke für Ihr Feedback!
Fragen Sie AI
Fragen Sie AI
Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen
Fragen Sie mich Fragen zu diesem Thema
Zusammenfassen Sie dieses Kapitel
Zeige reale Beispiele
Awesome!
Completion rate improved to 3.33
Else Expression
Swipe um das Menü anzuzeigen
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.
Danke für Ihr Feedback!