C if, if-else and switch statements

C programming language provides two types of control statements.

  1. Selection or Decision Control Statements – The decision and case control statements allow selective processing of a statement of a group of statements. These are also called as Conditional Statements.
  2. Repetition or Loop Control Statements – The Loop control statement executes a group of statements repeatedly till a condition is satisfied

Statements and blocks

An expression becomes a statement when a semicolon follows it. Braces {and} are used to group declarations and statements together into a compound statement, or block, so that they are syntactically equivalent to a single statement. There is no semicolon after the right brace that ends a block.

Selection or Decision control statements

The major decision making constructs of C language are:
1. The if statement
2. The if-else statement
3. The switch statement

The if statement

The if statement is used to specify conditional execution of a program statement, or a group of statements enclosed in braces.

The general format of if statement is:

if (expression)
{
    statement-block;
}
program statement;

When an if statement is encountered, expression is evaluated and if its value is true, then statement-block is executed, and after the execution of the block, the statement following the if statement (program statement) is executed. If the value of the expression is false, the statement-block is not executed and the execution continues from the statement immediately after the if statement (program statement).

* Program to print the maximum of the two given numbers using if statement */void main(void)
{
   int n1, n2, max;
   printf(“Enter two numbers: ”);
   scanf(“%d%d”, &n1, &n2);
   max = n1;
   if (n2 > n1)
       max = n2;
   printf(“The Maximum of two numbers is: %d \n”, max);
}

The if …else statement

The purpose of if-else statement is to carry out logical tests and then, take one of the two possible actions depending on the outcome of the test.

The general format of if-else statement is:

if (expression)
{
    /* if block */    true-statement-block;
}
else
{
    /* else block */    false-statement-block;
}

If the expression is true, then the true-statement-block, which immediately follows the if is executed otherwise, the false-statement-block is executed.

/* Program to check whether the given number is even or odd */void main()
{
   int num;
   printf(“Enter a number: ”);
   scanf(“%d”, &num);
   if ((num % 2) = = 0)
   printf(“%d is even \n”, num);
   else
   printf(“%d is odd \n”, num);
}

The group of statements after the if but not including the else is known as an if block. The statements after the else form the else block. When the if block or the else block contains more than one statements they have to be enclosed in a pair of { } braces. When the if or else block contain only one statement it need not be enclosed in braces as written in the example above.

Note: Its always a good practice to enclose the if, else or any loop blocks in the braces for maintainability of the code.

Nested conditional constructs

The if statement can be included within other if block, the else block or of another conditional statement.

if (expression1)
{
   true-statement1-block;
   if (expression2)
   {  
       true-statement2-block;
   }
}
   else
   {
       false-statement1-block;
   }

The else if .. statement

This sequence of if statements is the most general way of writing a multi-way decision. The expressions are evaluated in order; if any expression is true, the statement associated with it is executed, and this terminates the whole chain.

if (expression1)
{
    statement-block1;
}
else if (expression2)
{
    statement-block2;
}
else
{
    default-statement-block;
}

The last else part handles the “none of the above” or default case where none of the other conditions is satisfied. If there is no explicit action for the default then the else block can be omitted.

/* Program to calculate and print telephone bill for customers by checking certain conditions */void main(void)
{
   int units, custno;
   float charge;
   printf(“Enter customer no and units consumed: ”);
   scanf(“%d%d”, &custno, &units);
   if (units <= 200)
        charge = 0.5 * units;
   else if (units <= 400)
        charge = 100 + 0.65 * (units - 200);
   else if (units <= 600)
       charge = 230 + 0.8 * (units - 400);
   else
       charge = 390 + (units - 600);
   printf(“Customer No: %d consumed %d units \n”, custno, units);
   printf(“The total bill amount is : %.2f \n”, charge);
}

The switch statement

The switch statement is a multi-way decision that tests whether an expression matches one of a number of constant integer values, and branches accordingly.

switch (expression) 
{ 
   case value1: 
       statement-block1; 
       break; 
   case value2: 
       statement-block2: 
       break; 
       ... 
   default: 
       default-block; 
}

If the switch expression matches a case expression, the statements following the case expression are processed until a break statement is encountered or the end of the switch body is reached. In the following example, break statements are not present. If the value of text[i] is equal to ‘A’, all three counters are incremented. If the value of text[i] is equal to ‘a’, lettera and total are increased. Only total is increased if text[i] is not equal to ‘A’ or ‘a’.

char text[100]; 
int capa, lettera, total; 

// ... 

for (i=0; i<sizeof(text); i++) { 

   switch (text[i]) 
   { 
       case 'A': 
           capa++; 
       case 'a': 
           lettera++; 
       default: 
           total++; 
   } 
}

The following switch statement performs the same statements for more than one case label:

/** 
 ** This example contains a switch statement that performs 
 ** the same statement for more than one case label. 
 **/ 

#include  <stdio.h>
int main(void) 
{ 
    int month; 
    
    /* Read in a month value */ 
    printf("Enter month: "); 
    scanf("%d", &month); 
    
    /* Tell what season it falls into */ 
    switch (month) 
    { 
      case 12: 
      case 1: 
      case 2: 
            printf("month %d is a winter month\n", month); 
            break; 
      
      case 3: 
      case 4: 
      case 5: 
            printf("month %d is a spring month\n", month); 
            break; 
      case 6: 
      case 7: 
      case 8: 
            printf("month %d is a summer month\n", month); 
            break; 
      case 9: 
      case 10: 
      case 11: 
             printf("month %d is a fall month\n", month); 
             break; 
      case 66: 
      case 99: 
      default: 
             printf("month %d is not a valid month\n", month); 
    } 
    
    return(0); 
} 

If the expression month has the value 3, control passes to the statement:

printf("month %d is a spring month\n",month);

The break statement passes control to the statement following the switch body.

Related Post