5 Decision Statements – Programming in C, 3/e, 3rd Edition

CHAPTER 5

Decision Statements

Chapter Outline
5.1  INTRODUCTION

A program is nothing but the execution of one or more instructions sequentially in the order in which they come into sight. This process is analogous to reading the text and figures that appear on the page of a notebook. In the monolithic program, the instructions are executed sequentially in the order in which they appear in the program. Quite often, it is desirable in a program to alter the sequence of the statements depending upon certain circumstances. In real time applications, there are a number of situations where one has to change the order of the execution of statements based on the conditions.

Decision-making statements in a programming language help the programmer to transfer the control from one part to other parts of the program. Thus, these decision-making statements facilitate the programmer in determining the flow of control. This involves a decision-making condition to see whether a particular condition is satisfied or not. On the basis of real time applications it is essential:

  1. to alter the flow of a program.
  2. to test the logical conditions.
  3. to control the flow of execution as per the selection.

These conditions can be placed in the program using decision-making statements. C language supports the control statements as listed below:

  1. The if statement
  2. The if–else statement
  3. The if–else–if ladder statement
  4. The switch case statement
  5. The goto unconditional jump
  6. The loop statement

Besides, the C also supports other control statements such as continue, break.

The decision-making statement checks the given condition and then executes its sub-block. The decision­ statement decides which statement to execute after the success or failure of a given condition.

The conditional statements use relational operators, which have been explained in Chapter 3. The relational operators are useful for comparing the two values. They can be used to check whether they are equal to each other, unequal or one is smaller/greater than the other.

The reader or the programmer is supposed to understand the concepts as cited above. Following points are expected to be known to the programmer related to the decision-making statements.

Sequential execution: The statements in the program are executed one after another in a sequential manner. This is called the sequential execution.

Transfer of control: The C statements such as if, goto, break, continue, switch allow a program to transfer the control at different places in the program. This is accomplished by skipping one or more statements appearing in a sequential flow. This jumping of control is called the transfer of control.

During 1960s, programmers faced various difficulties in the program in which goto statement was used which allows a programmer to transfer the control anywhere in the program. Bohm and Jacopini reported that the programmer should not use the goto statement in their programs. Both Bohm and Jacopini demonstrated that all the programs could be written by using only three control­ structures, i.e. sequence structure, selection structure and repetition structure by eliminating the goto statement.

5.2  The if Statement

C uses the keyword if to execute a set of command lines or one command line when the logical condition is true. It has only one option. The sets of command lines are executed only when the logical condition is true (see Figure 5.1).

 

Syntax for the simplest if statement :-

if (condition) /* no semi-colon

*/ statement;

Figure 5.1  The if statement

The if statement contains an expression which is evaluated. If the expression is true it returns 1, otherwise 0. The statement is executed when the condition is true. In case the condition is false, the compiler skips the lines within the if block. The condition is always enclosed within a pair of ­parentheses. The conditional statements should not be terminated with semi-colons (;). The statements following the if statement are normally enclosed within curly braces. The curly braces indicate the scope of the if statement. The default scope is one statement. But it is good practice to use curly braces even if a single statement is used following the if condition.

Given below are simple programs that demonstrate the use of the if statement.

5.1  Write a program to check whether the entered number is less than 10. If yes, display the same.

 

void main()

{

int v;

clrscr();

printf(“Enter the number :”);

scanf(“%d”, &v);

if(v<10)

printf(“\nNumber entered is less than 10”);

sleep(2); /* process halts for given value in seconds */

}

OUTPUT:

Enter the number : 9

Number entered is less than 10

Explanation:

In the above program, the user can enter the number. The entered number is checked with the if statement. If it is less than 10, a message ‘Number entered is less than 10’ is displayed. For the sake of understanding, Figure 5.2 is given for the above program.

Figure 5.2  The if statement (flow of control)

5.2  Write a program to check whether the candidate’s age is greater than 17 or not. If yes, display message ‘Eligible for Voting’.

 

void main()

{

int age;

clrscr();

printf(“\n Enter age in the years :”);

scanf(“%d”,&age);

if(age>17)

printf(“\n Eligible for Voting.”);

getch();

}

OUTPUT:

Enter age in the years : 20

Eligible for Voting.

Explanation:

In the above program, age is entered through the keyboard. If the age is greater than 17 years, a message will be displayed as shown at the output.

5.3   Write a program using curly braces in the if block. Enter only the three numbers and calculate their sum and multiplication. 

 

void main()

{

int a,b,c,x;

clrscr();

printf(“\nEnter Three Numbers:”);

x=scanf(“%d %d %d”,&a,&b,&c);

if(x==3)

{

  printf(“\n Addition : %d”,a+b+c);

  printf(“\n Multiplication : %d”, a*b*c);

}

}

OUTPUT:

Enter Three Numbers: 1 2 4

Addition : 7

Multiplication : 8

After second time execution

Enter Three Numbers: 5 v 8

Explanation:

The variable ‘x’ contains the number of values correctly inputted by the user. If the value of ‘x’ is 3, the addition and multiplication operations are performed as per the first example in the output. In the second example, the numbers are not correctly entered. Hence, the if condition is false and no operation is performed. Here, the statements following the if condition is enclosed within curly braces.

5.3  The if–else Statement

We observed the execution of the if statement in the previous programs. We observed that the if block statements execute only when the condition in if is true. When the condition is false, program control executes the next statement which appears after the if statement.

The if–else statement takes care of the true and false conditions. It has two blocks. One block is for if and it is executed when the condition is true. The other block is of else and it is executed when the condition is false. The else statement cannot be used without if. No multiple else statements are allowed with one if (see Figures 5.3 and 5.4).

The flow chart for the if–else statement is given in Figure 5.4.

Figure 5.3  The if–else statements

Figure 5.4  The if–else statement

 

The syntax of if–else statement is as follows:

if(the condition is true)

execute the Statement1;

else

execute the Statement2;

OR

 

Syntax of if–else statement can be given as follows:

if ( expression is true)

{

statement1;     /* if block */

statement2;

}

else

{

statement3;     /* else block */

statement4;

}

The if–else statement is demonstrated in the following programs.

5.4  Write a program to find the roots of a quadratic equation by using if-else condition.

 

# include <math.h>

void main()

{

int b,a,c;

float x1,x2;

clrscr();

printf(“\n Enter Values for a,b,c :”);

scanf(“%d %d %d”, &a,&b,&c);

if(b*b>4*a*c)

{

  x1=−b+sqrt(b*b−4*a*c)/2*a;

  x2=−b−sqrt(b*b−4*a*c)/2*a;

  printf(“\n x1=%f x2=%f”,x1,x2);

}

else

  printf(“\n Roots are Imaginary”);

  getch();

}

OUTPUT:

Enter Values for a,b,c : 5 1 5

Roots are Imaginary

Explanation:

The user can enter the values of a, b and c in the above program. The terms b2 and 4*a*c are evaluated. The if condition checks whether b2 is greater than 4*a*c. If true, x1 and x2 are evaluated and printed; otherwise message displayed will be ‘Roots are Imaginary’.

5.5  Write a program to calculate the square of those numbers only whose least significant digit is 5.

 

void main()

{

int s,d;

clrscr();

printf(“\n Enter a Number :”);

scanf(“%d”,&s);

d=s%10;

if(d==5)

{

  s=s/10;

  printf(“\n Square = %d%d”,s*s++,d*d);

}

else

  printf(“\n Invalid Number”);

}

OUTPUT:

Enter a Number : 25

Square = 625

Explanation:

In the above program, a number whose square is to be computed is entered. With the modular division, operation the last digit is separated to confirm whether it is 5 or not. If yes, the body of the if loop is executed where 10 divides the entered number and a quotient is obtained. The quotient and its consecutive number are multiplied and displayed. Followed by this, a square of 5 is calculated and displayed. Care is taken in the printf() statement to display the two results: (i) multiplication of quotient and its consecutive number and (ii) square of 5 without space. Thus, the square of a number is displayed.

5.6  Write a program to calculate the salary of a medical representative based on the sales. Bonus and incentive to be offered to him will be based on total sales. If the sale exceeds or equals to Rs.1,00,000, follow the particulars of Table 1, otherwise follow Table 2.

 

1. TABLE

Basic=Rs. 3000.

Hra=20% of basic.

Da=110% of basic.

Conveyance=Rs.500.

Incentive=10% of sales.

Bonus=Rs. 500.

 

2. TABLE

Basic=Rs. 3000.

Hra=20% of basic.

Da=110% of basic.

Conveyance=Rs.500.

Incentive=5% of sales.

Bonus=Rs. 200.

 

void main()

{

float bs,hra,da,cv,incentive,bonus,sale,ts;

clrscr();

printf(“\n Enter Total Sales in Rs.:”);

scanf(“%f”, &sale);

if(sale>=100000)

{

    bs=3000;

    hra=20 * bs/100;

    da=110 * bs/100;

    cv=500;

    incentive=sale*10/100;

    bonus=500;

}

    else

    {

       bs=3000;

       hra=20 * bs/100;

       da=110 * bs/100;

       cv=500;

       incentive=sale*5/100;

       bonus=200;

    }

ts=bs+hra+da+cv+incentive+bonus;

printf(“\nTotal Sales : %.2f”,sale);

printf(“\nBasic Salary : %.2f”’,bs)

printf(“\nHra : %.2f”,hra);

printf(“\nDa : %.2f”,da);

printf(“\nConveyance : %.2f”,cv);

printf(“\nIncentive : %.2f”,incentive);

printf(“\nBonus : %.2f”,bonus);

printf(“\nGross Salary : %.2f”,ts);

getch();

}

OUTPUT:

Enter Total Sales in Rs. 100000

Total Sales: 100000.00

Basic Salary: 3000.00

Hra: 600.00

Da: 3300.00

Conveyance: 500.00

Incentive: 10000.00

Bonus: 500.00

Gross Salary: 17900.00

Explanation:

This program calculates the salary of a medical representative depending on sales. The basic salary is the same but other allowances and incentives change, depending on the sales. If the sale is more than Rs. 1,00,000, the rate of allowances and incentive is as per Table 1 otherwise it is as per Table 2. The if condition checks the given figure of sales. If sale is more than Rs. 1,00,000, the first bock following the if statement is executed otherwise the else block is executed. In both the blocks, simple arithmetic operations are performed to calculate the allowances and total salary.

5.4  Nested if–else Statements

In this kind of statement, a number of logical conditions are checked for executing various statements. Here, if any logical condition is true the compiler executes the block followed by if condition, other­ wise it skips and executes the else block. In the if–else statement, the else block is executed by default after failure of condition. In order to execute the else block depending upon certain condition we can add, repetitively, if statements in else block. This kind of nesting will be unlimited. Figure 5.5 describes the nested if–else–if blocks.

Figure 5.5  Nested if–else statements

Syntax of nested if-else statement can be given as follows.

 

if(condition)

{

/*Inside first if block*/

if(condition)

{

   statement 1; /*if block*/

   statement 2;

}

else

{

   statement 3; /*else block*/

   statement 4;

}

}

else

{

   /*Inside else block*/

   if(condition)

   {

      statement 5; /*if block*/

      statement 6;

   }

else

   {

      statement 7; /*else block*/

      statement 8;

   }

}

From the above block, following rules can be described for applying nested if-else-if statements.

  1. Nested if-else can be chained with one another.
  2. If the condition is true control passes to the block following first if. In that case, we may have one more if statement whose condition is again checked. This process continues till there is no if statement in the last if block.
  3. If the condition is false control passes to else block. In that case, we may have one more if statement whose condition is again checked. This process continues till there is no if statement in the last else block.
5.5  The if-else-if Ladder Statement

In this kind of statement, a number of logical conditions are checked for executing various statements. Here, if the first logical condition is true the compiler executes the block followed by first if condition, otherwise it skips that block and checks for next logical condition followed by else-if, if the condition is true the block of statements followed by that if condition is executed. The process is continued until a true condition is occurred or an else block is occurred. If all if conditions become false, it executes the else block. In the if-else-if ladder statement, the else block may or may not have the else block.

In if-else-if ladder statement we do not have to pair if statements with the else statements that is we do not have to remember the number of braces opened like nested if-else. So it is simpler to code than nested if-else and having same effect as nested if-else.

The statement is named as if-else-if ladder because it forms a ladder like structure as shown in Figure 5.6.

Figure 5.6  if–else–if ladder statement

Syntax of if-else-if statement can be given as follows.

 

if(condition)

{

statement 1; /*if block*/

statement 2;

}

else if(condition)

{

statement 3; /*second if block*/

statement 4;

}

else if(condition)

{

statement 5; /*third if block*/

statement 6;

}

else

{

statement 7; /*else block*/

statement 8;

}

From the above block, following rules can be described for applying nested if-else-if statements:

  1. Nested if-else can be chained with one another.
  2. If the first if condition is false control passes to else-if block where condition is again checked with the next if statement. This process continues till there is no if statement in the last else block.
  3. If one of the if statements satisfies the condition, other nested else-if statement will not be executed.

Given below programs are described on the bases on nested if-else and if-else-if ladder statements.

5.7  Write a program to calculate electricity bill. Read the starting and ending meter reading. The charges are as follows.

 

No. of units consumed

Rates in (Rs.)

200–500

3.50

100–200

2.50

Less than 100

1.50

 

void main()

{

int initial,final,consumed;

float total;

clrscr();

printf(“\n Initial & Final Readings :”);

scanf(“%d %d”, &initial, &final);

consumed = final−initial;

if(consumed>=200 && consumed<=500)

total=consumed * 3.50;

else if(consumed>=100 && consumed<=199)

total= consumed * 2.50;

else if(consumed<100)

total=consumed*1.50;

printf(“Total bill for %d unit is %f”,consumed,total);

getche();

}

OUTPUT:

Initial & Final Readings : 800 850

Total bill for 50 unit is 75.000000

Explanation:

Initial and final readings are entered through the keyboard. Their difference is nothing but the total energy consumed. As per the table given in the example, rates are applied and total bill based on consumption of energy is calculated.

5.8  Write a program to find the maximum number out of six numbers invoked though the ­keyboard.

 

void main()

{

int a,b,c,d,e,f;

clrscr();

printf(“Enter 1st number:”);

scanf(“\n%d”,&a);

printf(“Enter 2nd number:”);

scanf(“\n%d”,&b);

printf(“Enter 3 rd number:”);

scanf(“\n%d”,&c);

printf(“Enter 4th number:”);

scanf(“\n%d”,&d);

printf(“Enter 5th number:”);

scanf(“\n%d”,&e);

printf(“Enter 6th number:”);

scanf(“\n%d”,&f);

if((a>b)&&(a>c)&&(a>d)&&(a>e)&&(a>f))

printf(“Maximum out of six Numbers is : %d”,a);

else if((b>c)&&(b>d)&&(b>e)&&(b>f))

printf(“Maximum out of six Numbers is : %d”,b);

else if((c>d)&&(c>e)&&(c>f))

printf(“Maximum out of six Numbers is :%d”,c);

else if((d>e)&&(d>f))

printf(“Maximum out of six Numbers is : %d”,d);

else if(e>f)

printf(“Maximum out of six Numbers is : %d”,e);

else

printf(“Maximum out of six Numbers is : %d”,f);

getch();

}

OUTPUT:

Enter 1st number:23

Enter 2nd number:45

Enter 3rd number:67

Enter 4th number:89

Enter 5th number:80

Enter 6th number:90

Maximum out of six Numbers is : 90

Explanation:

Six numbers are entered through the keyboard. All the values of variables are compared with one another using && (and) in nested if–else–if statements. When one of the if statements satisfies the condition that if block is executed which prints the largest number otherwise the control passes to another if–else–if statement.

5.9  Write a program to find the largest number out of three numbers. Read the numbers through the keyboard.

 

void main()

{

int x,y,z;

clrscr();

printf(“\nEnter Three Numbers x, y, z :”);

scanf(“%d %d %d”, &x,&y,&z);

printf(“\nLargest out of Three Numbers is :”);

if(x>y)

{

   if(x>z)

   printf(“x=%d\n”,x);

   else

   printf(“z=%d\n”,z);

}

   else

   {

     if(z>y)

     printf(“z=%d\n”,z);

     else

     printf(“y=%d\n”,y);

   }

}

OUTPUT:

Enter Three Numbers x, y, z : 10 20 30

Largest out of Three Numbers is :z=30

Explanation:

This is also an example of the nested ifs. When the if statement satisfies the condition, control passes to another if statement block. Three numbers are entered through keyboard. The first if statement compares the first number with the second number. If the condition is a true, the block followed by first if statement executes. Inside the block, the if statement checks whether the first number is larger than the third number. If yes, then the largest number is the first one and the same is displayed. Else the third number is the largest and the same is printed. In case the first if statement fails to satisfy the condition, the else block with nested if would be executed. The third number is compared with the second number. If it is true the third number is the largest otherwise the second number is the largest.

5.10  Write a program to find the smallest out of the three numbers.

 

void main()

{

int a,b,c,smallest;

clrscr();

printf(“\n Enter Three Numbers :”);

scanf(“%d %d %d”, &a,&b,&c);

if(a<b)

{

   if(a<c)

   smallest=a;

   else

   smallest=c;

}

   else

   {

      if(b<c)

      smallest =b;

      else

      smallest =c;

   }

printf(“The smallest of %d %d %d is %d \n”, a,b,c, smallest);

getche();

}

OUTPUT:

Enter Three Numbers : 1 5 8

The smallest of 1 5 8 is 1

Explanation:

The logic in the above program is the same as the last one. Instead of > (greater than) < (less than) condition is used.

5.11  Write a program to calculate the gross salary for the conditions given below.

 

void main()

{

float bs,hra,da,cv,ts;

clrscr();

printf(“\n Enter Basic Salary :”);

scanf(“%f”,&bs);

if(bs=>5000)

{

   hra=20 * bs/100;

   da= 110 * bs/100;

   cv=500;

}

   else

   if(bs=>3000 && bs<5000)

   {

      hra=15*bs/100;

      da=100*bs/100;

      cv=400;

   }

      else

      {

         if(bs<3000)

         hra=10*bs/100;

         da= 90*bs/100;

         cv=300;

      }

ts=bs+hra+da+cv;

printf(“\nBasic Salary : %5.2f”,bs);

printf(“\nHra : %5.2f”,hra);

printf(“\nDa : %5.2f”,da);

printf(“\nConveyance : %5.2f”,cv);

printf(“\nGross Salary : %5.2f”,ts);

printf(“\nConveyance : %5.2f”,cv);

getch();

}

OUTPUT:

Enter Basic Salary: 5400

Basic Salary: 5400

Hra: 1080

Da: 5940

Conveyance: 500

Gross Salary:12920

Explanation:

In the above program, the basic salary of an employee is entered through the keyboard. This entered figure is checked with different conditions as cited in the problem. The if– else conditions are used and on the basis of the conditions gross salary is calculated and displayed.

5.12   Calculate the total interest based on the following.

 

PRINCIPLE AMOUNT (Rs.)

Rate of Interest (Rs.)

>=10000

20%

>=8000 && <=9999

18%

<8000

16%

 

void main()

{

float princ,nyrs,rate,interest;

clrscr();

printf(“\n Enter Loan & No. of years :-”);

scanf(“%f %f”, &princ, &nyrs);

if(princ>=10000)

rate=20;

else

if(princ>=8000 && princ<=9999)

rate=18;

else

if(princ<8000)

rate=16;

interest = princ * nyrs * rate/100;

printf(“\nYears : %6.2f”,nyrs);

printf(“\nLoan : %6.2f”,princ);

printf(“\nRate : %6.2f”,rate);

printf(“\nInterest : %6.2f”,interest);

getche();

}

OUTPUT:

Enter Loan & No. of years :- 5000 3

Loan : 5000.00

Years : 3.00

Rate : 16.00

Interest : 2640.00

Explanation:

In the above program, the loan and the number of years are entered through the keyboard. The entered principal amount is checked with the if statement. Based on the principal amount, the rate of interest is charged. The interest is calculated by considering different factors such as loan amount, the number of years and the rate of interest as per the table.

5.13  Write a program to find the average of six subjects and display the results as follows.

 

AVERAGE

RESULT

>=35 & <50

Third Division

>=50 & <60

Second Division

>=60 & <75

First Division

>=75 & <=100

Distinction

If marks in any subject less than 35

Fail

 

void main()

{

int a,b,c,d,e,f;

float sum=0;

float avg;

clrscr();

printf(“\nEnter Marks:\n”);

printf(“P C B M E H\n”);

scanf(“%d %d %d %d %d %d”,&a,&b,&c,&d,&e,&f);

if(a<35 || b<35 || c<35 || d<35 || e<35 || f<35)

{

printf(“\nResult: Fail”);

exit();

}

sum=a + b + c + d + e + f;

avg=sum/6;

printf(“Total : %g \nAverage : %g”, sum,avg);

if(avg>=35 && avg<50)

printf(“\n Result: Third Division”);

else

if(avg>=50 && avg <60)

printf(“\n Result: Second Division”);

else

if(avg>=60 && avg<75)

printf(“\n Result: First Division”);

else

if(avg>75 && avg <=100)

printf(“\nResult : Distinction”);

getche();

}

Enter Marks:

P

C

B

M

E

H

56

57

56

89

78

45

Total : 381

Average : 63.5

Result: First Division

Explanation:

In the above program, marks of six subjects are entered through the keyboard. Their sum and average are calculated. The first if statement checks the condition whether the marks in individual subjects are less than 35. If so, message displayed will be ‘Result: Fail’ and the program terminates. The logical OR (||) is used here.

The average marks obtained are checked with different conditions. The if-else blocks are used. Based on the conditions the statements are executed.

5.6  The break Statement

The keyword break allows the programmers to terminate the loop. The break skips from the loop or block in which it is defined. The control then automatically goes to the first statement after the loop or block. The break can be associated with all conditional statements.

We can also use the break statements in the nested loops. If we use the break statement in the innermost loop, then the control of the program is terminated only from the innermost loop.

The difference between the break and exit() is provided in Table 5.1.

Table 5.1  Difference between break and exit()

Sr. No

break

exit()

1.

It is a keyword.

It is a function.

2.

No header file is needed.

Header file process.h must be included.

3.

It stops the execution of the loop.

It terminates the program.

5.7  The continue Statement

The continue statement is exactly opposite of the break statement. The continue statement is used for continuing the next iteration of the loop statements. When it occurs in the loop, it dose not terminate, but it skips the statements after this statement. It is useful when we want to continue the program without executing any part of the program. Table 5.2 gives the differences between break and continue.

Table 5.2  Difference between break and continue

break

continue

Exits from current block or loop.

Loop takes the next iteration.

Control passes to the next statement.

Control passes at the beginning of the loop.

Terminates the loop.

Never terminates the program.

5.8  The goto Statement

This statement does not require any condition. This is an unconditional control jump. This statement passes control anywhere in the program, i.e. control is transferred to another part of the program without testing any condition. User has to define the goto statement as follows:

goto label;

where, the label name must start with any character.

Here, the label is the position where the control is to be transferred. A few examples are described for the sake of understanding.

5.14  Write a program to detect the entered number as to whether it is even or odd. Use the goto statement.

 

# include <stdlib.h>

void main()

{

int x;

clrscr();

printf(“Enter a Number :”);

scanf(“%d”,&x);

if(x%2==0)

goto even;

else

goto odd;

even :

printf(“\n %d is Even Number.”,x);

return;

odd:

printf(“\n %d is Odd Number.”,x);

}

OUTPUT:

Enter a Number : 5

5 is Odd Number.

Explanation:

In the above program, a number is entered. The number is checked for even or odd with modules division operator. When the number is even, the goto statement transfers the control to the label even. Similarly, when the number is odd the goto statement transfers the control to the label odd and respective message will be displayed.

5.15  Write a program to calculate the telephone bill. Transfer controls at different places according to the number of calls and calculate the total charges. Follow rates as per given in the table.

 

Telephone Call

Rate in Rs.

<100 No Charges

 

>99 & <200

1

>199 & <300

2

>299

3

 

void main()

{

int nc;

clrscr();

printf(“\nEnter Number of Calls :”);

scanf(“%d”,&nc);

if(nc<100)

goto free;

else if(nc>99 && nc<200)

goto charge1;

else if(nc>199 && nc<300)

goto charge2;

else

goto charge3;

free :

printf(“\n No charges.”);

return;

charge1:

printf(“\n Total Charges : %d Rs.”,nc*1);

return;

charge2:

printf(“\n Total Charges : %d Rs.”,nc*2);

return;

charge3:

printf(“\n Total Charges : %d Rs.”,nc*3);

}

OUTPUT:

Enter Number of Calls : 500

Total Charges: 1500 Rs

Explanation:

The execution process of the above program is the same as that of the previous one. The difference is that in this program control is transferred to various labels.

5.16  Write a program to check if the entered year is a leap year or not. Use the goto statement.

 

#include <stdio.h>

#include <conio.h>

int main()

{

int year;

clrscr();

printf(“\nEnter Year :”);

scanf(“%d”,&year);

if(year%4==0 && year%100!=0 || year%400==0)

goto leap;

else

goto noleap;

leap:

printf(“%d is a leap year.”,year);

return 0;

noleap:

printf(“%d is not leap year.”,year);

getch();

return 0;

}

OUTPUT:

Enter Year : 2012

2012 is a leap year.

Explanation:

The entered year is divided using the modulus division operator 400. The condition is satisfied hence the year 2012 is the leap year.

5.9  The switch Statement

The switch statement is a multi-way branch statement. In the program, if there is a possibility to make a choice from a number of options, this structured selection is useful. The switch statement requires only one argument of any data type, which is checked with the number of case options. The switch statement evaluates expression and then looks for its value among the case constants. If the value matches with case constant, this particular case statement is executed. If not, default is executed. Here, switch, case and default are reserved keywords. Every case statement terminates with ‘:’. The break statement is used to exit from current case structure. The switch statement is useful for writing the menu-driven program.

The syntax of the switch case statement is as follows.

 

switch(variable or expression)

{

case constant A :

statement;

break;

case constant B :

statement;

break;

default :

statement ;

}

  1. The switch expression

    In the block, the variable or expression can be a character or an integer. The integer expression following the keyword switch will yield an integer value only. The integer may be any value 1, 2, 3, and so on. In case a character constant, the values may be given in the alphabetic order such as ‘x’, ‘y’, ‘z’.

  2. The switch organization

    The switch expression should not be terminated with a semi-colon and/or with any other symbol. The entire case structure following switch should be enclosed with curly braces. The keyword case is followed by a constant. Every constant terminates with a colon. Each case statement must contain different constant values. Any number of case statements can be provided. If the case structure contains multiple statements, they need not be enclosed with curly braces. Here, the keywords case and break perform the job of opening and closing curly braces, respectively.

  3. The switch execution

    When one of the cases satisfies, the statements following it are executed. In case, there is no match, the default case is executed. The default can be put anywhere in the switch expression. The switch statement can also be written without the default statement. The break statement used in switch causes the control to go outside the switch block. By mistake, if no break statements are given all the cases following it are executed (see Figure 5.7).

5.17  Write a program to print lines by selecting the choice.

 

void main()

{

int ch;

clrscr();

printf(“\n[1] .........”);

printf(“\n[2] _________”);

printf(“\n[3] *********”);

printf(“\n[4] ==========”);

printf(“\n[5] EXIT”);

printf(“\n\n ENTER YOUR CHOICE :”);

scanf(“%d”, &ch);

switch(ch)

{

   case 1 :

   printf(“\n ............................................”);

   break;

   case 2 :

   printf(“\n ___________________________________________”);

   break;

   case 3 :

   printf(“\n ********************************************”);

   break;

   case 4 :

   printf(“\n ============================================”);

   break;

   case 5 :

   printf(“\n Terminated by choice”);

   exit();

   break;

   default :

   printf(“\n Invalid Choice”);

}

getch();

}

OUTPUT:

[1] .........

[2] _________

[3] *********

[4] ==========

[5] EXIT

ENTER YOUR CHOICE : 1

...........................

Figure 5.7  switch statement

Explanation:

In this program, a menu appears with five options and it requests the users to enter their choice. The choice entered by the user is then passed to switch statement. In the switch statement, the value is checked with all the case constants. The matched case statement is executed in which the line is printed of the user’s choice. If the user enters a non-listed value, then no match occurs and default is executed. The default warns the user with a mes-sage ‘Invalid Choice’.

5.18  Write a program to calculate (1) Addition, (2) Subtraction, (3) Multiplication, (4) Division, (5) Remainder calculation, (6) Larger out of two numbers by using switch statements.

 

void main()

{

int a,b,c,ch;

clrscr();

printf(“\t =================”);

printf(“\n\t MENU”);

printf(“\n\t =================”);

printf(“\n\t[1] ADDITION”);

printf(“\n\t[2] SUBTRACTION”);

printf(“\n\t[3] MULTIPLICATION”);

printf(“\n\t[4] DIVISION”);

printf(“\n\t[5] REMAINDER”);

printf(“\n\t[6] LARGER OUT OF TWO”);

printf(“\n\t[0] EXIT”);

printf(“\n\t=================”);

printf(“\n\n\t ENTER YOUR CHOICE :”);

scanf(“%d”, &ch);

if(ch<=6 & ch>0)

{

   printf(“Enter Two Numbers :”);

   scanf(“%d %d”,&a,&b);

}

   switch ( ch)

   {

      case 1 :

      c=a+b;

      printf(“\n Addtion : %d”,c);

      break;

      case 2 :

      c=a−b;

      printf(“\n Subtraction : %d”,c);

      break;

      case 3 :

      c=a*b;

      printf(“\n Multiplication : %d”,c);

      break;

      case 4 :

      c=a/b;

      printf(“\n Division : %d”,c);

      break;

      case 5 :

      c=a%b;

      printf(“\n Remainder : %d”,c);

      break;

      case 6 :

      if(a>b)

      printf(“\n\t %d (a) is larger than %d (b).”,a,b);

      else

      if(b>a)

      printf(“\n\t %d (b) is larger than %d (a).”,b,a);

      else

      printf(“\n\t %d (a) & %d (b) are same.”,a,b);

      break;

      case 0 :

      printf(“\n Terminated by choice”);

      exit();

      break;

      default :

      printf(“\n Invalid Choice”);

   }

getch();

}

OUTPUT:

MENU

=================

[1] ADDITION

[2] SUBTRACTION

[3] MULTIPLICATION

[4] DIVISION

[5] R]EMAINDER

[6] LARGER OUT OF TWO

[0] EXIT

=================

ENTER YOUR CHOICE : 6

Enter Two Numbers : 8 9

9 (b) is larger than 8 (a).

Explanation:

In this program also, a menu appears with different arithmetic operations. It requests the user to enter the required choice number. The choice entered by the user is checked with the if statement. If it is in between 1 and 6 the if block is executed which prompts the user to enter two numbers. After this, the choice entered by the user is passed to the switch statement and it performs relevant operations.

5.19  Write a program that converts number of years into (1) minutes, (2) hours, (3) days, (4) months and (5) seconds using switch statements.

 

void main()

{

long ch,min,hrs,ds,mon,yrs,se;

clrscr();

printf(“\n[1] MINUTES”);

printf(“\n[2] HOURS”);

printf(“\n[3] DAYS”);

printf(“\n[4] MONTHS”);

printf(“\n[5] SECONDS”);

printf(“\n[0] EXIT”);

printf(“\n Enter Your Choice :”);

scanf(“%ld”, &ch);

if(ch>0 && ch<6 )

{

   printf(“Enter Years :”);

   scanf(“%ld”,&yrs);

}

   mon=yrs*12;

   ds=mon*30;

   ds=ds+yrs*5;

   hrs=ds*24;

   min=hrs*60;

   se=min*60;

   switch(ch)

   {

      case 1 :

      printf(“\n Minutes : %ld”,min);

      break;

      case 2 :

      printf(“\n Hours : %ld”,hrs);

      break;

      case 3 :

      printf(“\n Days : %ld”,ds);

      break;

      case 4 :

      printf(“\n Months : %ld”,mon);

      break;

      case 5 :

      printf(“\n Seconds: %ld”,se);

      break;

      case 0 :

      printf(“\n Terminated by choice”);

      exit();

      break;

      default :

      printf(“\n Invalid Choice”);

   }

getch();

}

OUTPUT:

[1] MINUTES

[2] HOURS

[3] DAYS

[4] MONTHS

[5] SECONDS

[0] EXIT

Enter Your Choice : 4

Enter Years : 2

Months : 24

Explanation:

In this program, the number of years is entered and according to the user’s choice switch case structure performs the operation.

5.20  Write a program to perform the following operations:

  1. Display any numbers or stars on the screen by using for loop.
  2. Display the menu containing the following: (a) whole screen, (b) half screen, (c) the top three lines and (d) the bottom three lines.

void main()

{

int i,c;

clrscr();

for (i=0;i<=700;i++)

printf(“%d”,i);

printf(“\n\n\t\tCLRAR SCREE MENU\n”);

printf(“\t\t1] Whole screen\n”);

printf(“\t\t2] Half Screen\n”);

printf(“\t\t3] Top 3 Lines \n”);

printf(“\t\t4] Bottom 3 Lines\n”);

printf(“\t\t5] Exit \n Enter Your Choice :”);

scanf(“%d”,&c);

switch(c)

{

   case 1:

   clrscr();

      break;

      case 2 :

      for (i=0;i<=189;i++)

      {

         gotoxy(i,1);

         printf(“\t”);

      }

         break;

         case 3 :

         for (i=1;i<=99;i++)

         {

            gotoxy(i,1);

            printf(“\t”);

         }

            break;

            case 4 :

            for (i=1;i<120;i++)

            {

               gotoxy(i,21);

               printf(“\t”);

            }

         default :

         break;

   }

getche();

}

Explanation:

In the above program, the for loop is used for displaying numbers on the screen. The screen will be covered with numbers. The screen as a whole or part or top or bottom portion can be cleared by using switch cases. While using switch cases for loops are used. The programmer can execute the program and see its effect by entering the different choices.

5.21  Write a program to display the following files of current directory by using system the DOS command: (1) .exe files, (2) .bat files, (3) .obj files and (4) .bak files.

 

void main()

{

int c;

clrscr();

printf(“\n FILE LISTING MENU”);

printf(“\n 1] .EXE”);

printf(“\n 2] .BAT”);

printf(“\n 3] .obj”);

printf(“\n 4] .bak\n Enter Your Choice -:”);

scanf(“%d”,&c);

switch(c)

{

   case 1 :

   system(“dir .exe”);

   break;

   case 2:

   system(“\dir .c”);

   break;

   case 3:

   system(“\dir .obj”);

   break;

   case 4:

   system(“\dir .bak”);

   break;

   default :

   break;

}

getch();

}

Explanation:

In the above program, a menu is displayed. The user can give different choices. The effect can be observed by selecting one of the choices. The user can view all .exe, .bat, .obj, .bak files. The effect is the same as the DOS ‘dir’ command. The System function is used to call the operating system command.

5.22  Write a program to display days in a calendar format of an entered month of year 2015.

 

void main()

{

int m,h,i=1,a,j,b=1;

clrscr();

printf (“\n Enter Month Number of the Year 2015 : “);

scanf (“%d”,&m);  /* Program for finding days of any month of 2015*/

switch(m)

{

case 1

a=5;

j=31;

break;

case 2 :

a=1;

j=28;

break;

case 3 :

a=1;

j=31;

break;

case 4 :

a=4;

j=30;

break;

case 5 :

a=6;

j=31;

break;

case 6 :

a=2;

j=30;

break;

case 7 :

a=4;

j=31;

break;

case 8 :

a=7;

j=31;

break;

case 9 :

a=3;

j=30;

break;

case 10 :

a=5;

j=31;

break;

case 11 :

a=1;

j=30;

break;

case 12 :

a=3;

j=31;

break;

default :

printf (“\a\a Invalid Month”);

exit();

}

/* starting day is to be shown/adjusted as per calendar */

printf (“\n\n\n”);

printf (“\t\t\tMonth − %d − 2015\n\n”,m);

printf (“ SUN MON TUE WED THU FRI SAT\n\n”);

switch (a)

{

case 1 :

printf (“\t%d”,i);

break;

case 2 :

printf (“\t\t%d”,i);

break;

case 3 :

printf (“\t\t\t%d”,i);

break;

case 4 :

printf (“\t\t\t\t%d”,i);

break;

case 5 :

printf (“\t\t\t\t\t%d”,i);

break;

case 6 :

printf (“\t\t\t\t\t\t%d”,i);

break;

case 7 :

printf (“\t\t\t\t\t\t\t%d”,i);

break;

}

h=8−a; /* The starting day is subtracted from 8 */

for (i=2;i<=h;i++) /* To display the first row */

printf (“\t%d”,i);

printf (“\n”);

for (i=h+1; i<=j;i++) /* To continue with second row onwards */

{

   if (b==8) /* To terminate the line after every week */

   {

   printf (“\n”);

   b=1;

   }

printf (“\t%d”,i);

b++;

}

getch();

}

OUTPUT:

Enter Month Number of the Year 2015: 2

      Month – 2 – 2015

SUN
MON
TUE
WED
THU
FRI
SAT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

Explanation:

This program prints the days of a given month of a year (2015) in the calendar form. This will be done without the help of system resources. The month number is to be entered by the user. It is passed to the first switch structure. This structure finds the first day of the month in the numeric form and the number of days present in that month. These values are assigned to a and j, respectively. Here, Sunday to Monday refer to 1 to 7 values, respectively. The printf() functions and second switch structure perform printing of dates in a columnwise manner. The variables i, b are initialized to 1.

The second switch structure defines starting column and prints the value of ‘i’ that is always 1. The value of ‘h’ (8 minus ‘a’) determines the number of dates to be printed in the first row. This task is performed by the first for loop. In the second for loop, h is incremented with 1 and loop continues up to the number of day, i.e. j. To break up dates rowwise, the if statement compares the value of variable ‘b’ with 8. If b=8 then line breaks and ‘b’ again initializes to 1. Whenever b=8, line is broken and whole dates of month are arranged in a calendar form.

5.23  Write a program to convert decimal to hexadecimal number.

 

# include <process.>

void main()

{

int x,y=30,z;

clrscr();

printf(“\nEnter a number :”);

scanf(“%d”,&x);

printf(“\n Conversion of Decimal to Hexadecimal Number \n”);

for( ;; )

{

   if(x==0)

   exit(1);

   z=x%16;

   x=x/16;

   gotoxy(y−−,5);

   switch(z)

   {

      case 10 :

      printf(“A”);

      break;

      case 11 :

      printf(“%c”,‘B’);

      break;

      case 12 :

      printf(“%c”,“C”);

      break;

      case 13 :

      printf(“D”);

      break;

      case 14 :

      printf(“E”);

      break;

      case 15 :

      printf(“F”);

      break;

      default :

      printf(“%d”,z);

   }

}

}

OUTPUT:

Enter a number : 31

Conversion of Decimal to Hexadecimal Number

1F

Explanation:

In the above program, an infinite for loop is used. In the for loop, the switch case statement is used for printing letters A to F. In case entered numbers are in between 1 to 9, the same will be displayed. But if the remainders obtained are greater than 9, in for loop, the appropriate case statement is executed for displaying hexadecimal symbols A to F.

5.10  Nested switch case

The C supports nested switch statements. The inner switch can be a part of an outer switch. The inner and outer switch case constants may be the same. No conflicts arise even if they are the same. A few examples are given below on the basis of nested switch statements.

5.24  Write a program to detect if the entered number is even or odd. Use nested switch case statements.

 

void main()

{

int x,y;

clrscr();

printf(“\n Enter a Number :”);

scanf(“%d”,&x);

switch(x);

{

   case 0 :

   printf(“\n Number is Even.”);

   break;

   case 1 :

   printf(“\n Number is Odd .”);

   break;

   default :

   y=x%2;

   switch(y)

   {

      case 0:

      printf(“\n Number is Even.”);

      break;

      default :

      printf(“\n Number is Odd.”);

   }

}

getche();

}

OUTPUT:

Enter a Number : 5

Number is Odd.

Explanation:

In the above-given program, the first switch statement is used for displaying the message such as even or odd numbers when the entered numbers are 0 and 1, respectively.

When the entered number is other than 0 and 1, its remainder is calculated with modulous operator and stored in the variable ‘y’. The variable ‘y’ is used in the inner switch statement. If the remainder is ‘0’ the message displayed will be ‘Number is Even’, otherwise for non-zero it will be ‘Number is Odd’. Here, the constants used for inner and outer switch statements are the same.

5.25  Write a program to count the number of 1s, 0s, blank spaces and others using nested switch statement.

 

void main()

{

static int x,s,a,z,o;

char txt[20];

clrscr();

printf(“\n Enter a Number :”);

gets(txt);

while(txt[x]!=’\0’)

{

   switch(txt[x])

   {

      case ‘ ’ :

      s++;

      break;

      default :

      switch(txt[x])

      {

         case ‘1’:

         a++;

         break;

         case ‘0’:

         z++;

         break;

         default :

         o++;

      }

   }

x++;

}

printf(“\n Total Spaces : %d”, s);

printf(“\n Total 1s : %d”,a);

printf(“\n Total 0s : %d”,z);

printf(“\n Others : %d”,o);

printf(“\n String Length: %d”,s+a+z+o);

}

OUTPUT:

Enter Numbers : 1110022 222

Total Spaces : 1

Total 1s : 3

Total 0s : 2

Others : 5

String Length:11

Explanation:

In the above-mentioned program, the outer switch counts only spaces in a given text. For other than spaces, the inner switch statement is used. The inner switch is for counting 1s, 0s and others. The string length is printed at the end of the program, which is the addition of all the counts.

5.11  THE switch case AND nested ifs

The distinction between the switch case and the nested ifs is narrated in Table 5.3.

Table 5.3  Distinction between the switch case and nested ifs

switch case

nested ifs

The switch can only test for equality, i.e. only constant values are applicable. The if can evaluate relational or logical expressions.
No two case statements have identical constants in the same switch. Same conditions may be repeated for the number of times.
Character constants are automatically converted to integers. Character constants are automatically converted to integers.
In switch case statement nested if can be used. In nested if statement switch case can be used.

5.26  Write a program to convert integer to character using if condition.

 

void main()

{

int x;

clrscr();

printf(“\n Enter a Number :);

scanf(“%d”,&x);

if(x==‘A’)

printf(“%c”,x);

}

 

OUTPUT:

Enter a Number : 65

A

Explanation:

In this program, the variable ‘x’ is declared as an integer variable. Its value is entered through the keyboard. The ASCII value of entered number is checked with the if statement. If there is a match, the ASCII, value is displayed.

5.27   Write a program to use nested if–else statements in the switch statement. Also show the effect of conversion of integer to character.

 

void main()

{

int i;

clrscr();

printf(“\n Enter Any ASCII Number :”);

scanf(“%d”,&i);

clrscr();

switch(i)

{

   case ‘A’:

   printf(“Capital A\n”);

   break;

   case ‘B’:

   printf(“Capital B\n”);

   break;

   case ‘C’:

   printf(“Capital C\n”);

   break;

   default:

   if(i>47 && i<58)

   printf(“\n Digit :[ %c ]”,i);

   else if(i>=58 && i<=64)

   printf(“\nSymbol :[ %c ]”,i);

   else if(i>64 && i<91)

   printf(“\nCapital :[ %c ]”,i);

   else if(i>96 && i<123)

   printf(“\n Small :[ %c ]”,i);

   else

   printf(“\n Invalid Choice”,i);

   getche();

}

}

OUTPUT:

Enter Any ASCII Number : 65

Capital A

Explanation:

An ASCII number is entered. In the outer switch if its ASCII value is equivalent to ‘A’, ‘B’ and ‘C’ then relevant message is displayed. If the ASCII values are other than these three values, then the inner switch statement is used to determine its equivalent ASCII symbols. The symbols may be any character including special symbols and digits. If we enter 65, Capital A is displayed.

SUMMARY

The reader is made aware about the decision-making statements such as if and the if–else statements in the C programming. Also, the multi-way-decision statement switch case is also discussed. How nested if–else and switch case statements are to be used in programs are also illustrated in a simple and easy way. Ample simple examples have been explained on the decision-making statements. To change the flow of the program, the programmer can use statements such as break, continue and goto. The reader is expected to execute all programs given in this chapter so as to achieve the expertise in handling decision-making statements in the programs. By writing programs for solving more real-life problems, a programmer benefits a lot.

EXERCISES

I  Fill in the blanks:

  1. The switch can only test for ________.
    1. equality
    2. non-equality
    3. None of them
  2. Only ______ values are applicable in the switch structure.
    1. constants
    2. variables
    3. objects
  3. No two case statements have ______ in the same switch.
    1. identical constants
    2. different constants
    3. variables
  4. In switch, character constants are automatically converted to ________
    1. floats
    2. integers
    3. bool values
  5. Same conditions may be repeated for number of times in _______structure.
    1. nested ifs
    2. switch case
    3. None of the them

II  True or false:

  1. The else is associated with if.
  2. The else block is executed when condition is false.
  3. The if statement can have multiple else statements
  4. The statement if (1) executes if block.
  5. One switch statement can have multiple case statements but only one default statement.
  6. The default statement can be written anywhere in the switch block.
  7. The break statement is used to separate two case statements.
  8. The case statement is always terminated by a semi-colon.
  9. The switch statement accepts only constant as an argument.
  10. Like if-else the switch statement can be nested.
  11. The default statement is compulsory for switch statement
  12. The switch statement testes for equality only.
  13. The if statement can evaluate relational and logical expressions.
  14. The if statement works with expression as well as constants.
  15. The default is a keyword.
  16. The default statement can be placed at the beginning of switch, without any statement in its block
  17. The switch block should be terminated by a semi-colon.

III  Select the appropriate option from the multiple choices given below:

  1. The switch statement is used to
    1. switch between functions in a program
    2. switch from one variable to another variable
    3. choose from multiple possibilities which may arise due to different values of a single variable
    4. use switching variables
  2. The default statement is executed when
    1. all the case statements are false
    2. one of the case is true
    3. one of the case is false
    4. None of the above
  3. Each case statement in switch is separated by
    1. break
    2. continue
    3. exit()
    4. goto
  4. The keyword else can be used with
    1. if statement
    2. switch statement
    3. do...while() statement
    4. None of the above
  5. What will be the output of the following program?

    void main()

    {

    char x=‘H’;

    clrscr();

    switch(x)

    {

        case ‘H’: printf(“%c”,‘H’);

        case ‘E’: printf(“%c”,‘E’);

        case ‘L’: printf(“%c”,‘L’);

        case ‘l’: printf(“%c”,‘L’);

        case ‘O’: printf(“%c”,‘O’);

    }

    }

    1. HELLO
    2. HELlo
    3. H
    4. None of the above
  6. What will be the output of the following program?

    void main()

    {

    char x=‘G’;

    switch(x)

    {

    if( x==‘B’)

    {

      case ‘d’: printf(“%”,‘o’);

      case ‘B’: printf(“%s”,“Bad”);

    }

      else

      case ‘G’:

      printf(“%s”,“Good”);

      default : printf(“%s”,“Boy”);

    }

    }

    1. Good Boy
    2. bad boy
    3. boy
    4. None of the above
  7. What will be the output of the following program?

    void main()

    {

    char x=‘d’;

    clrscr();

    switch(x)

    {

      case ‘b’:

      puts( “0 1 001”);

      break;

      default :

      puts(“1 2 3”);

      break;

      case ‘R’ :

      puts(“I II III”);

    }

    }

    1. 1 2 3
    2. 0 1 001
    3. I II III
    4. None of the above

IV  What is/are the output/s of the following programs?

  1.  

    void main()

    {

    int number=7;

    clrscr();

    if(number %2==0)

    printf(“\n The entered number %d is even”,number);

    else

    printf(“\n The Entered number %d is odd”,number);

    getche();

    }

  2.  

    void main()

    {

    int b=4,a=1,c=2;

    float x1,x2;

    clrscr();

    if(b*b>4*a*c)

    {

      x1=−b+sqrt(b*b−4*a*c)/2*a;

      x2=−b−sqrt(b*b−4*a*c)/2*a;

      printf(“\n x1=%.1f

      x2=%.1f”, x1,x2);

    }

      else

      printf(“\n Roots are Imaginary”);

      getch();

    }

  3.  

    void main()

    {

    float bs,hra,da,cv,incentive,

    bonus,sale=110000,ts;

    clrscr();

    if(sale>=100000)

    {

      bs=3000;

      hra=20 * bs/100;

      da=110 * bs/100;

      cv=500;

      incentive=sale*10/100;

      bonus=500;

    }

      else

      {

        bs=3000;hra=20 *

        bs/100;

        da=110 * bs/100;

        cv=500;

        incentive=sale*5/100;

      }

    ts=bs+hra+da+cv+incentive+

    bonus;

    printf(“\n %.2f”,ts);

    getch();

    }

  4.  

    void main()

    {

    int x=6,y=5,z=10;

    clrscr();

    printf(“\nAnswer is :”);

    if(x > y)

    {

      if(x > z)

      printf(“%d\n”,x);

      else

      printf(“%d\n”,z);

    }

      else

      {

        if(z > y)

        printf(“%d\n”,z);

        else

        printf(“%d\n”,y);

      }

    getche();

    }

  5.  

    void main()

    {

    int initial=1000,final=1300,

    consumed;

    float total;

    clrscr();

    consumed = final−initial;

    if(consumed>=200)

    total=consumed * 2.50;

    else

    total=consumed * 1.50;

    printf(“Total bill for %d units is Rs %.2f”,consumed,total);

    getche();

    }

  6.  

    void main()

    {

    int a=2,b=4,c=1,temp;

    clrscr();

    if

    (a<b)

    {

      if(a<c)

      temp=a;

      else

      temp=c;

    }

      else

      {

        if(b<c)

        temp=b;

        else

        temp=c;

      }

    printf(“Answer out of three numbers (%d %d %d) is %d \n”,a,b,c, temp);

    getche();

    }

V  Find the bug/s in the following program/s?

  1.  

    void main()

    {

    int cet ;

    clrscr();

    printf(“\n Enter marks obtained in CET examination :”);

    scanf(“%d”,&cet);

    if(cit>120)

    printf(“\n Eligible for admission in autonomous Institute.”);

    getch();

    }

  2.  

    void main()

    {

    clrscr();

    if(0)

    printf(“False”);

    else

    printf(“True”);

    }

  3.  

    void main()

    {

    clrscr();

    if(3>2)

    printf(“2 is smaller than 3”);

    printf(“and”);

    else

    printf(“3 is greater”);

    }

  4.  

    void main()

    {

    clrscr();

    if(3>2)

    printf(“2 is smaller than 3”);

    else

    printf(“ Numbers are equal”);

    else

    printf(“3 is greater”);

    }

VI  Attempt the following programs:

  1. Write a program to check whether the blood donor is eligible or not for donating blood. The conditions laid down are given below. Use if statement.
    1. Age should be greater than 18 years but not more than 55 years.
    2. Weight should be more than 45 kg.
  2. Write a program to check whether the voter is eligible for voting or not. If his/her age is equal to or greater than 18, display message ‘Eligible’ otherwise ‘Non- Eligible’. Use the if statement.
  3. Write a program to calculate bill of a job work done as follows. Use if-else statement.
    1. Rate of typing Rs. 3/page.
    2. Printing of 1st copy Rs. 5/page and later every copy Rs. 3/page.

    User should enter the number of pages and print out copies he/she wants.

  4. Write a program to calculate the amount of the bill for the following jobs.
    1. Scanning and hardcopy of a passport photo Rs. 5.
    2. Scanning and hardcopies (more than 10) Rs. 3.
  5. Write a program to calculate bill of Internet browsing. The conditions are given below.
    1. 1 Hour – 20 Rs.
    2. ½ Hour – 10 Rs.
    3. Unlimited hours in a day – 90 Rs.

    Owner should enter number of hours spent by customer.

  6. Write a program to enter a character through keyboard. Use switch case structure and print appropriate message. Recognize the entered character whether it is vowel, consonants or symbol?
  7. The table given below is a list of gases, liquids and solids. By entering one by one substances through the keyboard, recognize their state (gas, liquid and solid).

    WATER

    OZONE

    OXYGEN

    PETROL

    IRON

    ICE

    GOLD

    MERCURY

  8. Write a program to calculate the sum of remainders obtained by dividing with modular division operations by 2 on 1 to 9 numbers.

VII  Answer the following questions:

  1. Is it possible to use multiple else with if statement?
  2. Is it possible to use multiple default statements in switch statement?
  3. Write the use of else and default statements in if–else and switch statements, respectively.
  4. Why goto statement is avoided?
  5. Why the break statement is essential in the switch statement?
  6. Which other functions or keywords can be used in place of the break statement?
  7. Is it possible to use the else statement in place of default or vice versa?
  8. Can we put default statement anywhere in the switch case structure?
  9. What are the limitations of the switch case statement?
  10. What is a sequential execution?
  11. What is the transfer of control?
ANSWERS

I  Fill in the blanks:

Q

Ans.

1.

a

2.

a

3.

a

4.

b

5.

a

II  True or false:

Q

Ans.

1.

T

2.

T

3.

F

4.

T

5.

T

6.

T

7.

T

8.

F

9.

T

10.

T

11.

T

12.

T

13.

T

14.

T

15.

T

16.

T

17.

F

III  Select the appropriate option from the multiple choices given below:

Q

Ans.

1.

a

2.

a

3.

a

4.

a

5.

a

6.

a

7.

a

IV  What is/are the output/s of the following programs?

Q
Ans.
1.

The Entered number 7 is odd

2.

x1=−2.0 x2=−6.0

3.

18900.00

4.

Answer is :10

5.

Total bill for 300 units is Rs 750.00

6.

Answer out of three numbers ( 2 4 1) is 1

V  Find the bug/s in the following program/s?

Q
Ans.
1.

Replace cet instead of cit in if statement.

2.

if (0) is always false statement.

3.

scope of if block is not defined.

4.

if should not have multiple else.