Lecture - 7 : Control statement in C language ( if, else, else if, nested if)


Lecture - 7
Control statement in C language



if statement
Statement execute set of command like when condition is true. 

If (condition) Statement;
The statement is executed only when condition is true. If the if statement body is consists of several statement then better to use pair of curly braces. Here in case condition is false then compiler skip the line within the if block.

void main()
{
int n;
printf (“ enter a number:”); scanf(“%d”,&n);
If (n>10)
Printf(“ number is grater”);
}

Output:
Enter a number:12 Number is greater

if…..else ... Statement
It is bidirectional conditional control statement that contains one condition & two possible action. Condition may be true or false, where non-zero value regarded as true & zero value regarded as false. If condition are satisfy true, then a single or block of statement executed otherwise another single or block of statement is executed.
Its syntax is:-

if (condition)
{
Statement1; Statement2;
}
else
{
Statement1; Statement2;
}

  • Else statement cannot be used without if or no multiple else statement are allowed within one if statement. It means there must be a if statement with in an else statement.
Example:-

/* To check a number is eve or odd */
void main()
{
int n;
printf (“enter a number:”); sacnf (“%d”, &n);
If (n%2==0)
printf (“even number”);
else
printf(“odd number”);

Output: 
enter a number:121 odd number


Nesting of if …else
When there are another if else statement in if-block or else-block, then it is called nesting of if-else statement.
Syntax is :-

if (condition)
{
If (condition) Statement1;
else
}
statement2;
Statement3;
If….else LADDER

In this type of nesting there is an if else statement in every else part except the last part. If condition is false control pass to block where condition is again checked with its if statement.
Syntax is :-

if (condition) 
Statement1;
else if (condition) 
statement2;
else if (condition) 
statement3;
else 
statement4;

This process continue until there is no if statement in the last block. if one of the condition is satisfy the condition other nested “else if” would not executed.
But it has disadvantage over if else statement that, in if else statement whenever the condition is true, other condition are not checked. While in this case, all condition are checked.

Comments

Most popular post

Lecture 11 : Local, Global and Static variable monolithic vs modular programming, Storage classes, storage class cont.., pointer in C programming language

Lecture 3: Character set, identifiers, keywords