If Else Statement in C++

If Else Statement in C++

2 min read

It is the first selection statement. It checks a particular condition, if condition evaluates to be true course-of-action is performed, it gets ignored.

Syntax:

 if(condition)
Statement; 

where a statement can be a single statement or a compound statement(sequence of statement enclosed in a pair of ‘{}’)or nothing.

Remember, not to put a semicolon after any if, else if or else statement. Always write if, else in lowercase, since they are keywords

. For example:-

int main()
{
  int a,b;
  cin>>a>>b;
  if(a>b)
  cout<<”Greatest number is”<<a; 
  return 0;
} 

OUTPUT

6 
4 
Greatest number is 6

if-else STATEMENT

Syntax:-

 if(condition)
 Statement 1;
 else
 Statement 2; 

If the expression evaluates to be true, statement 1 is executed, otherwise, statement 2 is executed.

If statement flow chart

Let’s take same example but with if-else now.

int main()
{
  int a,b;
  cin>>a>>b;
  if(a>b)
  cout<<”Greatest number is”<<a; 
  else 
  Cout<<”Greatest number is”<<b;
  return 0;
}

The difference between two program is in the first one we can only check whether a is bigger than b or not, but in the second one we can find the greatest of 2 no’s and can print it.

OUTPUT

2 
4 
Greatest number is 4

if-else-if STATEMENT

Syntax:-

 if(condition1)
 Statement 1;
 else if(condition2)
 Statement 2;
 :
 :
 else
 Statement n; 

The expressions are evaluated from the top downwards.As soon as an expression evaluates to true, its associated statement will be executed ,otherwise ladder is bypassed.

If none of the expressions are true,the final else statement get executed.In case if final else statement is missing, no action will take place.

SHORTHAND if

Ternary/conditional operator(? 🙂 can work as an alternative to if-else.

Syntax:-

 Condition?statement1:statement2; 

It will check the condition if it is true statement 1 will be executed else statement 2 gets executed.

Again from the example given above

int main()
{
  int a,b,c;
  cin>>a>>b;
  c=(a>b)?a:b;
  cout<<”Greatest number is”<<c; 
  return 0;
} 

If you liked this article please follow me on @priya123, for more latest article and status by me..

Choose your Reaction!
Leave a Comment