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.
Bedankt voor je feedback!
Vraag AI
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.
Awesome!
Completion rate improved to 3.33
Else Expression
Veeg om het menu te tonen
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.
Bedankt voor je feedback!