If you like my posts please leave a comment.

Wednesday, August 1, 2012

Control Statements


Introduction:

Control statements of a programming language govern the flow of program control in a program. Normally a C++ program starts at the top of the list of commands and executes them one after another until the list of commands ends. C++ also provides a list of mechanisms to specify branches, loops and subroutines. All of these features together make the programming language C++ more powerful and efficient enough to process a large amount of information.

Structured Programming:

By structured programming technique we mean that a program development and coding must follow a top-down approach.
            By top-down approach we mean defining a problem from highest conceptual level and works down to the details. This implies, planning the program in a hierarchy of modules. In this approach a program unit is coded only after the unit that calls for it to be performed is already been coded.
            Reverse of top-down approach is bottom – up approach, where defining of problems starts with details and works up to highest conceptual level.
            Keeping the syllabus in mind for now we will just focus on top-down approach of problem solving:
In order to follow top-down problem solving approach, the following structured programming constructs should be well known.

Sequence:

Sequence means to the execution order of program statements.

Selection (branching):

This is also known as branching. This means to execution of a group of statements depending on some specified condition(s). C++ provides following selection or branching constructs:
  • if statement
  • if – else statement
  • else – if statement
  • switch statement

Repetition (loop):

By repetition or looping we mean to repeat the execution of a group of program statements for a finite number of times based on validity of certain specified condition(s). C++ provides following looping constructs:
  • for statement
  • while statement
  • do – while  statement

Jumping:

Jumping control statements are used to skip a set of program statements and jump to a specified part of program. C++ provides the following jumping statements:
  • break statement
  • continue statement
  • goto statement
  • return statemen

Sequence:

As it is said earlier that sequence means to the execution order of program statements. If there is no control structure applied for intervening normal flow of program control, then program control normally passes from one instruction to next. The sequence structure is built in C++. Unless it is directed computer executes C++ statements one after another, in the order they are written.
Following figure illustrates a normal sequence structure.

Flowchart 1: Illustrates default program statement execution sequence.
     

In the above flowchart rectangle boxes are used. These boxes are known as Process box. Lines used here to join this boxes is known as flow lines. It shows the flow of program control.

Selection:

Selection means to make a decision. While writing a solution to a problem we may come across a situation where we may need to choose from one or more options based on some decisions; as an outcome of   evaluating one or certain number of conditions together. This can be illustrated with the help of the flow chart given below:
Flowchart 2: Single-selection
 
In the above flowchart a diamond symbol is used. It is known as decision box. Expression written inside this box evaluates to True or Flase. The decision box has two flow lines emerging out of it. One indicates the decision to be takes if the condition (expression) evaluates to true (evaluates to 1) and the other one indicates decision to be taken when the condition evaluates to False (evaluates to 0). Apart from the used symbols other symbols used to draw a flow chart are ovals and small circles. Flow chart is a graphical way of representing Algorithm to a solution of a problem.

            In C++ if statement used to implement a single – selection structure. The if selection structure either selects an action if the condition evaluates to true or skips the action if the condition evaluates to false.
Now let’s have a look over double – selection (multiple - selection). 
Flowchart 3: Multiple –selection / Double – selection
 
As you can see in the above flowchart that if Marks obtained by a student is > = 50 then program will print “PASS” otherwise will print “FAIL”. So, in this type of structure either one of the specified actions to be taken on the basis of the evaluating the specified condition. In C++ we use if – else structure to implement Multiple – selection

Repetition (loop):

If one more statement executes more than once for the time being the specified condition specified evaluates to True is known as loop. Flow chart shown below illustrates this concept more:
Flowchart 4: Repetition (loop) structure 
 
 
As you can see in the above flowchart that as long as value of SUM remains < = 10 every time previous value of SUM will be added with 2. This is an example of Finite Loop, where program statements are repeatedly executed for a finite number of times. There can be a situation where a condition may remain always True, then program statements inside the loop body will be executed for ever. This is called Infinite Loop. In C++ use the while, do – while and for statements to create a loop. 
Let’s see C++ program code example implementing an infinite loop.

while(1)
{
cout<<”\n I am in an infinite loop construct”;
}
In the above code the while statement always will evaluate to TRUE, so the line ‘cout’ will be always executed.

Caution** Implementing an infinite loop construct in your program can be very dangerous. In practice we never implement a truly infinite loop in a program. A loop always must have an exit condition.

Selection (Using if statement):

In C++ if statement helps in decision making; depending on the outcomes from the evaluation of specified expression(s). It allows conditional execution of the program statement(s). In other words, program statements specified will be executed if the condition specified evaluates to non-zero. In C++ if statement takes the following formats:
if ( <condition>)
{
 Block of C++ program statements to execute
}
OR
if ( <condition>)

 A single C++ statement to execute

Note**
1.      in C++ If construct does not need a pair of curly braces if it is followed by a single line of program statement.
2.      Do not put semicolon after the parenthesis of the relational test condition

Example:
//Program demonstrating the use of if
#include<iostream.h>
int main()
{
int a, marks;
cout<<”\n Enter a number: ”;
cin>>a;
cout<<”\n Enter Marks: “;
cin>>marks;

if (a  = = 0)
cout<<”\n It is Zero”;
if (a > 0)
cout<<”\n It is a positive number”;
if(a < 0)
cout<<”\n It is a negative number”;
if (marks > = 50)
{
cout<<”\n You have PASSED”; /*Here if block is having multiple
Statements to execute */
grade = ‘A’;
}
return 0;
}

else Statement:

The else statement can appear with a if statement. if – else statement is used together to implement multiple or double selection. In C++ if – else construct takes the following formats:

if (<condition)
{
Program statements to execute
}
else
{
Another set of program statements to execute
}
OR
if (<condition)
Single Program statement to execute

else
Another single program statement to execute

If the condition specified is true then entire block or single statement that follows will execute. If the condition goes False, then the entire block or single statement that follows else will be executed.
Example:
//Program demonstrating the use of if-else
#include<iostream.h>
void main()
{
int number;
cout<<”\n Enter a number: “;
cin>>number;
     if(number = = 0)
     cout<<”\n You have entered a ZERO”;
     else
     cout<<”\n You have entered a NON-ZERO number”;
return;
}

Nested if:

Nested if statements is required to implement when we required to evaluate the inner if statement only if the outer if statement evaluates to true.
Example:
//Program demonstrating the use of nested if
#include<iostream.h>
void main()
{
float theory_marks, practical;
char grade;
cout<<"\n Enter theory marks: ";
cin>>theory_marks;
cout<<"\n Enter practical marks: ";
cin>>practical;

if(theory_marks >= 50)
{
     if(practical >= 20)
     {
     grade = 'A';
     cout<<"\n Your Grade = "<<grade;
     }
}
return;
}
In the above case if the theory_marks is entered as 50 or more also if practical is entered as 20 or more then variable grade will be assigned with ‘A’. Thus you will have the output as Your Grade = A. So in this we are implementing logical AND (&&) operation. Another version of the program is given below:

//Program demonstrating the use &&
#include<iostream.h>
void main()
{
float theory_marks, practical;
char grade;
cout<<"\n Enter theory marks: ";
cin>>theory_marks;
cout<<"\n Enter practical marks: ";
cin>>practical;

if(theory_marks >= 50 && practical >= 20)
{
     grade = 'A';
     cout<<"\n Your Grade = "<<grade;

}

return;
}

Nested if – else:

Nested if – else structure tests for multiple conditions by placing if-else structure inside another if-else structure.
Example:

//Program demonstrating the use of nested if - else

#include<iostream.h>

#include<conio.h>

void main()

{

clrscr();

float theory_marks, practical;

char grade;

cout<<"\n Enter theory marks: ";

cin>>theory_marks;

cout<<"\n Enter practical marks: ";

cin>>practical;

 

if(theory_marks >= 50)

{

     if(practical >= 20)

     {

     grade = 'A';

     cout<<"\n PASS!!!, Your Grade = "<<grade;

     }

     else

cout<<"\n Your result is pending. Failed in Practical Examination: ";

}

else

{

     if(theory_marks<50)

 

     if(practical >= 20)

cout<<"\n Your result is pending. Failed in Theory Examination ";

     else

     cout<<"\n FAILED!";

}

getch();

return;

}

Dangling else:

While implementing nested if – else structure, one may come across a situation where we will find that number of if statements you have written is more that number of corresponding else clauses. Thus you may have one or more proceeding unmatched else statements. This situation is known as dangling else.
Example:
// code fragment taken from the previous program:
if(theory_marks<50)
     if(practical >= 20)
     cout<<"\n Your result is pending. Failed in Theory Examination ";
     else
     cout<<"\n FAILED!";

In this above code two ifs statements are present and only one else statement. Now confusion may arise that - With which if does the additional else statement should match up? So, answer is – an else clause in C++ is matched up with preceding unmatched if. So, in this occasion if (practical >=20) evaluates to False then else clause will be matched up ant thus you will have the output as FAILED!
So, for now it is been very clear that, in the above code there is no corresponding else clause for the line if(theory_marks<50). What happens if this if condition evaluates to False? So, here the answer to the question is that in C++ in the case of nested if-else structure, each and every if condition need not to have corresponding else clause.
            Now the question arises that, is it is source of potential ambiguity. The answer is ‘YES’ if it is not handled with care. You may have logical error in your program more over it can not be traced by the compiler. Because as I said earlier that, as per the syntax of if – else in C++ each if statement may or may not have corresponding else  statement.  
            Now lets examine my previous program with nested if – else to see if there is logical error because of dangling else?

In this program the logic I want to implement is –
  • if a student’s theory marks is 50 or more and practical marks is 20 or more then
he will be said as PASS and grade will be given as A
  • if student’s theory marks is 50 or more but practical marks is less than 20 then
print the message  “Your result is pending. Failed in Practical Examination:”
  • if student’s theory marks is less than 50 but practical marks is 20 or more then
print the message – “Your result is pending. Failed in Theory Examination
  • else if theory marks < 50 and also practical marks <20 then
print the message – “FAILED”

Let’s check out whether the program is working as per my expectation or not.
  • if a student’s theory marks is 50 or more and practical marks is 20 or more then
he will be said as PASS and grade will be given as A
First Run:
 
  • if student’s theory marks is 50 or more but practical marks is less than 20 then
print the message  “Your result is pending. Failed in Practical Examination:”
Second Run:
 
  • if student’s theory marks is less than 50 but practical marks is 20 or more then
print the message – “Your result is pending. Failed in Theory Examination
Third Run:
 
  • else if theory marks < 50 and also practical marks <20 then
print the message – “FAILED”
Fourth Run:
 
So, it is proved that my program is working as I want. Here Dangling else is not providing any ambiguous result. 
Conclusion: So, finally I would like to say -  if you are aware of what you are doing then you need not to get scared of dangling else, it is not going to be dangerous.

If – else – if Ladder:

Sometimes the conditions of the problem may increase its levels. In the same way the structure of if-else extends its level higher into higher. That is the structure becomes if – else – if ladder. Actually when else part of a if condition used to have another if condition and when this situation continues to several levels down the structure thus it forms if – else – if , which is also known as if-else-if ladder and this ladder ends with an else statement.

if ( condition1)
Statement1;
else
     if(condition2)
Statement2;
     else
          if(condition3)
          Statement3
          else
              if(condition4)
              {
              ………………
              ……………….
              }
              else
                   :
                   :
                   :
                   StatementN;
Example:
//Program demonstrating the use of if-else-if ladder
#include<iostream.h>
#include<conio.h> 
void main()
{
clrscr();
int hardness,tensil,grade;
float carbon=0.0;
hardness=tensil=0;
cout<<"\n Enter for carbon quantity";
cin>>carbon;
cout<<"\n Enter for hardness quantity";
cin>>hardness;
cout<<"\n Enter for tensil quantity";
cin>>tensil;
if((hardness>=50) && (carbon<=0.7) && (tensil>5600))
grade=10;
else
if((hardness>=50) && (carbon<=0.7) && (tensil==0))
grade=9;
else
if((carbon<=0.7) && (tensil>=5600) && (hardness==0))
grade=8;
else
if((hardness>=50) && (tensil>=5600) && (carbon==0))
grade=7;
else
grade=6;
cout<<"\n Grade="<<grade;
getch();
}

Selection using switch – case statement:

switchcase statement can be considered as  a very handy replacement of if – else – if. This statement is very clear, easy to understand and very flexible to implement. Let’s see the format of switch – case statement.

switch (expression)
{
case (expression1):
statement1;
break;
case (expression2):
statement2;
break;
:
:
:
default:
statement_deault;
}

The expression with switch can be int or char variable, constant, relational expression, logical expression or both. However expression with case must be a constant only. default line is optional. If none of the case expression matches that of the switch expression then the default case is executed. break statement is used after each case block to take the program control out of the switch – case  construct, after when a particular case block is executed. If you forget to use break statement after each and every case block you may get logical error. break statement is not required to use after default statement.
Now let’s have some C++ program examples to understand the use of switch – case construct.

//program using int variable as switch expression
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num;
cout<<"\nEnter a number: ";
cin>>num;
switch(num)
{
     case -1:
     cout<<"\n Negative number is entered: ";
     break;
     case 1:
     cout<<"\n Positive number is entered:";
     break;
     default:
     cout<<"\n 0 or Unknown";
}
getch();
}

Output:
If -1 is entered we will get output as
Negative number is entered:
If 1 is entered you will have output as
Positive number is entered:
If any number other then these is entered then you will have output as
0 or Unknown.

/*Program demonstrating the use of relational expression in switch statement also introducing the concept of nested switch construct.*/
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num;
cout<<"\nEnter a number: ";
cin>>num;
switch(num >= 0)//Nesting switch
{
     case 1:
     switch(num == 0) //Nested switch
     {
     case 1:
     cout<<"\n Zero is entered:";
     break;
     case 0:
     cout<<"\n Positive number is entered:";
     }
     break;
     case 0:
     cout<<"\n Negative number is entered:";
}
getch();
}
Working of the program:
If a number greater than or equal to 0 (>=0)is entered then the nesting switch statement evaluates to true (1) and then case 1: statement block executes which in turn leads to evaluation of nested switch expression. Now if the number was 0 then expression will evaluate to True (1) and you will have the output as - Zero is entered: otherwise statement evaluates to false (0) then case 0: statement will execute and you will have the output as - Positive number is entered:
            Now consider the second case  - where number entered is less then 0 then nesting switch expression will evaluate to False (0)and so case 0 statement block will execute and you will have the output as - Negative number is entered

/*Program demonstrating the use of logical expression in switch statement also implementing the concept of nested switch construct.*/

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a,b,c;
cout<<"\nEnter three number: ";
cin>>a>>b>>c;
switch(a >b && a>c)//Nesting switch
{
     case 1:
     cout<<"\n Greatest = "<<a;
     break;
     case 0:
          switch(b>c) //Nested switch
          {
          case 1:
              cout<<"\n Greatest = "<<b;
              break;
          case 0:
              cout<<"\n Greatest = "<<c;
          }
}
getch();
}
Output:
If you enter three numbers as –
5
10
7
You will have output as – Greatest = 10

Note** carefully follow the program and see how switch - case can be used as an alternative to if – else construct.

Nested switch – case statement:

Thus in above examples we have seen that, when a switch statement is used within another switch statement then it is said as nested switch – case statement. Nested switch – case statements can be used as an alternative to nested if – else statements.  So, the structure of nested switch is as follows:

switch (expression1)
{
     case 1:
              switch (expression2)
              {
                   Case 0:
                        ……………….
                        ………………..
                   break;
                   case 1:
                        ………………….
                        ………………..
              }
     break;
     case 2:
              ………………….
              ………………….
     Break;
     default:
              ……………………
              …………………..
}

If - else Vs switch – case:

So, on the basis of above discussion so far we have done, we are now in position to trace some important differences between if – else and switch – case.
  • In case of switch – case evaluated value of the expression with switch should match with either one of the constants mentioned with the related case statement.
Where as in case of if – else, expression with if evaluates and then either statement block following if or statement block following corresponding else executes.
  • if statement encloses multiple statements with in a pair of curly braces. Thus a pair of curly brace signifies and separates a block of statements form other.
Where as switch – case never uses a pair of curly braces to enclose multiple program statements to execute under a case statement. Each group of program statements to execute under a case statement is separated by using break. However switch uses a pair of curly braces to enclose all its related case statements as a single unit.
  • break statement is used with switch – case but not with if – else.
  • If – else statement can handle floating point numbers but switch can not.

What happens if switch – case does not use ‘break’?

Let’s find the answer to this question by comparing the working of two simple programs:
 
Program 1:

Program 2:
 
Note** in the above two programs coloured lines used for demonstrating the flow of controls in the program.

Output of the first program:     Output of the second program:

So, after following the flow of program control in above two programs and by comparing the two program outputs we can say that, in a switch-case construct break is used to take the control immediately out of the switch construct after the first match with the case constant is found. Otherwise from the point (case constant) it has found the match, program control will flow downwards and all the further case clauses will be executed.

//A simple calculator program using switch – case:
#include<iostream.h>
int main()
{
int a, b,ans = 0;
char op;
cout<<"\n Enter 1st number, operator, 2nd number\n";
cin>>a>>op>>b; //follow here how cascading of input operator is done
     switch(op)
     {
          case '+':
              ans = a+b;
              break;
          case '-':
              ans = a-b;
              break;
          case '*':
              ans = a*b;
              break;
          case '/':
              if(b == 0)
              {
              cout<<"\n Cannot divide by Zero: ";
              ans = NULL;
              break;
              }
              else
              ans = a/b;
              break;
          default:
          cout<<"\n Sorry!! Unknown operator";
     }
if(ans!=NULL)
cout<<a<<' '<<op<<' '<<b<<" = "<<ans;
return 0;
}
Output:
 
Some important points about switch – case
  1. The switch – case construct is efficient only in the situation that supports the nature of switch operation.
  2. No, to case labels within the same switch - case construct can have the same constant values. But in the case of nested switch – case the case constant of the inner switch and the outer switch can be same.
  3. Character constants used in the switch statement is automatically converted to their equivalent integer value (ASCII code)
Example: 

#include<iostream.h>

void main()
{
char ch;
ch = 'A';
  switch(ch)
  {
       case 65:
       cout<<"\n I am in case 65";
       break;
  }
}
Output:
I am in case 65

Iteration / Loop / Looping Statements:

When a set of instruction is allowed to perform repeatedly for a finite number of times is called looping or loop. In a programming language iteration or looping statements allow to repeat one or more programming instructions to repeatedly execute until a certain condition remains true. The condition that we specify to control the looping process is also known as loop control.
           
A loop can be infinite, empty. A loop is said to be infinite if it goes on iterating for ever. In other words a loop is provided with such a condition that never turns to False then it will always continue or if you forget to write the update expression or if you do not write test expression (only allowed in for loop). 

The loop construct with no statement in its body other than just a semicolon (;) (Null statement) is known as empty loop. 

            In C++ we have three different kinds of looping statements: for loop, while loop, do–while loop.
Let’s see a list of common parts of looping statements that controls a loop before we move further.

Parts of a loop:

Whatever the looping statement you are using they all have 4 common parts. However, there location in the statement varies.
  1. Initialization of Expression(s):
The expression(s) used to assign an initial value to the loop variable(s) used by the looping statement. The initialization expression is executed for once only in the beginning of the loop.
  1. Test Expression
The text expression controls the loop. Till the test expression evaluates to true loop-body executes. Otherwise loop exits.
  1. Update Expression
The update expression changes the value of the loop variable(s), in increasing or decreasing order.
  1. The Loop-Body
The statements that are required to be executed repeatedly as long as the test expression remains true, is called loop-body.

Classification of Loops:

On the basis of the execution style, looping statements can be classified in to categories:

Entry-Controlled Loop:

In an entry-controlled loop the test expression is executed first before entering into a loop. Means if the text expression evaluates to true then only the program control enters the loop body otherwise it skips. The looping statements come in this category are: for and while

Exit-Controlled Loop:

In an exit-controlled loop the test expression is executed before exiting form the loop. Means even if the condition is false program control will enter the loop body at least for once. The looping statement in this category is: do-while

Loop Construct Comparison:

Each of these above mentioned looping statements have their own format to implement. However, all the four parts of the loop remains same and they are in use. Let’s compare them:

General structure of structure of for loop:
for (<initialization-expression>;<test-condition>;<update-expression>)
{
:
:
<loop-body>

:
}

Empty for loop:
for (<initialization-expression>;<test-condition>;<update-expression>)
{

  ; //null statement

}
OR
for (<initialization-expression>;<test-condition>;<update-expression>);
Example:
for(int I = 0;I < 10;I++)
{

; //null statement
}

Infinite for loop:
for (<initialization-expression>;<test-condition>; )//Here update-expression is missing
{

<loop-body>
}
OR
for (<initialization-expression>; ;<update-expression> )//Here test-expression is missing
{

<loop-body>
}

Example:
for(int I = 0; I<10; ) //Here variable I will always remain <10
{
cout<<"\n I am in infinite loop";

}


OR

for(int i=1; ;i++)//Here the test-expression is missing
{
cout<<"\n I am in infinite loop";
}
General structure of while loop:
<initialization-expression>;
while (<test-expression>)
{
:
<loop-body>
:
<update-expression>
}

Empty while loop:
<initialization-expression>
While (<test-expression>)
{

;   //null statement

}
                                               
Example:
int I = 1;
while(++1 < 100)
{

; //null statement

}

Infinite while loop:
Example:
while (1)            // This condition always remains true
{
cout<<"\n I am in infinite loop";

}

OR

<initialization-expression>
while(<test-expression>)
{

            //update-expression is missing                        
}

Example:
int I  = 1;
while(I <= 10) //Here value of I will always remain <=10. As value of I is never been updated
{

Cout<<”\n I am in an infinite loop”;

}

General structure of do-while loop:
<initialization-expression>;
do
{
:
<loop-body>
:
<update-expression>;
}while(<test-expression>);

Empty do-while loop:
do
{

;  // null statement
           
}while(<test-expression>);

Example:
do{
    
; //null statement

}while(++i<1000);

Infinite do-while loop:
Example:
do{
cout<<”\n I am in infinite loop”;
}while(1); //Here 1 stands for always true
OR
do{

            //update-expression is missing
}while(<test-expression);
Example:

do{

Cout<<”\n I am in infinite loop”;
}while(i<=10);

Now let’s have detailed discussion on each of these looping statements:

for Loop:

Before a for loop begins, C++ starts evaluating the initialization-expression, validates with test-expression, enters the loop body and before exiting the loop executes the update-expression. In a for loop initialization expression, test expression and update expression are optional. You can skip any one or all of these expressions, but remember even if you skip one or all expressions semicolons (;) must remain present. In case of for loop, prefer prefix increment over post fix increment in order to increase the value of loop variable by 1. Because, when a prefix operator is used alone they execute faster then post fix operator.
Example 1:
//Sample program using for loop
#include<iostream.h>
int main()
{
int i;
int ctr = 2;
     for(i = 0; i<10;++i)
     {
      cout<<ctr<<' ';
      ctr +=2;
     }
return 0;
}
Output:
2 4 6 8 10 12 14 16 18 20

Example 2:
#include<iostream.h>
int main()
{
int i = 0;
int ctr = 2;
     for( ; i<10;)
     {
      cout<<ctr<<' ';
      ctr +=2;
      ++i;
     }
return 0;
}
Output:
2 4 6 8 10 12 14 16 18 20

Now let’s see a second version of the same program:
//Sample program using for loop
#include<iostream.h>
int main()
{
int i;
int ctr;
         //region for initialization-expression          test-expression     update-expression
     for(i = 0,ctr = 2; i<10; ++i,ctr += 2)
     {
      cout<<ctr<<' ';

     }
return 0;
}
Output:
2 4 6 8 10 12 14 16 18 20
It is very clear from the second version of the program that, two semicolons creates three different regions in the ‘for’ statement.
for(<region for initialization-expression>; <region for test condition>; <region for update-expression>)
In these regions, more than one expressions of same type can be written separated by a comma (,) operator.

Terminating for Loop:

If a ‘for’ is terminated by using a semicolon (;) means, if you use a semicolon after the right parenthesis of ‘for’ loop then it is a “terminating-for-loop”. A terminating-for-loop continues looping each time without executing the loop body, until the test expression becomes false. In some occasions this terminating-for-loop is useful. It is advisable not use a terminating-for loop at this stage.

Declaring variables in ‘for’ loop:

In C++ ‘for’ loop supports declaration of variables.
Example:
//Sample program demonstrating the declaration of variables in for loop
#include<iostream.h>
int main()
{

     for(int i = 0,ctr = 2; i<10; i++,ctr +=2)
     {
      cout<<ctr<<' ';
     }
return 0;
}
Note: In the above sample program variable i and ctr are declared as of type int and initialized at the same time.

The while Loop:

The next looping statement present in C++ is while loop. while loop is known as entry-controlled loop.
 Like for loop, while loop can also contain single statement, compound statement or empty statement as its loop-body. The loop body iterates as long as condition expression evaluates to true. Otherwise the program control passes to the line next to the loop-body. In case of while loop, the loop variables are required to be declared and initialized prior to use. Loop variables are updated inside the loop-body. The program given below is illustrating the use of while loop.
Example:
//Program to illustrate the use of while loop
#include<iostream.h>
#include<dos.h>
int main()
{
int num,i=1;
cout<<"\n Enter a number:";
cin>>num;
     while(i<=10)
     {
     cout<<num<<" X "<<i<<" = "<<num*i<<endl;
     i = i+1;
     }
delay(2000);
return 0;
}

The do-while Loop:

As it is said earlier that do-while loop is an exit-controlled loop. It evaluates the test-expression at the bottom of the loop after executing the loop body. So, in the situations where it is required to execute the loop-body at least for once even if the test expression goes False from the very beginning.
     This loop construct is very commonly used in menu selection routine.

Concept of Nested Loop:

If a loop-body contains another loop in it, then this form of a loop is known as Nested Loop. In a nested loop both inner loop and the outer loop may be composed of same or different form of loop construct. But inner loop must terminate before the outer loop.
            It is also required to understand that – for a single value of outer loop variable the inner loop completely finishes or interrupted. In other words the value of outer loop variable will change only after the inner loop is completely finished or interrupted.   

Example 1:
/*code fragment showing you the use of loop construct of same type (for loop) in a nested loop*/
for(int i = 1;i<=5;++i)//Outer loop
{
     for(int j=1;j<=i;++j)//inner loop
     cout<< "*";
cout<<endl;
}

Example 2:
/* code fragment showing you the use of loop construct of different forms (for and while)in a nested loop*/
for(int i = 1;i<=5;++i)//Outer loop
{    int j=1;
     while(j<=i)   //inner loop
     {
          cout<<”*";
          j++;
     }
cout<<endl;
}

Working of Nested Loop:

To understand how a nested loop works. Let’s take an example:
for(i = 1;i<=5;++i)//Outer loop
{
     for(int j=1;j<=i;++j)//inner loop
     cout<<j<<' ';
cout<<endl;
}
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Now see the explanation below:
For each value of i in outer for loop              value of j in inner for loop changes to
 

Jump Statements:

The jump statements in C++ allow unconditional transfer of program control to the specific part of the same program. As it is said earlier in C++ we have four different statements that perform an unconditional jump (branching): break, continue, goto and return

break Statement:

A break statement can be used with for, while, do-while and switch-case. As soon as the break statement is executed program control jumps out of the loop body in which it is present and execution resumes at the statement immediately following the body of the terminated loop. If break statement appears in a nested loop structure, then it causes an exit from only the very loop it appears in (inner loop). A break statement used in switch effects the switch statement only. Because of break statement program control jumps out of the very switch it appears in. It does not affect the loop if switch happens to be in.
Below see the diagrammatic explanations for working of break statement.
//Explanation for working of break statement in a loop construct.
 
//Explanation for working of break statement in a nested loop construct.
 

continue Statement:

In C++ continue is also a break statement. It also let the program control to skip over a part of the program code. But unlike break statement continue statement instead of termination, it forces next iteration of the loop, skipping any code in between. Figure below explains this further.
 
Please follow the flow of program control
Output:
Enter a character A – Z A
Enter a character A – Z B
Enter a character A – Z C
Enter a character A – Z Z
Enter a character A – Z a

For 4 No. of times correct keys are pressed

goto statement:

A goto statement can transfer the program control to any part of the same program in other words it leads to the absolute jump of the program control. The part of the program where the control is to be transferred should be marked by a label (a valid identifier) and that label should appear with goto statement.
Syntax:
goto label_1;
:
:
:
Label_1:

Before you can start using goto statement you should be aware of the fact that, goto statement can not jump forward over a variable definition, however it is possible if the variable(s) is defined in a block. In that case it can jump over the entire block.

Example:
//Sample program demonstrating the use of goto statement
#include<iostream.h>
void main()
{
int ctr=0;
     char ch;
     while(1)
     {

     cout<<"\n Enter a character A - Z";
     cin>>ch;
     if(ch>90)
     goto LABEL;//Instruct to go to the program part named as LABEL
     else
     {
     ctr++;
     cout<<"\n Enter correct caracter for "<<ctr<<" time(s)";
     continue;
     }
     }
LABEL: //Rest of the part of program is labeled as LABEL
//int a = 10; this is wrong
{int a = 10;}//This is correct way
}

return statement:

The return statement is used to return the program control from a function. This statement will be discussed further in chapter ‘Functions’.

exit( ) Function:

exit function is used to break out of the a program no matter where it is present. It is a library function so to use this function you need to include “stdlib.h” or “process.h” header file. In C++ exit( ) function must return an integer value. If a value other then of integer type is provided it converts it to its corresponding integer type and is returned to the operating system. This returned value can be tested in batch files.
Example:
//Sample code illustrating the working of exit()
void main()
{
int ch;
cout<<”\n Enter a number: “;
cin>>ch;
     if(ch == 0)
     exit(0);
     else
     {
     :
     :
     }
}

Caution**
Don’t let the program control to jump unconditionally other wise you may have logical error. Always put the JUMP STATEMENT(S) inside some SELECTION STATEMENT(S) (if or if-else, switch-case). Then program control will conditionally jump out of the normal sequence of program statement execution.

No comments:

Post a Comment