Sunday 20 December 2015

TERNERY OPERATOR VS IF ELSE


TERNERY OPERATOR:
SYNTAX:
(CONDITION? STAEMENTS IF TRUE: TATEMENTS IF FALSE)
EXPLANATION:
It consists of 3 statements:
·        Condition
·        Statements if true
·        Statements if false
It is an alternative of if else only if if the statements to be executed in if and else part are 1 if there are more than 1 statements in if else ternary operator cannot be used
IF ELSE IF
Syntax:
if(condition)
{
            statements;
}
else
{
            statements; 
}
Explanation:
It contains 2 blocks:
            if block
            else block
Tests the condition in if block
If the condition is true the 1st block is executed if it is false second block is executed
For Example:
Problem:
            Get two numbers from user if the first is divisible by second display the quotient if not display the quotient and remainder
#include<iostream>
using namespace std;
void main()
{           int num1,num2;
cout<<”enter the number”;
            cin>>num1;
cout<<”enter the second number”
cin>>num2;
if(num1%num2==0)
{
            cout<<num1/num2;
}
else
{
cout<<”quotient”<<num1/num2;
cout<<”remainder=”<<num1%num2;
}
This problem cannot be solved by ternary operator because else part contains 2 statements


No comments:

Post a Comment