Monday 21 December 2015

SWITCH STATEMENT IN C++ VS. IF ELSE IF STATEMENT

SWITCH STATEMENT IN C++ VS. IF ELSE IF STATEMENT
SWITCH STATEMENT:
SYNTAX=
switch(expression)
{
    case constant-expression1  :
       statement(s) 1;
       break; //optional
    case constant-expression 2 :
       statement(s) 2;
       break; //optional
.
.
.
.
.
.
case constant expression n:
Statements n ;
break;//optional 
    // you can have any number of case statements.
   default : //Optional
       statement(s);
}
if else if statement:
Syntax:
if(condition1)
{
Statements 1;
}
else if(condition 2)
{
statements 2;
}
else if(condition 3)
{
statements 3;
}
.
.
.
.
.
.
Else if(condition n)
{
Statements n;
}
Else
{
Statements;
}
Similarities:
·        Both are used to compare more than one conditions
·        In both if else if and switch statements if one condition is true its statements are executed and other conditions are not even tested
·        Both are alternatives of each other
Differences:
·        There is a lot of difference in their syntaxes
·        In if else if if none case is matched else is executed in switch default is executed
·        The main difference in both the statements is that in if else if we can compare a value with a certain range but in switch the operand must be a character or an integer so we cannot compare range the value should be exact that character or integer
As we can see in the example
#include<iostream>
using namespace std;
void main()
{
     Int num;
Cout<<”enter the number”
Cin>>marks;
if(num>0&&num<33)
          {
                   Cout<<”fail”;
}
else if(marks>=33&&marks<=60
{
          Cout<<”just pass”;
}
else if(marks>=61&&marks<=100)
{
cout<<”great marks”;
}
else
cout<<”wrong choice”;
}

We can’t do it using switch

No comments:

Post a Comment