SELECTION STATEMENT: IF-ELSE STATEMENT

The if keyword is used to execute the statements/ block of statements . If the condition is true then those statements will be executed else the statements under the else keyword will be executed .

SYNTAX:

if (condition )

{  ——————

–statements —

—————– }

else

{—————

–statemnts—

—————}

it’s not necessary to use an else, if you don’t use it then simply if your condition fails then nothing will happen and the next set of statement after if will be executed … i.e

if (condition )

{ ——– —–}

statemnts —-;// will get executed if the condition is false

———-;

i.e the if block will be ignored simply .

here’s a flow diagram that’ll help you to get a better understanding ….

.   EXAMPLE
2.2

For C Users

Code:


#include"stdio.h"  
int main()
        
 int i;   
 printf("Enter a number");
 scanf("%d",&i);          
 if(i>10){
 printf("\n%d is greater than 10\n",i);
  }
 else{
 printf("\n%d is less than 10\n",i);
  }
 return 0;
 }
Note:

The Input and Output function are different in compare to c++
for input ,c users use scanf(“format-string”,&variable) while c++
users use cin>>variable .
Another difference is of Header file
for c users it is #include<stdio.h> while for c++ users #include<iostream.h>

2.1

Here in this example first of all the condition in if is checked i.e whether the number entered is greater than 10 or not since its not hence it jumped to else and executed the statements in it .

NOTE: if there is only one statement after if or else then no need of putting it under braces , it by default assume that the statement below it is of the if/ else statement .The same goes for the for statement too .

Now consider the example of without else…..

2.3

2.4

here in this example since there was not else hence when the condition was checked then it didn’t satisfy it hence after that return 0; was executed …

We also can use multiple if-else statements i.e condition under a condition 

SYNTAX:

if (condition )

{————

————–}

else if (condition )

{ ————-

}

else

{————

———–}

EXAMPLE:

2.5
2.1

Here in this example we have used multiple if-else statements. Whenever we want to use multiple if -else statements the “else if ” is used as shown in the example . Here first the condition of if is checked since it didn’t satisfy it then the condition in else if is checked , but it also didn’t satisfy it hence lastly the else was checked which obviously satisfied it hence the output is obtained . it wastes  lot of memory and time hence its better to use switch ( about which we’ll discuss in next post).

The rest of the topic is continued in next post .

Have something to add in SELECTION STATEMENT: IF-ELSE STATEMENT ? Share/Ask into comments it in the comments.

Follow us on Facebook, Google Plus and Twitter

Previous                                      C Programming                                      Next