Sunday, July 20, 2014

Using if statements in C++

1. Conditional Programming Using if 
Syntax:
if (conditional expression)
         Do something when expression evaluates true;
Example:
if (x == 100)
             cout << "x is 100 ";


2. Conditional Programming Using if … else
Syntax:
if (conditional expression)
          Do something when expression evaluates true;
else // Optional
          Do something elsewhen condition evaluates false;
Example:
if (x == 100)
             cout << "x is 100 ";
else
             cout << "x is not 100";
3. Executing Multiple Statements Conditionally
Syntax:

if (condition){
            // condition success block
           Statement 1;
           Statement 2;
}
else{
           // condition failure block
          Statement 3;
          Statement 4;
}
Example:
if (x >100)
{
     cout << "x > 100 ";
     cout << x;
}
else
{
     cout << "x <= 100 ";
     cout << x;
}
4. Nested if Statements
Syntax:

if (expression1)
{
        DoSomething1;
        if(expression2)
               DoSomething2;
        else
               DoSomethingElse2;
}
else
        DoSomethingElse1;
Example:
float mark;
cout<<"Input mark: "; cin>>mark;
if(mark>=0 && mark<=10){
      if(mark>=8.5)
               cout<<"A";
      else if(mark>=7.0)
               cout<<"B";
      else if(mark>=5.5)
               cout<<"C";
      else if(mark>=4.0)
               cout<<"D";
      else
               cout<<"F";
}
else
      cout<<"Mark wrong !";

No comments:

Post a Comment