if and if-else statements

This is used to decides whether to do something at a special point, or to decide between two courses of action. Formally the syntax is

if (expr)
    statement1;
else
    statement2;

where the else part is optional. The expr evaluated; if it is true, the statement 1 is executed. If it is false and if there is an else part, statement2 is executed. After this, the rest of the program continues as usual.


img
img

The following test decides whether a student has passed an examination with a pass mark of 45

If (result >= 45)
    Printf (“pass\n”);
Else
    Printf (“fail\n”);

It is possible to use the if part without the else.

if (temperature<0)
printf (“frozen\n”);


If we wish to have more than one statement following the if or the else, they should be grouped together between curly braces. Such a grouping is called a compound statement or a block.

If (result >= 45)
{
    Printf (“passed \n”);
    Printf (“congratulation \n”);
}
Else

{
    printf (“failed \n”);
    printf (“good luck, try for next\n”);
}

Because the else part of an if - else is optional, there I is an ambiguity when an else is omitted from a nested if sequence. This is resolved by associating the else with the closest previous else – less if. For example, in following if statement:

if (n>0)
    if (a>b)
        z = a;
    else
        z = b;

The else goes with the inner if. If that is not what you want, braces must be used to force the proper association as given below:

If (n>0)
{
    if (a>b)
        z = a;
}
Else
    Z = b;


About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext