Conditional statement
Condition ? statement1 : Statement2 ;
is known as conditional statement which is an alternative of simple if-else statement.
If ( condition )
Statement1
Else
Statement2
? : is known as conditional operator.
Conditional statement consists of 3 operands, first contains the condition and it is evaluted only as true or false, second is the operand(statement) which is evaluted if the answer to the first operand comes out to be true and third is the operand(statement) which is evaluted in case if the answer to the first operand comes to be false.
Example
GetLargest() function take 2 input parameters and returns the largest of two using conditional statement:
return a > b ? a : b;
This statement means that if a is greater than b then evalute the first statement which returns a else evalute the second statement which returns b.
GetSmallest() function take 2 input parameters and returns the smallest of two using conditional statement:
return a < b ? a : b;
This statement means that if a is smaller than b, then evalute the first statement which returns a else evalute the second statement which returns b.
Code
#include "stdafx.h"
#include "iostream"
#include "conio.h"
using namespace std;
int GetLargest( int a , int b )
{
return a > b ? a : b;
}
int GetSmallest( int a , int b )
{
return a < b ? a : b;
}
int main()
{
cout << "Largest from 5 and 8 is : " << GetLargest( 5 , 8 ) << endl;
cout << "Smallest from 5 and 8 is : " << GetSmallest( 5 , 8 ) << endl;
_getche();
return 0;
}
Output
Largest from 5 and 8 is : 8
Smallest from 5 and 8 is : 5
0 comments:
Post a Comment