Chapter 5

Decision Statements

Chapter Outline
5.1  INTRODUCTION

A program is nothing but the execution of a sequence of one or more instructions. In a monolithic program, the sequences of instructions are executed in the same order as they appear in the program. Quite often, it is desirable to alter the sequence of the statements in the program depending upon certain circumstances. In practical applications, there are a number of situations where one has to change the decisions based on the requirements/conditions. This involves taking a decision to see whether a particular condition is satisfied

Decision-making statements in a programming language help the programmer to transfer the control from one part of the program to another part. Thus, these decision-making statements enable the programmer to determine the flow of control.

On the basis of applications it is essential to:

  • Alter the flow of a program
  • Test the logical conditions and
  • 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 decision making-statements as listed below.

  • The if statement
  • The if-else statement
  • The nested if-else statements.
  • The else-if ladder
  • The switch case statement.
  • The break statement
  • The default keyword

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

5.2  THE if STATEMENT

Among the decision-making statements in C++, the if statement is the simplest one. C++ uses the keyword if to execute a set of command lines or a command line when the logical condition is true. It has only one option. The syntax for the simplest if statement is as shown in Figure 5.1.

 

Syntax for the simplest if statement:

if (expression) /* no semi-colon */

Statement;

Syntax for the simplest if statement:

if (expression) /* no semi-colon */

{

Statement 1;

Statement 2;

----------------

----------------

}

Fig. 5.1 The if statement

The if statement contains an expression. The expression is always enclosed within a pair of parentheses. The conditional statements should not be terminated with semicolons (;). 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 a good practice to use curly braces even with a single statement.

The if keyword is followed by an expression in parentheses. The expression is evaluated. If the expression is true, it returns 1, otherwise 0. The value 1 or any non-zero value is considered as true and 0 as false. In C++, the values (1) true and (0) false are known bool data type. The bool data type occupies one byte in memory. If the given expression in the if statement is true, the following statement or block of statements are executed; otherwise, the statement that appears immediately after the if block (true block) is executed as given in Figure 5.2.

Fig. 5.2

Fig. 5.2 The simple if statement

Fig. 5.3

Fig. 5.3 Flowchart for if statement

As shown in Figure 5.2, the expression is always evaluated to true or false. When the expression is evaluated as true, the statements within the if block are executed and the program continues from the next statement. When the expression is false, the if block is skipped and statement 3 is executed.

The expression given in the if statement may not be always true or false. For example, if (1) or if (0). When such a statement is encountered, the compiler will displays a warning message “condition is always true” or “condition is always false”. Instead of the expression, we can also use the function that returns 0 or 1 return values. The following programs illustrates all the above discussed points.

Flowchart for if statement is as shown in Figure 5.3. Example of a simple if statement.

 

5.1 Write a program to declare the price of the book with if statement and check its price. If its price is less than or equal to 600, print the output with some comment, else terminate.

Algorithm:

Step 1: Start.

Step 2: Declare the price of a book with some variable.

Step 3: Check the condition with if statement i.e. price<=600.

Step 4: If ‘yes’ print the output with some comment, otherwise terminate.

Step 5: End.

#include<iostream.h>

#include<conio.h>

int main()

{

int price;

clrscr();

cout<<“ Enter the price of the book:”;

cin>>price;

if(price<=600)

{

      cout<<“ Hurry up buy the book!!!!!”;

}

return 0;

}

OUTPUT

Enter the price of the book: 345

Hurry up buy the book!!!!!

Explanation: In the above program, the price of the book is entered through the keyboard. If entered price is less than or equal to 600, the message displayed is “Hurry up buy the book!!!!!”.

 

5.2 Write a program to check the equivalence of two numbers.      image

#include<iostream.h>

#include<conio.h>

int main()

{

int m,n;

clrscr();     cout<<“ Enter two numbers:”;

cin>>m>>n;

if(m-n==0)

cout<<“ Two numbers are equal.”;

return 0;

}

OUTPUT

Enter two numbers: 5 5

Two numbers are equal.

Explanation: The two numbers are entered. They are checked with if statement. If the difference of two numbers is zero, it prints the message “Two numbers are equal”.

 

5.3 Write a program to use library function strlen() and check for a string. If the string is non-zero, then display some message.

#include<iostream.h>

#include<conio.h>

#include<string.h>

int main()

{

static char nm[]=“Hello”;

clrscr();

if (strlen(nm))

{

cout<<“The string is not empty.”;

}

return 0;

}

OUTPUT

The string is not empty.

Explanation: In the above program, the character array nm[] is initialized with the string “Hello”. The strlen() function is used in the if statement. The strlen() function calculates the length of the string and returns it. If the string is empty, it returns (0) false: otherwise, it returns a non-zero value (string length). The non-zero value is considered as true. The strlen() function returns non-zero value (true). The if statement displays the message “The string is not empty.” Here, instead of an expression, a library function is used.

5.3  MULTIPLE ifs

In our daily life also we take alternate decisions to satisfy conditions such as should we go for purchasing a laptop, desktop, or tablet based on the budget/specifications of a device/application. In C++ language, we take the help of multiple ifs to tackle such a problem.

The syntax of multiple ifs is shown in Figure 5.4. Programs on multiple ifs are as follows.

 

Syntax for the multiple ifs:

if (expression) /* no semi-colon */

Statement 1;

if (expression) /* no semi-colon */

Statement 2;

if (expression) /* no semi-colon */

Statement 3;

Fig. 5.4 Multiple ifs

5.4 Write a program to enter the percentage of marks obtained by a student and display the class obtained.

#include<iostream.h>

#include<conio.h>

int main()

{

float per;

clrscr();

cout<<“ Enter the percentage:”;

cin>>per;

if(per>=90 && per<=100)

      cout<<“ Distinction”;

if(per>=70 && per<90)

      cout<<“ First class”;

if(per>=50 && per<70)

      cout<<“ Second class”;

if(per>=40 && per<50)

      cout<<“ Pass”;

if(per<40)

cout<<“ Fail”;

return 0;

}

OUTPUT

Enter the percentage: 95

Distinction.

5.5 Program to display whether an entered character is in upper case, lower case, or not an alphabet.      image

#include<iostream.h>

#include<conio.h>

int main()

{

char c;

clrscr();

cout<<“ Enter the alphabet:”;

cin>>c;

if(c>=65 && c<=90)

cout<<“ Entered alphabet is in Upper case”;

if(c>=97 && c<=122)

cout<<“ Entered alphabet is in Lower case ”;

if(c>=48 && c<=57)

cout<<“It is not an alphabet.”;

return 0;

}

OUTPUT

Enter the alphabet: 7

It is not an alphabet.

Explanation: The program prompts the user to enter an alphabet. In case an uppercase letter is entered, the first if statement is executed, otherwise, for lowercase letters the second if statement is executed. For digit entry the third if is executed.

5.4  THE if-else STATEMENT

In the if–else statement, if the expression/condition is true, the body of the if statement is executed; otherwise, the body of the else statement is executed. The else keyword is used when the expression is not true. The format/syntax of if–else statement is given in Figures 5.5, 5.6 and 5.7.

As shown in Figure 5.7, both if and else blocks contain statement/statements. When the expression is true, the if block is executed, otherwise, the else block is executed.

 

if( expression)

execute the statement1;

else

execute the statement2;

Fig. 5.5 The if-else statement

OR
Fig. 5.6

Fig. 5.6 The if-else statement

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

if (expression is true) // if block

{

      statement1;

      statement 2;

}

else         // else block

{

      statement 3;

      statement 4;

}

Fig. 5.7 The if-else statement

Flowchart for if-else is as shown in Figure 5.8.

Fig. 5.8

Fig. 5.8 The if-else flow-chart

Consider the following programs for understanding the if-else statement.

 

5.6 Write a program to enter age and display a message whether the user is eligible for voting or not. Use if-else statement.

#include<iostream.h>

#include<constream.h>

#include<string.h>

int main()

{

clrscr();

int age;

cout<<“Enter Your Age:”;

cin>>age;

if (age>=18)

{

      cout<<“You are eligible for voting.”;

}

else

{

      cout<<“You are not eligible for voting”<<endl;

      cout<< “Wait for”<<18-age<<“year(s).”;

}

return 0;

}

OUTPUT

Enter Your Age: 17

You are not eligible for voting

Wait for 1 year(s).

Explanation: In the above program, the user enters his/her age. The integer variable age is used to store the value. The if statement checks the value of age. If the age is greater than or equal to 18, then the if block of the statement is executed. Otherwise, the else block of statement is executed.

 

5.7 Write a program with simple if-else statement. If the entered cricket score is less than 50 display one message otherwise another message.

#include<iostream.h>

#include<conio.h>

int main()

{

int score;

clrscr();

cout<<“Enter the run scored of batsman: ”;

cin>>score;

if(score>=50)

cout<<“ nCongrats !! You scored a half / more than half century ”;

else

if(score<50)

cout<<“ nCome on !! You can too score a half century ”;

return 0;

}

OUTPUT

Enter the run scored of batsman: 45

Come on!! You can too score a half century

Explanation: The program prompts the user to enter the score of the batsman. If the score entered is greater than 50 or equal to 50, then it shows a particular message. Otherwise, for a score less than 50, the other message displayed.

5.5  NESTED if-else STATEMENTS

In this kind of statement, a number of logical conditions are tested for taking decisions. Here, the if keyword followed by an expression is evaluated. If it is true, the compiler executes the block following the if condition; otherwise, it skips this block and executes the else block. It uses the if statement nested inside an if-else statement, which is nested inside another if-else statement. This kind of nesting can be limitless. The syntax of a simple nested if-else statement is shown in Figure 5.9.

The flowchart for nesting an if-else statement is shown in Figure 5.10.

 

if (expression1)

{ if(expression2)

statement1;

else

statement2;

}

else

{ if(expression3)

statement3;

else

statement4;

}

next statement5;

Fig. 5.9 The nested if-else

Fig. 5.10

Fig. 5.10 The nested if-else flow-chart

Programs on nested if-else statements are as follows.

 

5.8 Program to print the largest of three numbers.      image

#include<iostream.h>

#include<conio.h>

int main()

{

int a,b,c;

clrscr();

cout<<“ Enter three numbers:”;

cin>>a>>b>>c;

if(a>b)

{

      if(a>c)

        cout<<“ a is largest ”;

      else

        cout<<“ c is largest ”;

}

else

{

      if(b>c)

        cout<<“ b is largest ”;

      else

        cout<<“ c is largest ”;

      }

return 0;

}

OUTPUT

Enter three numbers: 3 6 89

c is largest.

Explanation: Three numbers are entered. They are compared as per the theory illustrated above and the largest number is obtained and displayed

5.6  THE else-if LADDER

A common programming construct is the else-if ladder, sometimes called the if-else-if staircase because of its appearance. In the program one can write a ladder of else-if. The program goes down the ladder of else-if, in anticipation of one of the expressions being true.

The general syntax of else-if ladder is as shown in Figure 5.11.

 

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

if(condition)

{

statement 1;    /* if block*/

statement 2;

}

else if(condition)

{

statement 3;     /* else if block*/

statement 4;

}

else

{

statement 5;     /* last else block */

statement 6;

}

Fig. 5.11 The else-if ladder

The conditions are evaluated from top to bottom. As soon as a true condition is met, the associated statement block gets executed and the rest of the ladder is bypassed. If none of the conditions are met, then the final else block is executed. If this else is not present and none of the if statements evaluate to true, then the entire ladder is bypassed

Programs on else if ladder are explained as follows.

 

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

 

No. of units Consumed

Rates in (Rs.)

200 - 500

3.5

100 - 200

2.50

Less than 100

1.50

#include<iostream.h>

#include<conio.h>

int main()

{

int previous,current,consumed;

float total;

clrscr();

cout<<“ Initial & Final Readings:”;

cin>>previous>>current;

consumed = current-previous;

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;

cout<<“ Total no of units consumed: ”<<consumed;

cout<<“ Electric Bill for units ”<< consumed<< “is” <<total;

return 0;

}

OUTPUT

Initial & final readings: 100 235

Total no of units consumed: 135

Electric bill for units 135 is 337.5

Explanation: Previous and current electrical readings are entered through the keyboard. Their difference is the total energy consumed. As per the table, rates are applied and the total bill based on consumption of energy is calculated

 

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

image
image

#include<iostream.h>

#include<stdio.h>

#include<conio.h>

int main()

{

float bs,hra,da,cv,ts;

clrscr();

cout<<“ Enter Basic Salary:”;

cin>>bs;

if(bs>=10000)

{

hra=20*bs/100;

da= 110*bs/100;

cv=500;

}

else

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

{

hra=15*bs/100;

da=100*bs/100;

cv=400;

}

else

{

if(bs<5000)

hra=10*bs/100;

da= 90*bs/100;

cv=300; }

ts=bs+hra+da+cv;

cout<<“ Basic Salary: ”<<bs;

cout<<“ HRA: ”<<hra;

cout<<“ DA: ”<<da;

cout<<“ Conveyance: ”<<cv;

cout<<“ Gross Salary: ” <<ts;

return 0;

}

OUTPUT

Enter Basic Salary: 7500

Basic Salary: 7500

HRA: 1125

DA: 7500

Conveyance: 400

Gross Salary: 16525.

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 else-if statements are used. Based on the conditions, gross salary is calculated and displayed.

 

5.11 Write a program to simulate tariff charges for reaching different destinations by bus.

#include<conio.h>

#include<iostream.h>

int main()

{

int cost,ch;

clrscr();

cout<<“ ..........NANDED BUS STATION........ ”;

cout<<“................Menu................”;

cout<<“ 1.Bombay”;

cout<<“ 2.Nagpur”;

cout<<“ 3.Pune”;

cout<<“ 4.Amravati”;

cout<<“ 5.Aurangabad”;

cout<<“ 6.Enter your destination:”;

cin>>ch;

if(ch==1)

      cost=1000;

else if(ch==2)

      cost=700;

else if(ch==3)

      cost=500;

else if(ch==4)

      cost=600;

else if(ch==3)

      cost=400;

else

      cost=0;

if(cost!=0)

{

      cout<<“ The ticket cost is: Rs ”<<cost;

      cout<<“ Pay the amount to get book the ticket”;

}

else

      cout<<“Sorry there’s no bus to the desired destination”;

cin.get();

return 0;

}

OUTPUT

..........NANDED BUS STATION........

................Menu................

1.Bombay

2.Nagpur

3.Pune

4.Amravati

5.Aurangabad

Enter your destination: 4

The ticket cost is: Rs 600

Pay the amount to book the ticket.

Explanation: As can be seen, the program simulates a bus station. We use an if-else-if ladder to find out the cost of a ticket to a particular station, if there was a bus to that station. There was no bus to that station that had cost=0. Finally, if the cost is non-zero, it is printed. The user is prompted to enter the choice. Depending upon the choice, the fare of destination station is displayed. In the above example, the choice 4 is given. The result displayed is

“The ticket cost is : Rs 600

Pay the amount to book the ticket.”

5.7  UNCONDITIONAL CONTROL TRANSFER STATEMENTS

C/C++ has four statements that perform an unconditional control transfer. They are return, goto, break and continue. Of these, return is used only in functions. The goto and return may be used anywhere in the program but continue and break statements may be used only in conjunction with a loop statement. The break is used most frequently in switch case.

5.7.1  The goto statement

This statement does not require any condition. This statement passes control anywhere in the program without considering any condition. The general format for this statement is shown in Figure 5.12.

Here, a label is any valid label either before or after goto. The ‘label’ must start with any character and can be constructed with rules used for forming identifiers. Avoid using the goto statement.

 

goto label;

-----

-----

-----

label:

Fig. 5.12 The goto statement

5.12 Write a program to demonstrate the use of goto statement.

#include<iostream.h>

#include<constream.h>

void main()

{

int x;

clrscr();

cout<<“Enter a Number:”;

cin>>x;

if (x%2==0)

goto even;

else

goto odd;

even: cout<<x<<“ is an Even Number.”;

return;

odd: cout<<x<<“ is an Odd Number.”;

}

OUTPUT

Enter a Number: 5

5 is an Odd Number.

Explanation: In the above program a number is entered. The number is checked to see if it is 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 the respective message will be displayed.

5.7.2  The break Statement

The break statement allows the programmer to terminate the loop. The break skips from the loop or the block in which it is defined. The control then automatically passes on to the first statement after the loop or the block. The break can be associated with all the conditional statements (especially switch case). We can also use break statements in the nested loops. If we use break statement in the innermost loop, then the control of the program is terminated from that loop only and resumes at the next statement following that loop. The widest use of this statement is in the switch case where it is used to avoid flow of control from one ‘case’ to the other. Programming examples on break are given in switch topic.

5.7.3  The continue Statement

The continue statement works somewhat like the break statement. Instead of forcing the control to the end of the loop (as it is in case of break), the continue case causes the control to pass on to the beginning of the block/loop. In the case of for loop, the continue case initiates the testing condition and increment on steps has to be executed (while rest of the statement following the continue are neglected). For while and do-while, the continue case causes control to pass on to conditional tests. It is useful in a programming situation where it is required that particular iterations occur only up to some extent or when some part of the code has to be neglected. The programs on continue are explained in the control loop chapter.

5.8  THE switch STATEMENT

The switch statement is a multi-way branch statement and an alternative to if-else-if ladder in many situations. The expression of switch contains only one argument, which is then checked with a number of switch cases. The switch statement evaluates the expression and then looks for its value among the case constants. If the value is matched with a particular case constant, then those case statements are executed until a break statement is found or until the end of switch block is reached. If not, then simply the default (if present) is executed (if a default is not present, then the control flows out of the switch block). The default is normally present at the bottom of the switch case structure. But we can also define default statement anywhere in the switch structure. The default block must not be empty. Every case statement terminates with a ‘:’ (colon). The break statement is used to stop the execution of succeeding cases and pass the control to the end of the switch block.

 

switch(variable or expression)

{

case constant A:

statement;

break;

case constant B:

statement;

break;

default:

statement;

}

Fig. 5.13 The switch case.

The syntax of the switch case statement is shown in Figure 5.13.

Note the following for switch case.

  • 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, etc. In case of character constant, the values may be with alphabets such as ‘x’, ‘y’, ‘z’, etc.
  • The switch organisation: The switch expression should neither be terminated with a semicolon (;) nor with any other symbol. The entire case structure following the switch should be enclosed within 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 within curly braces. Here, the keyword case & break performs, respectively, the job of opening and closing curly braces.
  • The switch execution: When one of the cases is satisfied, the statements following it are executed. In case there is no match, the default case is executed.
  • The break statement used in switch passes control outside the switch block. By mistake if no break statements are given, all the cases following it are executed.

The flowchart for the switch case is as shown in Figure 5.14.

Fig. 5.14

Fig. 5.14 Flowchart for switch case.

Programs on switch case are as follows.

 

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

#include<iostream.h>

#include<conio.h>

int main()

{

int ch;

clrscr();

cout<<“ [1] .........”;

cout<<“ [2] _________”;

cout<<“ [3] *********”;

cout<<“ [4] ==========”;

cout<<“ [5] EXIT”;

cout<<“ ENTER YOUR CHOICE:”;

cin>>ch;

switch(ch)

{

      case 1:

      cout<<“ ............................................”;

      break;

      case 2:

      cout<<“ ___________________________________________”;

      break;

      case 3:

      cout<<“ ********************************************”;

      break;

      case 4:

      cout<<“ ============================================”;

      break;

      case 5:

      cout<<“ Terminated by choice”;

      break;

default:

cout<<“ Invalid Choice”;

}

return 0;

}

OUTPUT

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

[2] _________

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

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

[5] EXIT

ENTER YOUR CHOICE: 4

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

Explanation: In the above program a menu appears with five options and it requests the user to enter his/her 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 according to the user’s choice. If the user enters a non-listed value, then no match occurs and the default is executed. The default warns the user with a message “Invalid Choice.”

 

5.14 Write a program to perform the multiple arithmetic operations as l. Addition, 2. Subtraction, 3. Multiplication, and 4. Division using switch case.

#include<iostream.h>

#include<conio.h>

int main()

{

int a,b,c,ch;

clrscr();

cout<<“ =================”;

cout<<“ MENU”;

cout<<“ =================”;

cout<<“ [1] ADDITION”;

cout<<“ [2] SUBTRACTION”;

cout<<“ [3] MULTIPLICATION”;

cout<<“ [4] DIVISION”;

cout<<“ =================”;

cout<<“ ENTER YOUR CHOICE:”;

cin>>ch;

if (ch<=4 & ch>0)

{

cout<<“Enter Two Numbers:”;

cin>>a>>b;

}

switch (ch)

{

      case 1 :

      c=a+b;

      cout<<“ Addition:”<<c;

      break;

      case 2 :

      c=a-b;

      cout<<“ Subtraction:”<<c;

      break;

      case 3 :

      c=a*b;

      cout<<“ Multiplication:”<<c;

      break;

      case 4 :

      c=a/b;

      cout<<“ Division:”<<c;

      c=a%b;

      cout<<“ Remainder:”<<c;

      break;

      default:

      cout<<“ Invalid choice:”;

      break;

      }

      return 0;

}

OUTPUT

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

             MENU

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

[1] ADDITION

[2] SUBTRACTION

[3] MULTIPLICATION

[4] DIVISION

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

Enter your choice: 4

Enter two numbers: 20 10

Division :2

Remainder: 0

Explanation: The above program is used to perform various arithmetic operations. It requests the user to enter the choice. The choice entered by the user is checked with the if statement. If it is between 1 and 4, 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 the relevant operation.

 

5.15 Write a program to enter a month number of year 2011 and display number of days present in the month.

#include<iostream.h>

#include<conio.h>

void main()

{

clrscr();

int month,day;

cout<<“Enter a month of year 2011:”;

cin>>month;

switch(month)

{

      case 1:

      case 3:

      case 5:

      case 7:

      case 8:

      case 10:

      case 12:

      day=31;

      break;

      case 2:

      day=28;

      break;

      case 4:

      case 6:

      case 9:

      case 11:

      day=30;

      break;

}

cout<<“ Number of days in this month are ”<<day;

}

OUTPUT

Enter a month of year 2011: 2

Number of days in this month are 28.

5.9  NESTED switch case

C/C++ supports the nesting of switch case. The inner switch can be part of an outer switch. The inner and the outer switch case constants may be the same. No conflict arises even if they are same. The example below demonstrates this concept.

 

5.16 Write a program to demonstrate the nested switch case statement.      image

#include<iostream.h>

#include<constream.h>

int main()

{

int x;

clrscr();

cout<<“ Enter a number:”;

cin>>x;

      switch(x)

{

case 0:

cout<<“ The number is 0”;

break;

default:

int y;

y=x%2;

switch(y)

{

      case 0:

      cout<<“ The number is even”;

      break;

      case 1:

      cout<<“ The number is odd”;

      break;

      }

      }

return 0;}

OUTPUT

Enter a number: 5

The number is odd

Explanation: The above program aims at identifying whether the input number is zero or an even or an odd number. The first switch case finds out whether the number is zero or non-zero. If a non-zero value is entered, a default statement of first switch case statement is executed, which executes another nested switch case. The nested switch case statement determines whether the number is even or odd and displays the respective messages.

SUMMARY
  1. Decision-making statements in a programming language help the programmer to transfer the control from one part of the program to another part.
  2. C++ language supports the following decision-making statements: if statement, if-else statement, nested if-else statements, else-if ladder, switch case statement, break statement, and the default keyword.
  3. C++ uses the keyword if to execute a set of command lines or a command line when the logical condition is true.
  4. Multiple ifs are used in C++ to tackle alternate decisions.
  5. In the if–else statement, if the expression/condition is true, the body of the if statement is executed; otherwise, the body of the else statement is executed. The else keyword is used when the expression is not true.
  6. In nested if-else statements, a number of logical conditions are tested for taking decisions. Here, the if keyword followed by an expression is evaluated. If it is true, the compiler executes the block following the if condition; otherwise, it skips this block and executes the else block. It uses the if statement nested inside an if-else statement, which is nested inside another if-else statement. This kind of nesting can be limitless.
  7. A common programming construct is the else-if ladder, sometimes called the if-else-if staircase because of its appearance. In the program one can write a ladder of else-if. The program goes down the ladder of else-if, in anticipation of one of the expressions being true.
  8. C/C++ has four statements that perform an unconditional control transfer. They are return, goto, break and continue. Of these, return is used only in functions. The goto and return may be used anywhere in the program but continue and break statements may be used only in conjunction with a loop statement. The break is used most frequently in switch case.
  9. The goto statement does not require any condition. This statement passes control anywhere in the program without considering any condition.
  10. The break statement allows the programmer to terminate the loop. It is widely used in the switch case where it is used to avoid the flow of control from one “case”
  11. The continue statement works somewhat like the break statement. Instead of forcing the control to the end of the loop (as it is in case of break), the continue case causes the control to pass on to the beginning of the block/loop. It is useful in a programming situation where it is required that particular iterations occur only up to some extent or when some part of the code has to be neglected.
  12. The switch statement is a multi-way branch statement and an alternative to if-else-if ladder in many situations.
  13. C/C++ supports the nesting of switch case. The inner switch can be part of an outer switch. The inner and the outer switch case constants may be the same. No conflict arises even if they are same.
EXERCISES

(A) Answer the following questions

  1. Give the syntax and flowchart of the if decision making statement.
  2. Why is it important to use multiple ifs in a program?
  3. Is it possible to use multiple else with an if statement?
  4. Explain the use of if-else statement.
  5. Explain the use of switch case statement.
  6. Explain the use of keyword default.
  7. Is it possible to use multiple default statements in a switch statement?
  8. Write the use of else and default statements in if-else and switch statements, respectively.
  9. Is it possible to use else statement in place of default or vice versa?
  10. Can we put default statement anywhere in the switch case structure?
  11. What are the limitations of switch case statement?
  12. What is sequential execution?
  13. What is transfer of control? Explain the control transfer keywords used in C++.
  14. Explain nested ifs.
  15. Explain nested switch case statement.

(B) Answer the following by selecting the appropriate option

  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. Conditional if statement always returns
    1. 0 or 1
    2. 1 or 2
    3. –1 or 0
    4. none of the above
  6. The meaning of if (1) is
    1. always false
    2. always true
    3. both (a) and (b)
    4. none of the above
  7. In case curly braces are absent, following the if statements, then what is the scope of if block?
    1. one statement
    2. two statements
    3. four statements
    4. none of the above
  8. In nested loop
    1. the inner most loop is completed first
    2. the outer most loop is completed first
    3. both (a) and (b)
    4. none of the above
  9. What will be the output of the following program?

    #include<iostream.h>

    #include<conio.h>

    int main()

    {

    char x=‘H’;

          clrscr();

    switch(x)

    {

    case ‘H’: cout<<“H”;

    case ‘E’: cout<<“E”;

    case ‘L’: cout<<“L”;

    case ‘L’: cout<<“L”;

    case ‘O’: cout<<“O”;

    }

    return 0;

    }

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

    #include<iostream.h>

    #include<conio.h>

    int main()

    {

    char x=‘G’;

    clrscr();

    switch(x)

    {

    if( x==‘B’)

    {

    case ‘d’: cout<<“o”;

    case ‘B’: cout<<“Bad”;

    }

    else

    case ‘G’: cout<<“Good”;

    break;

    default : cout<<“ Boy”;

    }

    return 0;

    }

    1. Good Boy
    2. Good
    3. Boy
    4. none of the above
  11. What will be the output of the following program?

    #include<iostream.h>

    #include<conio.h>

    int main()

    {

    char x=‘d’;

    clrscr();

    switch(x)

    {

    case ‘b’:

    cout<<“0 1 001”;

    break;

    default :

    cout<<“1 2 3”;

    break;

    case ‘R’:

    cout<<“I II III”;

    }

    return 0;

    }

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

(C) Attempt the following programs

  1. Write a program to check whether the blood donor is eligible for donating blood. The conditions laid down are as under. 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. If his/her age is equal to or greater than 18, display the message “Eligible” otherwise “Non-eligible”. Use if statement.
  3. Write a program to calculate the bill of a job work done as follows. Use if else statement.
    1. Rate of typing 3 Rs./ page.
    2. Printing of first copy Rs. 5/ page and the rate of every copy taken after that as Rs. 3/ page.

    The user should enter the number of pages and printout 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 Rs. 20.
    2. ½ Hour Rs. 10.
    3. Hours Rs. 90.

    The owner should enter the number of hours spent by the customer.

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

    OXYGEN

    PETROL

    IRON

    ICE

    GOLD

    MERCURY

  8. Write a program to display the days of week using switch case.
  9. Write a program to calculate telephone bill based on the following.

    (a) calls 0 to 100

    Rs. 1/call.

    (b) calls 101 >=500

    Rs. 0.75/call.

    (c) more than 500 calls

    Rs. 0.50/call.

  10. Write a program to find the incentive to be offered to a salesman based on the sales of number of items/turnover. Use else if ladder.
  11. Write a program to display grades obtained by a student in the MCA CET examination. Assume suitable data.
..................Content has been hidden....................

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