Control Statements

Control statements enable us to specify the flow of program control; ie, the order in which the instructions in a program must be executed. They make it possible to make decisions, to perform tasks repeatedly or to jump from one section of code to another.

There are four types of control statements in C:

  1. Decision making statements
  2. Selection statements
  3. Iteration statements
  4. Jump statements

Decision Making Statement: the if-else Statement

The if-else statement is used to carry out a logical test and then take one of two possible actions depending on the outcome of the test (ie, whether the outcome is true or false).

Syntax:

if (condition)
 
{
 
  statements
 
}
 
  else
 
{
 
  statements
 
}

If the condition specified in the if statement evaluates to true, the statements inside the if-block are executed and then the control gets transferred to the statement immediately after the if-block. Even if the condition is false and no else-block is present, control gets transferred to the statement immediately after the if-block.

The else part is required only if a certain sequence of instructions needs to be executed if the condition evaluates to false. It is important to note that the condition is always specified in parentheses and that it is a good practice to enclose the statements in the if block or in the else-block in braces, whether it is a single statement or a compound statement.

The following program checks whether the entered number is positive or negative.

#include<stdio.h>
 
int main( )
 
   {
 
    int a;
 
    printf("n Enter a number:");
 
    scanf("%d", &a);
 
    if(a>0)
 
     { 
 
      printf( "n The number %d is positive.",a);
 
     }
 
    else
 
     {
 
      printf("n The number %d is negative.",a);
 
     }
 
  return 0;
 
   }

The following program compares two strings to check whether they are equal or not.

#include <stdio.h>
 
#include <string.h>
 
int main( )
 
   {
 
    char a[20] ,  b[20];
 
    printf("n Enter the first string:");
 
    scanf("%s",a);
 
    printf("n Enter the second string:");
 
    scanf("%s",b);
 
    if((strcmp(a,b)==0))
 
      {
 
       printf("nStrings are the same");
 
       }
 
    else
 
      {
 
      printf("nStrings are different");
 
      }
 
  return 0;
 
  }

The above program compares two strings to check whether they are the same or not. The strcmp function is used for this purpose. It is declared in the string.h file as:

int strcmp(const char *s1, const char *s2);

It compares the string pointed to by s1 to the string pointed to by s2. The strcmp function returns an integer greater than, equal to, or less than zero,  accordingly as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2.

Therefore in the above program, if the two strings and b are equal , the strcmp function should return a 0. If it returns a 0, the strings are the same; else they are different.

Nested if and if-else Statements

It is also possible to embed or to nest if-else statements one within the other. Nesting is useful in situations where one of several different courses of action need to be selected.

The general format of a nested if-else statement is:

if(condition1)
{
// statement(s);
}
else if(condition2)
{
//statement(s);
}
.
.
.
.
else if (conditionN)
{
//statement(s);
}
else
{
//statement(s);
}

The above is also called the if-else ladder. During the execution of a nested if-else statement, as soon as a condition is encountered which evaluates to true, the statements associated with that particular if-block will be executed and the remainder of the nested if-else statements will be bypassed. If neither of the conditions are true, either the last else-block is executed or if the else-block is absent, the control gets transferred to the next instruction present immediately after the else-if ladder.

The following program makes use of the nested if-else statement to find the greatest of three numbers.

#include<stdio.h>
 
int main( )
   {
       int a, b,c;
       a=6,b= 5, c=10;
       if(a>b)
          {
             if(b>c)
               {
                 printf("nGreatest is: " , a);
                }
              else if(c>a)
                     {
                      printf("nGreatest is: ", c);
                     }
            }
         else if(b>c)     //outermost if-else block
                {
                 printf("nGreatest is: " , b);
                }
               else
                {
                 printf( "nGreatest is: " , c);
                }
      return 0;
    }

The above program compares three integer quantities, and prints the greatest. The first if statement compares the values of and b. If a>b is true, program control gets transferred to the if-else statement nested inside the if block, where b is compared to c. If  b>c is also true, the value of a is printed; else the value of c and a are compared and if c>a is true, the value of c is printed. After this the rest of the if-else ladder is bypassed.

However, if the first condition a>b is false, the control directly gets transferred to the outermost else-if block, where the value of b is compared with c (as a is not the greatest). If b>c is true the value of b is printed else the value of c is printed. Note the nesting, the use of braces, and the indentation. All this is required to maintain clarity.

Selection Statement: the switch-case Statement

A switch statement is used for multiple way selections that will branch into different code segments based on the value of a variable or expression. This expression or variable must be of integer data type.

Syntax:

switch (expression)
{
  case value1:
    code segment1;
    break;
  case value2:
    code segment2;
    break;
.
.
.
  case valueN:
    code segmentN;
    break;
  default:
    default code segment;
}

The value of this expression is either generated during program execution or read in as user input. The case whose value is the same as that of the expression is selected and executed. The optional default label is used to specify the code segment to be executed when the value of the expression does not match with any of the case values.

The break statement is present at the end of every case. If it were not so, the execution would continue on into the code segment of the next case without even checking the case value. For example, supposing a switch statement has five cases and the value of the third case matches the value of expression. If no break statement were present at the end of the third case, all the cases after case 3 would also get executed along with case 3. If break is present only the required case is selected and executed; after which the control gets transferred to the next  statement immediately after the switch statement. There is no break after defaultbecause after the default case the control will either way get transferred to the next statement immediately after switch.

Example: a program to print the day of the week.

#include<stdio.h>
 
int main( )
 
    {
 
     int day;
 
     printf("nEnter the number of the day:");
 
     scanf("%d",&day);
 
     switch(day)
        {
          case 1:
                  printf("Sunday");
                  break;
          case 2:
                  printf("Monday");
                  break;
          case 3:
                  printf("Tuesday");
                  break;
          case 4:
                  printf("Wednesday");
                  break;
          case 5:
                  printf("Thursday");
                  break;
          case 6:
                  printf("Friday");
                  break;
          case 7:
                  printf("Saturday");
                  break;
          default:
                  printf("Invalid choice");
        }
   return 0;
 
     }

This is a very basic program that explains the working of the switch-case construct. Depending upon the number entered by the user, the appropriate case is selected and executed. For example, if the user input is 5, then case 5 will be executed. The break statement present in case 5 will pause execution of the switch statement after case 5 and the control will get transferred to the next statement after switch, which is:

return 0;

It is also possible to embed compound statements inside the case of a switch statement. These compound statements may contain control structures. Thus, it is also possible to have a nested switch by embedding it inside a case.

All programs written using the switch-case statement can also be written using the if-else statement. However, it makes good programming sense to use the if statement when you need to take some action after evaluating some simple or complex condition which may involve a combination of relational and logical expressions (eg, (if((a!=0)&&(b>5))).

If you need to select among a large group of values, a switch statement will run much faster than a set of nested ifs. The switch differs from the if in that switch can only test for equality, whereas if can evaluate any type of Boolean expression.

The switch statement must be used when one needs to make a choice from a given set of choices. The switch case statement is generally used in menu-based applications. The most common use of a switch-case statement is in data handling or file processing. Most of file handling involves the common functions: creating a file, adding records, deleting records, updating records, printing the entire file or some selective records. The following program gives an idea of how the switch case statement may be used in data handling. It does not involve the code for file processing as we can discuss file handling in C only after we have learnt advanced concepts like pointers, structures and unions.

Example: A switch case statement used in data file processing.

#include<stdio.h>
 
int main()
 
    { //create file &set file pointer .
 
     int choice;
 
     printf("n Please select from the following options:");
 
     printf("n 1. Add a record at the end of the file.");
 
     printf("n 2. Add a record at the beginning of the file:");
 
     printf("n 3. Add a record after a particular record:";
 
     printf("nPlease enter your choice:(1/2/3)?");
 
     scanf("%d",&choice);
 
     switch(choice)
 
         {
 
           case 1:
 
                   //code to add record at the end of the file
 
                   break;
 
           case 2:
 
                   //code to add record at the beginning of the file
 
                    break;
 
           case 3:
 
                   //code to add record after a particular record
 
                    break;
 
           default:
 
                   printf("n Wrong Choice");
 
        }
 
    return 0;
 
    }

The above example of switch-case generally involves nesting the switch-case construct inside an iteration construct like do-while. In our nex post, we will discuss these iteration statements.

Related Posts

© 2024 Software Engineering - Theme by WPEnjoy · Powered by WordPress