Thursday, October 18, 2012

if, if else

if:

if statement is used to execute a code or a series of codes if and only if the condition is met. The form is:

if (condition)
     statement;

The condition is the expression that is being evaluated. If it is true, statement is executed. If it is false, statement is not executed.

If you want to execute a series of statements/codes, you should use curly braces { }. The form is:

if (condition)
{
    statements;
    statements;
}

Examples:

int x=0;

if (x==0)
    cout<<"X is "<<x<<endl;

if (x==1)
    cout<<"X is 1";
cout <<"X is not 1";

if (x==0)
{
    cout<<"X is 0";
    cout<<"X is not 1";
}


if else:
if else control structure is very similar to if statements. We will just add the else keyword if the condition is false. The form is:

if (condition)
    statement;
else
    statement;

If the condition is false, the statement in the else will be executed. Again, if you want to execute a series of statements/codes, you should use curly braces { }.

Example:

int x = 0;

if ( x==1)
    cout<<"X is 1";
else
    cout<<"X is not 1";

Next: switch case statements

No comments:

Post a Comment