if else statement in C++

if else statement in C++ 

In if else statement, there is only one condition. If  condition is true, one set of statements will be executed otherwise another set of statements will be executed.

Syntax of if else statement in C++ is:

if(Test-Condition)
{
  Statement-Block1;
}
else
{
  Statement-Block2;
}

Test-Condition is any conditional expression If  it is true, then Statement-Block1 gets executed otherwise Statement-Block2 gets executed.

 

 Program to demonstrate the use of if else statement in C++.

#include<iostream>
using namespace std;
int main()
{
 int n;
 cout<<“\nEnter a number=";
 cin>>n
 if(n>0)
   cout<<“Number is +ve";
 else
   cout<<“Number isn't +ve";
 cout<<“\nBye";
 return(0);  
}

Output

Enter a number= -5
Number is -ve
Bye

*In the above program, variable n has been entered as -5.  Condition n>0 is false so very next statement after  else would be executed i.e.  cout<<“Number is -ve” followed by  cout<<“\nBye”.

Spread the love
Lesson tags: if else in c, if else statement in C++
Back to: C++ Programming Notes
Spread the love