If else in C (Conditional statements)12 min read

In C, the if-else statement is used to carry out operations based on a set of conditions. If and only if the supplied condition is true, the operations stated in the if block is executed.

In the C programming language, there are several different types of if statements.

  • if condition
  • If-else condition
  • If else-if ladder
  • Nested if

1. Control Statements

  • In a monolithic program, the compiler executes the instruction or statement one by one in a sequential manner.
  • But there are many situations when one would like to alter this execution with a few instructions being executed only when a certain condition is met or terminate the execution when a certain condition is satisfied and stops the further processing and usually referred to as branching statement.
  • There might be a situation where one would like to execute the same set of instructions again and again as long as the condition is true.

The solution for the above problem is to include or use a control flow statement, provided by the language, which is used to alter the normal order of execution. The control structure in the ‘C’ language provides the following statements,

if else in c

2. Conditional Statements

  • The statements that are used in ‘C’ to perform the task of decision-making can be classified into bi-directive and multiple branching.
  • In a bi-directive statement out of two blocks (true and false block) only one of the blocks of the if statement will be executed when the condition is satisfied. The statement if, if-else, and the else-if statement is used under this construct.
  • In multiple branching out of many alternative blocks, one of the blocks will be executed when the condition is satisfied. Only statement switch is used under this construct.

3. if Statement (Uni-directional Statement)

  • Using a general if statement a general decision-making capability is constructed and used to compare either two integers or floating or character or string values.
  • The condition(s) in the form of relational expression and/or logical expression must be placed within the parenthesis preceded with the keyword if and should not be terminated with a semicolon. The parenthesis is followed by at least a single statement, which is executed only if the condition is true. When the condition is evaluated to false then the statement or the statement within curly braces is skipped without execution and control execution continues with a statement following the keyword if statement. If only one instruction is to be executed then braces are not required.
  • observe that the above syntax does not provide any mechanism when the condition is evaluated to false. When the braces are not used then ‘C’ evaluates only one statement associated with if statement Semicolon at the end of if statement mollifies the scope of if statement and executes all the states that follow if statement irrespective of the condition is true or false?
  • Whenever a condition is evaluated in ‘C’, it is given a value of 0 if the condition is not satisfied and non-zero otherwise i.e. a non-zero number is always treated as a true value.

Syntax :

If (Conditional true)
{
  Instruction 1;
  Instruction 2;
} 

4. if-else Statement (Bi-directional statement)

The if-else statement is an extension of the general if statement and provide two-way branching of control We observe that, General if statement does not provide any mechanism when the condition is evaluated to false4 The pair of if-else statement is used to carry out a logical test and pass the control to one of block i.e. either if-block (true) or else block (false).

Syntax :

if ( Condition true ) 

 {
    Statement (s);      /* if block */
 }
 
 else
 
 {
    
    Statement(s);       /* else block */

 }

In the above syntax, when the condition is satisfied then the control branch to if-block or true block otherwise control is transferred to the else-block or false block. Here the condition is built up with the help of relational and/or logical expression.

How you will determine that number is even or odd? Divide the number by two and find the remainder. If it is zero it means the number is even otherwise it is considered odd.

Example

To check number is even or odd

#include <stdio.h>
#include <conio.h>

void main(void)
  
{
  
  int num,rem; 
  printf(" Enter number :- "); 
  scanf("%d", &num); 
  rem = num % 2; 
  
  if (rem == 0)
    printf (" Number %d is Even", num); 
  else
    printf (" Number %d is Odd", num); 
  
  getch();
  
}

5. Nested If’s

When the entire if-else statement is written within either the body of if statement or within the body of an else statement and known as nested or embedded if’s in a nested-if statement, it is not necessary to have a number of if and else statement as use of else statement is optional During nested-if remember that else clause is always associated with the preceding if statement that does not pair with an else statement and use indenting technique to avoid conflict.

Syntax :

if (condition true)
{
    Statment(s);
}

else

{

    if (condition true)
    {
      Statement(s);
    }
    else
    {
      Statement(s);
    }
     
}

In nested if, an else is associated with the closed previous if.

Example

Consider the following example where the user wants to check whether the number is positive or negative or zero.

#include<stdio.h>
#include<conio.h> 

void main(void)

{

  int num; 
  
  clrscr(); 
  
  printf(" enter a number :- "); 
  scanf("%d", &num); 
  
  if(num >0)
    printf(" number is positive"); 
  
  else 
    
    if(num <0) 
      printf(" number is negative"); 
    else 
      printf(" number is zero "); 
  
  getch();
  
}

After accepting a number, first of all, we are checking whether the number is greater than zero or not, if so program will be terminated after displaying a message that the number is positive otherwise it will check another condition that whether the number is less than zero if so, a message number is negative will be displayed otherwise it will be concluded that number is zero.

6. else-if ladder

Example

Consider the following example where we are offering a kind of chocolate depending upon the age of the person.

#include<stdio.h> 
#include<conio.h> 

void main(void) 
  
{

  int age; 
  
  clrscr(); 
  
  printf(" Enter the age :- "); 
  scanf("%d", &age); 
  
  if (age = = 5 ) 
    printf("Milky Box "); 
  
  else 
    
    if ( age == 18 ) 
      printf( "Coffy bar");
  
  else
    
    if ( age == 21 ) 
      printf ( "Nestle bar" ); 
  
  else 
    
    if ( age == 58 ) 
      printf (" Toffy"); 
    else 
      printf ("Sorry"): 

  getch();
  
}

The logic of the above program is very straightforward, after accepting the age which condition is matched and accordingly will display the message. When none of the conditions match it will print the message “Sorry”. When there is a number of nested else-if statements in the program then it is referred to as the else-if ladder or else-if chain.

7. EMPTY Statement

It is necessary that every if statement must have an else sometimes program logic, becomes clearer when matching else’s are written specially in a nested branching without having any statement and called as Empty or NULL Statement. A NULL statement is just a semicolon.

For example,

if (Condition) 

  Statement(s); 

else 

  /* No Statement except semicolon */ 

8. Switch Statement (Multi-way Statement)

  • Usually, the if-else statement provides a two-way branching of control. For selecting one of the options out of many if statements, if we used the if-else statement then maintaining the indent of such a program is difficult and the program will be cumbersome to read.
  • Thus to select one choice out of many options ‘C’ provides a multi-way conditional statement called a switch statement is used.
  • The switch expression either integer or Character (which is converted into equivalent ASCII integer value) is evaluated against the unique case value, value1, value2, …….., value n, which need not be in any particular order but its value must be either constant or constant expression only.

Syntax :

switch (expression) 

{
    case value1: 
    statement(s); 
    break; 

    case value2: 
    statement(s);
    break; 

    case value3: 
    statement(s);
    break;

    default: 
    statement(s);
    break;
}
  • If the case value is matched then control transfers to the match case and executes all the statements until a break statement is encountered.
  • Thus break statement signals the end of a particular case and causes the execution of the switch statement to be terminated. If a break statement is not used then control will transfer to another case.
  • The break statement for the last case value is optional.
  • When the value of the expression does not match any of the case values then the special optional case called default is executed if written. Otherwise, control is transferred to the next statement followed by the switch statement body. Like nested else-if, we can also have a nested switch.
  1. The cases and default can occur in any order.
  2. The expression is implicitly converted into an integer.
  3. It is the programmer’s responsibility to add break statement i.e. In ‘C’ automatic break mechanisms are not implemented into the switch statement as supported by Visual Basic.

Example

Consider the same example that we have seen in the else-if ladder using a switch statement,

#include<stdio.h> 
#include<conio.h> 

void main (void)

{

  int age; 
  printf ("Enter age :- "); 
  scanf("%d", &age ); 
  
  clrscr();
  switch ( age ) 
  
  { 
  
  case 5: 
  printf( "Milky box" ); 
  break;
  
  case 36/2: 
  printf ("Coffy bar" ); 
  break; 
  
  case 20 +1: 
  printf ("Nestle bar" ); 
  break; 
  
  default : 
  printf ("Sorry");
  break;
  
  case 58 : 
  printf ("Toffy" ); 
  break;
  
  }
  
}

Observe that the above program is more readable compared to the equivalent program that we have written using the else-if ladder. One more thing, note that we have not written the case value in any particular order and we don’t know how the compiler determines or search the case value and execute it.

Example

Consider another example where we want to determine the number of days in a month and check whether the entered date is valid or not.

#include<stdio.h> 
#include<conio.h> 

void main(void) 

{

  int day, month, year, nod; 
  clrscr(); 
  
  printf(" Enter Date :- "); 
  scanf("%d %d %d",&day, &month, &year); 
  
  switch (month) 
  
  {

  case 1: 
  case 3: 
  case 5: 
  case 7: 
  case 8: 
  case 10: 
  case 12:
    nod 31; 
    break;
  
  case 4: 
  case 6: 
  case 9:
    nod = 30;
    break; 
  
  case 2:
    nod = (year%4 ==0? 29 : 28);    /* Ternary operation */
    break;
      
  default:
    printf(" Wrong Date "); 
  
  } 
  
  if(nod <day)
    printf(" Wrong Date"); 
  else
    printf(" Valid Date "); 
  
  getch(); 
  
}
  • Observe that for a number of case values the solution is the same, i.e. for the month of January, March, May, July, August, October, and December number of days in the month is 31 similarly for the month of April, June, and September number of days are 30.
  • February is a special case and either it will contain 29 or 28 days depending upon whether a year is a leap or not respectively.
  • Thus after knowing the number of days in the month, at last, we are determining whether the date is valid or not.

9. Difference between if-else and Switch Statement

  1. In if-else there is no restriction of data type while comparison but in a switch statement, the value of expression should be only integer or character (Each character has some equivalent ASCII value which is an integer value) only.
  2. The if-else statement can evaluate relational or logical expression but the switch statement is only useful to test for equality (i.e. only constant value).
  3. One can repeat some condition more then once using if but switch does not allows to have two cases value to be identical.
  4. if-else statement is useful when there are only two branches for a given condition, while the switch statement is most suitable for a program like a menu-driven program having many options.
  5. A program written using switch statement can be written using if-else (since switch is an extension of if-else statement) but vice-versa is not always true.
  6. There is no restriction on the depth of the if-else-if ladder but the number of switch cases is compiler dependent. In Turbo C we can have a maximum of 257 cases in the switch statement.
  7. If the ladder is two long, then program logic becomes difficult to comprehend in the if-else statement but by using a switch statement program readability improves.

Examples

Example 1

void main() 

{ 
  
  int a=2;
  switch(a)
 
  {
    
    case 1 : printf(" hello ");
    break; 
      
    case a:  printf(" bye ");
    break;
  
   } 

} 

Example 2

void main()

{
  
  int a=67;
  switch(a-1) 
 
  { 
 
    case 66: printf("B");
             break;
      
    case 65: printf("A");
             break; 
    
    case 'B': printf("B"); 
 
  }
 
}

Example 3

void main() 

{ 

  clrscr(); 
  switch(3/2.0) 
  
  { 
  
    case 1 : printf(" Hello "); 
             break; 
    
    case 2 : printf("bye"); 
    
  } 
   
  getch(); 
  
} 

In the first instance, it looks like it is an error, as the switch statement contains a floating value. But remember that, expression is implicitly converted into an integer. Therefore the result is 1 and output in Hello.

Example 4

A program for testing leap year

#include<stdio.h> 
#include<conio.h> 

void main(void) 

{
  
  int year;
  
  clrscr(); 
  
  printf("\n\t Enter Year :- "); 
  scanf("%d",&year); 
  
  if ((year % 4 == 0 && year % 100 !=0) || (year % 4000 == 0))
    printf(" %d is a leap year", year); 
  else
    printf("%d is not a leap year", year); 
  
  getch();
  
}

Example 5

A program to find the largest among any five numbers with minimum condition

#include <stdio.h>
#include <conio.h> 

void main(void) 

{

  int a,b,c,d,e; 
  int lar; 
  
  clrscr(); 
  
  printf(" Enter any 5 values ");
  scanf("%d %d %d %d %d", &a, &b, &c, &d, &e); 
  lar = a    /* Assume first number itself a largest a */
  
  if(b > lar)
    lar = b; 
  if(c> lar)
    lar = c;
  if(d> lar)
    lar = d; 
  if(e > lar)
    lar = e;
  printf(" Largest element is %d",lar); 
  
  getch();
  
}

Example 6

A program to find the roots of

#include<stdio.h> 
#include<conio.h> 
#include <math.h> 

void main(void) 

{

  int a,b,c,d; 
  float x1, x2, x; 

  clrscr(); 
  
  printf("Enter coefficient of equation :- "); 
  scanf("%d %d %d", &a, &b, &c); 
  d = b * b - 4 * a * c; 

  if(d > 0) 

  {

    printf(" \n\n Roots are Real and Different "); 
    x1 = ( -5 + sqrt(d))/(2*a); 
    x2 = ( -b - sqrt(d))/(2*a);
    printf("x1=%.2f x2 = %.2f",x1,x2); 
 
  } 
 
  else
 
    if ( d == 0 ) 
 
    {
    
      printf("\n\n Roots are Real and Equal "); 
      x = -b/(2*a); 
      printf("x = %.2f",x);
      
    }
  
    else
      
      printf ("\n\n Roots are complex");
  
}

Share:

Leave a Reply