4

CHAPTER

Control Structures

C
H
A
P
T
E
R

O
U
T
L
I
N
E
—•  4.1 Introduction
—•  4.2 Decision-Making Statements
—•  4.3 The if-else Statement
—•  4.4 The Nested if–else Statement
—•  4.5 The jump Statement
—•  4.6 The goto Statement
—•  4.7 The break Statement
—•  4.8 The continue Statement
—•  4.9 The switch case Statement
—•  4.10 The Nested switch( )case Statement
—•  4.11 Loops in C/C++
—•  4.12 The for Loop
—•  4.13 Nested for Loops
—•  4.14 The while Loop
—•  4.15 The do-while Loop

4.1 INTRODUCTION

This chapter deals with the basics of control structures of C++ language. Those who are already familiar with C, may skip this chapter. Those who are new to C++, should read this chapter thoroughly. As discussed earlier, C++ is a superset of C. The control structures of C and C++ are same. In this chapter, the concepts of structures are illustrated in detail for the new users.

A Program is nothing but a set of statements written in sequential order, one after the other. These statements are executed one after the other. Sometimes it may happen that the programmer requires to alter the flow of execution, or to perform the same operation for fixed iterations or whenever the condition does not satisfy. In such a situation the programmer uses the control structure. There are various control structures supported by C++. Programs which use such (one or three) control structures are said to be structured programs.

The C++ control structure covers two sets of statements. The set that performs certain operations repetitively is called as loop statements and the set that makes decision is known as decision-making statements.

4.2 DECISION-MAKING STATEMENTS

Following are decision-making statements.

(1) The if statement

(2) The switch ( ) case statement.

Simple if statement The syntax of simple if statement is described below

Syntax for the simplest if statement:
   if (expression) /* no semi-colon */
       Statement;

The if statement contains an expression. 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 as bool type data. The bool type data occupies one byte in memory. If the given expression in the if( ) statement is true, the following statement or block of statements too are executed, otherwise the statement that appears immediately after if block (true block) is executed as given in Figure 4.1.

images

Fig. 4.1 The simple if statement

As shown in Figure 4.1, the expression is always evaluated to true or false. When the expression is true, the statement in if block is executed. When the expression is false the if block is skipped and the statement (state-ment3) after if block 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 statement is encountered, the compiler will display a warning message “condition is always true” or “condition is always false”. In place of expression we can also use function that returns 0 or 1 return values. The following programs illustrate the points discussed above.

4.1 Write a program to enter age and display message whether the user is eligible for voting or not.

# include <iostream.h>
# include <constream.h>
# include <string.h>


void main( )
   clrscr( );
   int age;
   cout<<"Enter Your Age :";
   cin>>age;
       if (age>=18)
       {
       cout <<" You are eligible for voting.";
       }
}

OUTPUT
Enter Your Age : 23
You are eligible for voting.

Explanation: In the above program, integer variable age is declared. The user enters his/her age. The value is tested with if statement. If the age is greater than or equal to 18 the statement followed by if statement is executed. The message displayed will be “You are eligible for voting.” If the condition is false nothing is displayed.

4.2 Write a program to use library function with if statement instead of expression.

# include <iostream.h>
# include <constream.h>
# include <string.h>


void main( )
{
   static char nm[]="Hello";
   clrscr( );


if (strlen(nm))
{  cout <<" The string is not empty.";  }


}

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 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 expression, a library function is used.

4.3 THE if–else STATEMENT

The simple if statement executes statement only if the condition is true otherwise it follows the next statement. The else keyword is used when the expression is not true. The else keyword is optional. The syntax of if..else statement is given below and Figure 4.2 describes the working of if..else statement.

The format 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)

     {
     statement 1;     →     if block
     statement 2;
                   }
   


  else

     {
     statement 3;     →     else block
     statement 4;
                   }

images

Fig.4.2 The if-else statement

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

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

# include <iostream.h>
# include <constream.h>
# include <string.h>


void main( )
{
clrscr( );


int age;
cout<<"Enter Your Age : ";
cin>>age;


   if (age>=18)
   {
     cout <<" You are eligible for voting.";
   }
   else
   {
     cout <<" You are noneligible for voting"<<endl;
 
     cout<< " Wait for "<<18-age<<" year(s).";
   }
}

OUTPUT:
Enter Your Age : 17
You are noneligible 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, the if block of statement is executed, otherwise the else block of statement is executed. Thus, the else statement extends if statement.

4.4 Write a program with simple if statement. If entered score is less than 50 display one message, otherwise another message.

#include<iostream.h>
#include<conio.h>
int main( )
{
int v;
clrscr( );
cout<<"Enter a number : ";
cin>>v;
if(v>=50)
cout<<"
Congrats !! You scored a half / more than half century ";
else
if(v<50)
cout<<"
Come on !! You can score a half century ";
return 0;
}

OUTPUT:
               Enter a number : 49
               Come on !! You too can score a half century

               Enter a number : 56
               Congrats !! You scored a half / more than half century

Explanation: The program first prompts the user to enter a number ‘v’. If it is greater than 50 or equal to 50, it prompts a particular message, otherwise for less than 50, other message is displayed. If found true, a particular message is prompted, otherwise another.

4.4 THE NESTED if–else STATEMENT

In this kind of statements, 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, otherwise it skips and executes else block. In if..else statement, else block is executed by default after failure of if condition. In order to execute the else block depending upon certain conditions we can add repetitively if statements in else block. This kind of nesting will be unlimited.

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

if ( condition)
   {
   statement 1;         -> if  block
   statement 2;
                  }


else   if (condition)
{
   statement 3;         -> else block
   statement4;
                  }
else
{
statement5;
statement6;
                  }

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 false, control passes to else block where condition is again checked with the if statement. This process continues till there is no if statement in the last else block.

3. If one of the if statement satisfies the condition, other nested if..else will not be executed.

Following programs illustrates the working of nested if-else statements.

4.5 Write a program to enter two characters and display the larger character. Use nested if-else statements.

# include <iostream.h>
# include <constream.h>


void main( )
{
   char j,k;
   clrscr( );
   cout<<"
 Enter a character :";
   j=getche( );
   cout <<"
 Enter another character : ";
   k=getche( );
       cout<<endl;


   if (j>k)
   {
       cout <<j <<" is larger than "<<k;
   }
       else if(k>j)
   {
       cout <<k <<" is larger than "<<j;
   }
   else
   {
       cout <<"Both the charcters are same";
   }
}

OUTPUT

Enter a character : S
Enter another character : A
S is larger than A

Explanation: In the above program, two characters are entered and stored in the character variable j and k. The first if statement checks whether j is greater than k. Here, comparison is done considering ASCII values. If the condition is true, a message will be displayed and program terminates. In case the condition is false theelse block is executed. In the else block another if statement is present. The if statement inside the else block checks whether k is greater than j or not. If the condition is true if block is executed, otherwise else block is executed.

4.6 Write a program to explain the concept of nested if-else statements.

#include<conio.h>
#include<iostream.h>
int main( )
{
int score;
clrscr( );
cout<<"
Enter Sachin's score :";
cin>>score;
if(score>=50)
{
   if(score>=100)
   cout<<"Sachin scored a century and more runs";
   else
   {
cout<<"
Sachin scored more than half century ";
cout<<"
Cross your fingers and pray he completes century ";
   }
}
else
   {
   if(score==0)
   cout<<"Oh my God ";
   if(score>0)
   cout<<"Not in form today ";
   }
return 0;
}

OUTPUT:
Enter Sachin's score : 0
Oh my God !

Enter Sachin's score : 45
Not in form today

Enter Sachin's score : 60
Sachin scored more than half century
Cross your fingers and pray he completes century

Enter Sachin's score : 116
Sachin scored a century and more runs

Explanation: From above it can be seen that if score was greater than 50 and greater than 100 then a particular message is prompted. If score was greater than 50 but less than 100, then another set of messages is prompted. If, however, the score was less than 50 and equal to 0 then a particular message is prompted. If score was less than 50 but not 0 then another message is displayed.

4.7 Write a program to execute if statement without any expression.

# include <iostream.h>
# include <constream.h>


void main( )
{


   int j;
   clrscr( );
   cout <<"
 Enter a value : ";
   cin>>j;


   if(j)
   cout<<"Wel Come";
   else
   cout<<"Good Bye";
}

OUTPUT
Enter a value : 0
Good Bye

Explanation: In the above program, an integer variable j is declared. The user is asked to enter an integer value. The entered value is stored in the variable j. The if statement checks the value of j. As explained at the beginning of this chapter, 0 is considered as false and any non-zero value is true. Thus, when user enters 0, the else block is executed and when a non-zero value is entered, if block is executed.

The if-else-if Ladder Statement

A common programming construct is the if-else-if ladder, sometimes called the if-else-if staircase because of it's appearance. It's general form is

if ( expression) statement block1;
    else statement block2;
      if(expression) statement block3;
         else statement block4;
           if(expression) statement block5;
           .
           .
           .
           .
           .
           else statement blockn;

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

Although the indentation of the preceding ‘if-else-if’ ladder is technically correct, it can lead to overly deep indentation. Imagine 256 (maximum allowed) such stairs and each indented: Enough to confuse!

This reason made it vital to use the form as shown below:

If ( expression)
   statement block1;     → if block
else    if (expression)
   statement  block2;    → else block
else    if (expression)
   statement  block3;    → else block
.
.
.
else
   statement  block5;

The following program will clear your understanding.

4.8 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<<"
Bombay..1";
cout<<"
Nagpur..2";
cout<<"
Pune..3";
cout<<"
Amravati..4";
cout<<"
Aurangabad..5";
cout<<"

Enter your destination :";
cin>>ch;
if(ch==1)
   cost=100;
else if(ch==2)
   cost=70;
else if(ch==3)
   cost=50;
else if(ch==4)
   cost=60;
else if(ch==3)
   cost=40;
else
   cost=0;
if(cost!=0)
{
   cout<<"

The ticket cost is : Rs "<<cost;
   cout<<"
Pay the amount to get booked";
}
else
   cout<<"Sorry there's no bus to desired destination";
cin.get( );
return 0;
}

OUTPUT:
..........NANDED BUS STATION........
................Menu................
Bombay..1
Nagpur..2
Pune..3
Amravati..4
Aurangabad..5
Enter your destination : 4
The ticket cost is : Rs 60
Pay the amount to get booked

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

“The ticket cost is : Rs 60

Pay the amount to get booked”.

4.5 THE jump STATEMENT

C/C++ has four statements that perform an unconditional control transfer. These 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. In ‘switch case’ ‘break’ is used most frequently.

4.6 THE goto STATEMENT

This statement does not require any condition. This statement passes control anywhere in the program without least care for any condition. The general format for this statement is shown below:

goto  label;
__
__
__
label:

where, 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 goto statement.

4.9 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 Even Number.";
return;
odd: cout<<x<<" is Odd Number.";
}

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 messages will be displayed.

4.7 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 statement 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 program is terminated from that loop only and resumes at the next statement following that loop. The widest use of this statement is in switch case where it is used to avoid flow of control from one case to other.

4.8 THE continue STATEMENT

The continue statement works quite similar to the break statement. Instead of forcing the control to end of loop (as it is in case of break), continue causes the control to pass on to the beginning of the block/loop. In case of for loop, the continue case causes the condition testing and incrementation steps to be executed (while rest of the statements following continue are neglected). For while and do-while, continue causes control to pass on to conditional tests. It is useful in programming situation when you want particular iterations to occur only up to some extent or you want to neglect some part of your code. The programs on break and continue can be performed by the programmer.

4.9 THEswitch case STATEMENT

The switch statement is a multi-way branch statement and an alternative to if-else-if ladder in many situations. This statement requires only one argument, which is then checked with number of case options. The switch statement evaluates the expression and then looks for its value among the case constants. If the value is matched with a case constant then that case constant is executed until a break statement is found or end of switch block is reached. If not then simply default (if present) is executed (if default isn't present then simply control flows out of the switch block). The default is normally present at the bottom of 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 : (colon). The break statement is used to stop the execution of succeeding cases and pass the control to the switch end of block. The syntax of theswitch( ) case statement is shown below. Figure 4.3 simulates the working of switch ( ) case statement.

switch(variable or expression)
  {
  case  constant A :
  statement;
  break;

  case constant B :
  statement;
  break;

  default :
  statement ;
  }

images

Fig. 4.3 The switch case statement

4.10 Write a program to display different lines according to users choice. Use switch( ) case statement.

#include<stdlib.h>
#include<constream.h>
#include<iostream.h>
void  main( )
{
int c;
clrscr( );


cout<<"
 LINE FORMAT MENU ";
cout<<"
1] **********";
cout<<"
2] ==========";
cout<<"
3] ~~~~~~~~~~";
cout<<"
4] _______";
cout<<"
Enter your choice :";


cin>>c;


switch(c)
{
   case 1:
   cout <<"
***************************";
   break;


   case 2:
   cout <<"
===========================";
   break;


   case 3:
   cout <<"
~~~~~~~~~~~~~~~~~~~~~~~~~~~";
   break;


   case 4:
   cout <<"
___________________________";
   break;


  default:
  cout <<"
...........................";
   }
}

OUTPUT
LINE FORMAT MENU
1] **********
2] ==========
3] ~~~~~~~~~~
4] _______
Enter your choice :2
===========================

Explanation: In the above program, a menu is displayed on the screen with different type of lines. The user enters a number as given in the menu. The switch( ) statement checks the value of variable c. All case statements are tested and one that satisfies, is executed. If the user enters a value other than that listed in the menu, default statement is executed.

4.11 Write a program to enter a month number of year 2002 and display the number of days present in that month.

# include <iostream.h>
#include<constream.h>
void main( )
{
clrscr( );


int month,days;
cout<<"Enter a month of year  2002 :";
cin>>month;


switch(month)
{
   case 1:
   case 3:
   case 5:
   case 7:
   case 8:
   case 10:
   case 12:
   days=31;
   break;
   case 2:
   days=28;
   break;
   case 4:
   case 6:
   case 9:
   case 11:
   days=30;
   break;
}
cout<<"
Number of days in this month are "<<days;
}

OUTPUT
Enter a month of year 2002 :3

Number of days in this month are 31

Explanation: The above program is meant to calculate number of days in a month (given by user) of year 2002. We know that month numbers 1, 3, 5, 7, 8, 10 and 12 have 31 days each. So they can be put together in switch( )case. But since there isn't such an option we have used the technique shown above. Similar is the case with month numbers 4, 6, 9 and 11 having 30 days each.

4.10 THE NESTED switch( ) case STATEMENT

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.

4.12 Write a program to demonstrate nested switch( )case statement.

#include<iostream.h>
#include<constream.h>
void  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;
}
}}

OUTPUT

Enter a number :5

The number is odd

Explanation: The above program identifies whether input number was zero, even or odd. The first switch( )case finds out whether the number is zero or non-zero. If a non-zero value is entered, adefault 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 respective messages.

4.11 LOOPS IN C/C++

C/C++ provides loop structures for performing some tasks which are repetitive in nature. The C/C++ language supports three types of loop control structures. Their syntax is described in Table 4.1.

The for loop comprises of three actions. The three actions are placed in the for statement itself. The three actions initialize counter, test condition, and re-evaluation parameters are included in one statement. The expressions are separated by semi-colons (;). This helps the programmer to visualize the parameters easily. The for statement is equivalent to the while and do-while statements. The only difference between for and while is that the latter checks the logical condition and then executes the body of the loop, whereas the for statement test is always performed at the beginning of the loop. The body of the loop may not be executed at all times if the condition fails at the beginning. The do-while loop executes the body of the loop at least once regardless of the logical condition.

Table 4.1 Loops in C++

 

for
while
do-while
for (expression –1;
      expression-2;
      expression-3)
 statement ;
expression –1;
while (expression –2)
{
statement;
expression –3;
}
expression –1;
do
{
statement;
expression-3;
}
while (expression-2);

4.12 THE for LOOP

The for loop allows execution of a set of instructions until a condition is met. Condition may be predefined or open-ended. Although all programming languages provide for loops, still the power and flexibility provided by C/C++ is worth mentioning. The general syntax for the for loop is given below:

Syntax of for loop

 for (initialization; condition; increment/decrement)
 Statement block;

Though many variations of for loop are allowed, the simplest form is shown above.

The initialization is an assignment statement that is used to set the loop control variable(s). The condition is a relational expression that determines the number of the iterations desired or the condition to exit the loop. The increment or the re-evaluation parameter decides how to change the state of the variable(s) (quite often increase or decrease so as to approach the limit). These three sections must be separated by semi-colons. The body of the loop may consist of a block of statements (which have to be enclosed in braces) or a single statement (enclosure within braces is not compulsory but advised).

Following programs illustrate for loop:

4.13 4.14 4.15
# include <iostream.h> 
# include <constream.h>


void main( )
{
clrscr( );
int j;


for (j=1;j<11;j++)
cout<<" "<<j;
}
# include <iostream.h>
# include <constream.h>


void main( )
{
clrscr( );
int j=0;


for (;j<11;j++)
cout<<" "<<j;
}
# include <iostream.h>
# include <constream.h>


void main( )
{
clrscr( );
int j=0;


for (;j<11;)
cout<<" "<<j;
++j;
}
OUTPUT
1 2 3 4 5 6 7 8 9 10
OUTPUT
1 2 3 4 5 6 7 8 9 10
OUTPUT
1 2 3 4 5 6 7 8 9 10
Explanation: In this program initialization, condition, and increment is done in single parenthesis. Explanation: In this program initialization is done before for statement. In for statement only condition and increment is done. Explanation: In this program initialization is done before for statement. Increment is done inside the loop. The for loop contains only condition.

4.16 Write a program to display all leap years from 1900 to 2002.

#include<conio.h>
#include<iostream.h>


void main( )
{
   int i=1900;
   clrscr( );
   cout<<"
Program to print all the leap years from 1900 to 2002


";


for(;i++<=2002;)
{
   if(i%4==0&&i%100!=0)
   cout<<i<<" ";
   else if(i%100==0&&i%400==0)
   cout<<i<<" ";
}
}

Explanation: One must be aware that only those years that are

(a) divisible by 4 and not 100,

(b) divisible by 100 and also 400,

alone are qualified to be called as leap years. The above program checks for these conditions for all years from 1900 to 2002 and then prints the leap years. Stress is on for loop construct and use of if and else-if in the body.

4.13 NESTED for LOOPS

We can also nest for loops to gain more advantage in some situations. The nesting level is not restricted at all. In the body of a for loop, any number of sub for loop(s) may exist.

4.17 Write a program to demonstrate nested for loops.

# include <iostream.h>
# include <constream.h>>
void main( )
{
int a,b,c;
clrscr( );
for (a=1;a<=2;a++) /* outer loop */
{
for (b=1;b<=2;b++) /* middle loop */
{
   for (c=1;c<=2;c++) /* inner loop */
   cout <<"
 a="<<a <<" + b="<<b <<"+ c="<<c <<" :"<<a+b+c;
   cout <<"
 Inner  Loop Over.";
}


cout<<"
 Middle Loop Over.";
}
cout<<"
 Outer  Loop Over.";
}

Explanation: The above program is executed in the sequence shown below. The total number of iterations are equal to 2*2*2=8. The final output provides 8 results. Table 4.2 shows the working of this program.

4.14 THE while LOOP

Another kind of loop structure in C/C++ is the while loop. It's format is given below.

Syntax:

while (test condition)
{
   body of the loop
}

The test condition may be any expression. The loop statements will be executed till the condition is true i.e., the test condition is evaluated and if the condition is true, then the body of the loop is executed. When the condition becomes false the execution will be out of the loop.

The execution of the loop is shown in Figure 4.4.

The block of the loop may contain single statement or a number of statements. The same block can be repeated. The braces are needed only if the body of the loop contains more than one statement. However, it is a good practice to use braces even if the body of the loop contains only one statement.

Table 4.2 Working of program 4.17

images

images

Fig. 4.4 The while loop

4.18 Write a program to add 10 consecutive numbers starting from 1. Use the while loop.

# include <iostream.h>
# include <constream.h>


void main( )
{
   int a=1,sum=0;
   clrscr( );


while(a<=10)
{
   cout <<" "<<a;
   sum=sum+a;
   a++;
}
cout <<"
 Sum of 10 numbers : "<<sum;
}

OUTPUT :
1 2 3 4 5 6 7 8 9 10

Sum of 10 numbers : 55

Explanation: In the above program, integer variable a is initialized to 1 and variable sum to 0. The while loop checks the condition for a<=10. The variable a is added to variable sum and each time a is incremented by 1. In each while loop a is incremented and added to sum. When the value of a reaches to 10, the condition given in while loop becomes false. At last the loop is terminated. The sum of the number is displayed.

4.19 Write a program to calculate the sum of individual digits of an entered number.

# include <iostream.h>
# include <constream.h>
void main( )
{
int num,t;
clrscr( );
cout<<"
 enter a number : ";
cin>>num;
t=num;
int sum=0;
while(num)       //condition is true until num!=0
{
sum=sum+num%10;
num=num/10;
}
cout<<"
 Sum of the individual digits of the number "<<t<<" is =
"<<sum;
}

OUTPUT
Enter a number : 234

Sum of the individual digits of the number 234 is = 9

Explanation: The logic behind the program is to extract each time the LSD(lower significant digit) and divide the number by 10 so as to shift it by one place. To extract the LSD we use the fact that num % 10 = the remainder on dividing num by 10.

4.20 Write a program to check whether the entered number is palindrome or not.

# include <iostream.h>
# include <constream.h>
void  main( )
{
int num;
clrscr( );
cout<<"
 Enter the number : ";
cin>>num;
int b=0,a=num;
while(a)
{
b=b*10+a%10;
a=a/10;
}
if(num==b)
cout<<"
 The given number is palindrome ";
else
cout<<"
 The given number is not palindrome ";
}

OUTPUT

Enter the number: 121

The given number is palindrome

Explanation: Palindrome is a number that is equal to it's reverse, for example, 51715. The program above first simply reverses the number and stores it in b. Then it compares b with original number to tell you whether or not the number is a palindrome. See that in each interaction the LSD of a is being made MSD of b. a is being shifted left and b is shifted right by one digit each in every iteration. Iterations are done until a exhausts or becomes equal to 0.

4.15 THE do-while LOOP

The format of do-while loop in C/C++ is given below.

do
{
statement/s;
}
while (condition);

while (condition); The difference between the while and do-while loop is the place where the condition is to be tested. In the while loop, the condition is tested following the while statement and then the body gets executed. Where as in do-while, the condition is checked at the end of the loop. The do-while loop will execute at least once even if the condition is false initially. The do-while loop executes until the condition becomes false.

4.21 Write a program using do-while loop to print numbers and their cubes up to 10.

# include <iostream.h>
# include <constream.h>
# include <math.h>


void main( )
{
int y,x=1;
clrscr( );


cout <<"
	Numbers and their cubes 
"; 


do
{  y=pow(x,3);
   cout <<"	"<<x<<"		"<<y<<"
";
   x++;
}  while (x<=10);
}

OUTPUT

Numbers and their cubes

   1 1
   2 8
   3 27
   4 64
   5 125
   6 216
   7 343
   8 512
   9 729
 10 1000

Explanation: Here, the mathematical function pow (x,3) is used. Its meaning is to calculate the third power of x. With this function we get the value of y=x3. For use of the pow( ) function we have to include math.h header file.

SUMMARY

(1) This chapter teaches the basics of control structures of C++ language.

(2) The C++ control structure covers two sets of statements. The set that performs certain operations repetitively is called as loop statements and the set that makes decision is known as decision-making statements.

(3) The simple if statement executes statement only if the condition is true, otherwise, it follows the next statement. The else keyword is used when the expression is not true. The else keyword is optional.

(4) C/C++ has four statements that perform an unconditional control transfer. These are return( ), goto, break, and continue. Of these, return( ) is used only in functions. 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. break is used most frequently in switch case.

(5) The for loop comprises of three actions. The three actions are placed in the for statement itself. The three actions initialize counter, test condition, and re-evaluation parameters are included in one statement. The for statement is equivalent to the while and do-while statement. The only difference between for and while is that the latter checks the logical condition and then executes the body of the loop, whereas the for statement test is always performed at the beginning of the loop. The body of the loop may not be executed at all times if the condition.

EXERCISES

[A] Answer the following questions.

(1) Explain the need of control structures in C++.

(2) What are the differences between break and continue statements?

(3) Why goto statement is not commonly used?

(4) Explain the working of if-else statement.

(5) Explain the working of switch( )case statement.

(6) Explain the role of break statement in switch( )case.

(7) What are the differences between while and do-while loop statements?

(8) What is an infinite loop?

(9) Explain nested if's.

(10) Explain nested switch( )case statement.

(11) Explain the use of the keyword default.

[B] Answer the following by selecting the appropriate option.

(1) Which of the following loop statement uses two keywords?

(a) do-while loop

(b) for loop

(c) while loop

(d) none of the above

(2) The statement which requires at least one statement followed by it is

(a) default

(b) continue

(c) break

(d) else

(3) The loop statement terminated by a semi-colon is

(a) do-while loop

(b) for loop

(c) while loop

(d) none of the above

(4) Every expression always returns

(a) 0 or 1

(b) 1 or 2

(c) –1 or 0

(d) none of the above

(5) The meaning of if(1) is

(a) always true

(b) always false

(c) both (a) and (b)

(d) none of the above

(6) The curly braces are not present; the scope of loop statement is

(a) one statement

(b) two statements

(c) four statements

(d) none of the above

(7) In nested loop

(a) the inner most loop is completed first

(b) the outer most loop is completed first

(c) both (a) and (b)

(d) none of the above

[C] Attempt the following programs.

(1) Write a program to display numbers from 10 to 1 using for loop.

(2) Write a program to calculate the factorial of a given number.

(3) Write a program to display only even numbers in between 1 to 150.

(4) Write a program to solve the series x=1/2!+1/4!+1/n!.

(5) Write a program to calculate the sum of numbers between 1 to N numbers. The user enters the value of N.

(6) Write a program to use break and continue statements.

(7) Write a program to display alphabets A to Z using while loop.

(8) Write a program to use break statement and terminate the loop.

(9) Write a program to demonstrate the use of continue statement.

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

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