DEV Community

Cover image for C++ else
Nuriddin152
Nuriddin152

Posted on

C++ else

Hello everyone
today we will talk about else in C++

If if is false, the code to be executed needs an else statement to execute the condition block.
Syntax:

if (condition) 
{
  // block of code to be executed if the condition is true
} 

else 
{
  // block of code to be executed if the condition is false
}
Enter fullscreen mode Exit fullscreen mode

For example

#include <iostream>
using namespace std;

int main()
{
int num = 20;
int num1 = 30;

if ( num1 + num == num1)
{
cout << "True";
}

else 
{
cout << "False";
}

return 0;
Enter fullscreen mode Exit fullscreen mode

Answer:

False
Enter fullscreen mode Exit fullscreen mode

Example explained:

num1 + num == num1 cannot be equal, so False is output to the console

if else
Use an else if statement to specify a new condition if the first condition is false

#include <iostream>
using namespace std;

int main()
{

int time = 22;

if (time < 10) 
{
  cout << "Good morning.";
} 

else if (time < 20)
{
  cout << "Good day.";
}
 else 
{
  cout << "Good evening.";
}
// Outputs "Good evening."

return 0;
}
Enter fullscreen mode Exit fullscreen mode

Example explained:
In the above example, time (22) is greater than 10, so the first condition is false. The next condition, in the else if statement, is also false, so we go to the next condition because condition 1 and condition 2 are both false - and print "Good evening" to the screen.

However, if the time was 14, our program would print "Good day".

Oldest comments (0)