CHAPTER 5

Multi-Way Decision Making

We come across many situations where we have to make decisions among many alternatives. For example, a university awards a grade to a student as either A or B or C or D or E based on his marks, a specific business house gives a discount depending on the amount of purchase made, a bank gives interest on the amount deposited depending on the time period for which the deposit is made and so on. A careful observation of all the examples cited above reveals the fact that one has to choose an alternative among many alternatives. The process of selecting an alternative among many alternatives is generally referred to as multiway decision making. Multiway decision making can be implemented using two way decision making facilities. However most of the computer languages provide an exclusive facility to manage multiway decision making. In C multiway decision is made by employing the switch construct. Some examples which employ multiway decision making are discussed in this chapter.

5.1 SOLVING GIVEN QUADRATIC EQUATION USING MULTI-WAY DECISION MAKING FACILITY

The Method

As already discussed in Section 3.6 an equation of the form ax2 + bx + c = 0 is known as a quadratic equation. Solving a quadratic equation means finding out its roots. Every quadratic equation will have two roots. While solving a quadratic equation one of the important steps is to compute the discriminant using the relation discriminant = (b2 - 4ac). This discriminant could be zero, positive or negative. Obviously, for solving this problem we have to consider three cases: one for zero value of the discriminant, one for a positive value of the discriminant and another for a negative value of the discriminant. These three cases may be mapped (translated) on to some case values using some simple arithmetic or logical operations and then a multiway decision making facility of the coding (programming) language is used. For example, computed goto of FORTRAN, switch of C, etc. provide the necessary multiway branching.

Let some variable (say, flag) is used to store the different case values. Different case values are obtained and stored in this variable flag using the following strategy.

images

C-Tips

The switch statement is used to get the multiway branching. The general format of this statement is

switch (expression)
{   
       case value-1 :...... .   
                     ...... .
                     break;
        
       case value-2 :...... .
                     ...... .
                     break;
         .
        .
        .
    
       case value-n :...... .
                     ...... .
                     break;
        
            default :...... .
                     ...... .
                     break;
}

When the control comes to a switch statement the expression that appears with it is first evaluated. This evaluation must result in some integer value (i_v). Then the control gets into the switch block made up of many number of cases including an optional default block. The value i_v is compared with case values value-1, value-2,........., one after the other. If i_v and case value match then that particular case block is executed. As we are generally interested only in one case, the last statement in a case block will be generally the break statement. Thus after executing a case block the control goes out of the entire switch block. If none of the case blocks are executed then the default block, if present, will be executed.

The entire behavior of the switch statement can be pictorially represented as shown in the flowchart given below.

images

Depending upon the value stored in the variable flag, the roots are computed using the relations shown in the flow chart (also refer to Section 3.6) given in the next page.

Flowchart

images

The Program

/* Solving a quadratic equation using multiway decision making facility */

#include<conio.h>                    /* Including header file */
#include<stdio.h>
#include<math.h>
main()
{
float a,b,c,disc,root1,root2,part_r,part_i;
int flag;                        /* Declaring variables */
clrscr();                        /* Clearing the Screen */
printf(“

Enter co-efficients of the quadratic equation

”);
scanf(“%f%f%f”, &a, &b, &c) ;
printf(“
Co-efficients are a = %f	 b = %f	 c = %f 

”, a,b,c);
if (a==0 || b==0 || c==0)
        /* If any one co-efficent is zero roots cannot be calculated */
printf (“Zero co-efficient
”);
else
{
disc=b*b-4*a*c;/* Calculating discriminant*/
if ( disc == 0) flag = 0;
        if ( disc > 0) flag = 1;
        if ( disc < 0) flag = 2;

        switch( flag )
        {
           case 0 : printf (“Rootl = b1 (2*a); are real and equal
”);
                    root2 = rootl;
                    printf(“
Root1 = %f	 Root2 = %f
”,rootl, root2);
                    break;
        
           case 1 : printf (“Roots are real and distinct 
”);
                    printf(“
”);
                    root1 = (-b+sqrt(disc))/(2.0*a);
                    root2 = (-b-sqrt(disc))/(2.0*a);
                    printf(“
Root1 = %f	 Root2 = %f
”,root1, root2);
                    break;
        
           case 2 : printf(“Roots are complex
”);
                    part_r = -b/(2.0*a);
                    part_i = sqrt(-disc)/(2.0*a);
                    printf(“Root1 = %f + i %f	Root2 = %f -i %f 
”
                           , part_r, part_i, part_r, part_i) ;
                    break;

         }
     }
}

5.2 AWARDING GRADES BASED ON MARKS SCORED IN AN EXAMINATION

Quite often computers are used for processing examination results. This processing depends upon the policy adopted by the concerned institution or university. Typically, let us consider a situation where grades are awarded according to the following set of rules.

  1. Grade A is awarded for all those who score 80 or more.
  2. Grade B is awarded for all those who score 70 and above but below 80.
  3. Grade C is awarded for all those who score 60 and above but below 70.
  4. Grade D is awarded for all those who score 40 and above but below 60.
  5. Grade E is awarded for all those who score less than 40.

The Method

A careful observation of the given set of rules reveals the fact that we have to employ multiway branching technique. One of the methods to achieve the required multiway branching is to use if.....else ladder to implement the entire set of rules. However, using switch (using which one can switch on to one of many branches) is simple and straight forward.

This problem can be solved by mapping or translating the entire range of marks into very few possible cases by dividing (integer division) the given marks by 10. For example, 80/10 is 8, 47/10 is 4, 51/10 is 5 and so on. Thus we get exactly 11 possible cases {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } when marks are divided by 10. All these 11 cases can be classified into just 5 groups. Cases 10, 9 and 8 form one group, case 7 and 6 form two independent groups, case 5 and case 4 form one group. All the remaining cases, i.e. case 3, case 2, case 1 and case 0 form the last group. Now the grading can be achieved by the technique shown in the following flowchart.

C-Tips

More than one case can be made to execute the same set of statements. For example, the program segment given below is valid.

- - -
- - -
case 10 :
case  9 :
case  8 : printf(“
 Grade A 
”);
          break;
- - -
- - -

The above segment will be executed for the case values of 10 and 9 as well as 8.

Flowchart

images

The Program

/* Awarding grades based on marks scored in an examination */

#include<stdio.h>
#include<conio.h>
void main ( )
    {
      int marks;
      clrscr( );
      printf(“Enter the marks
”);
      scanf(“%d”, &marks);
      if (marks > 100) exit (1) ;
      /* The 0 - 100 range of marks is mapped into 10 different cases
           using the marks/10 expression*/

      switch(marks/10)
       {
            case 10 :
             case 9 :
             case 8 : printf ( “Grade is A
” ) ;
                      break;
             case 7 : printf(“Grade is B
”) ;
                      break;
             case 6 : printf ( “Grade is C
” ) ;
                      break;
             case 5 :
             case 4 : printf ( “Grade is D
” ) ;
                      break;
            default : printf(“Grade is E
”);
                      break;
    }
}

5.3 A SIMPLE CALCULATOR

A simple calculator is the one which is used to carry basic operations like addition (+), subtraction (-), multiplication (*) and division (/). In other words, expressions like 4 + 5, 14 - 10, 12 * 5 and 3/5 are evaluated using such a simple calculator. As the operator appears between the two operands in all the expressions given above, these expressions are said to be in infix form.

The problem here is to read-in an arithmetic expression given in the infix form, evaluate it and output the result. If any attempt is made to divide by 0 (zero) or evaluate an expression with an unidentified operator, errors must be reported.

The Method

As already mentioned, a simple arithmetic expression is first read-in. After reading in the expression to be evaluated, the operator has to be recognized first and then branch out to the ‘evaluating section’ accordingly. For example, if the operator recognized is ‘+’ then we have to branch out to the add section, if the operator recognized is ‘-’ then we have to branch out to the subtract section, and so on. As there are four operators to be taken care-of, there will be a five-way (four for permitted operators and one for unidentified operators) branching. As multi-way branching takes place one has to use some multi-way branching control structure like switch statement available in C.

Flowchart

images

The Program

/* Program to simulate a simple calculator */

/* The input will be in infix form i.e. operand1 operator operand2 */

#include<stdio.h>
#include<conio.h>
main()
{
   float value1, value2 ;
   char operator;
   clrscr();

printf(“Type in your expression.
”);
scanf(“%f %c %f”,&value1,&operator,&value2);

switch(operator)
{
   case ‘+’ : printf(“The sum of %.2f and %.2f is : %.2f
”,valuel,value2, value1+value2);
      break;
   case ‘-’ : printf(“The difference of %.2f and %.2f is : %.2f
”, value1,value2,value1-value2);
        break;
   case ‘*’ : printf(“The product of %.2f and %.2f is : %.2f
”,value1, value2,value1*value2);
      break;
   case ‘/’ : if(value2 = = 0)
     printf(“Division by zero.
”);
       else
              printf(“The result of %.2f/%.2f is : %.2f
”,
                value1, value2,value1/value2);
      break;

   default: printf ( “Unknown operator. 
” ) ;
      break;

   }
}

Note: Observe that evaluation of the required expressions has been done inside the printf() statement itself. This is permitted.

5.4 SELECTING AN OPERATION BASED ON A MENU

Assume that we are interested in some file operations. Let the different file operations be file reading, file writing, file saving and file deletion. In such circumstances a menu displaying the different actions that have to be performed can be used and any one action is selected.

Menu

  • W) Write a file
  • R) Read a file
  • S) Save a file
  • D) Delete a file

Enter your Choice:

The Method

Output statements are used to display the contents of the required menu. Then an input statement is used to accept the choice and act. As there are five actions (including the wrong choice) we have to take a multi-way decision. Obviously for this type of decision making a control construct like switch is used. The flowchart below shows the technique involved

C-Tips

Since the selection is based on characters, the format specifier %c is used. It may be noted that characters are stored inside the machine in the form of integers. Hence characters can be used as case values.

Flowchart

images

The Program

/* Program for selecting an operation based on a MENU */

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

main()
{
   char choice;
   clrscr();

   printf(“				 MENU

”);
   printf(“			 W : Writing a file 
”);
   printf(“			 R : Reading a file 
”);
   printf(“			 S : Saving a file 
”);
   printf(“			 D : Deleting a file 
”);

   printf(“			 Enter your choice : ”);
   scanf(“%c”,&choice);

   printf(“
”);

   switch(choice)
   {
     case ‘W’ : printf (“The file operation selected is : Writing a 
                         file
”);
               break;
     case ‘R’ : printf (“The file operation selected is : Reading a 
                        file
”);
               break;
     case ‘S’ : printf (“The file operation selected is : Saving a
                        file
”);
               break;
     case ‘D’ : printf (“The file operation selected is : Deleting a 
                       file
”);
               break;
    
     default: printf(“Invalid Input 
”);
               break;
   }
}

EXERCISES

  1. Develop a flowchart to identify and display the day of a week given an integer between 0 and 6. The first day of the week i.e. 0, may be assumed to be Sunday. Write a C program for the same.
  2. Given an array of elements you are expected to determine any one of the following
    • Biggest
    • Smallest
    • Sum
    • Average of all the elements

    Develop a flow chart to solve this problem using multiway decision facility. Write a C program for the same.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.215.96