Wednesday, December 26, 2012

Control Structures in C++

We have gone through some of the C++ programs with example code in the couple of posts before. Actually speaking, we cannot even think of programming without knowing about control structures because a program is usually not limited to a linear sequence of instructions. During its process it may split in to two parts, repeat code or take decisions. 

It's just as simple as living life. Do you think life keeps on flowing without a need to make decisions, repeat things /activities, continuing doing something or going back with memory and doing something depending on a decision we make. These are what a program definitely does to achieve some task.

For these purpose, C++ provides control structures that serve to specify what has to be done by our program, when and under which circumstances.

With the introduction of control structures, we have to know about some new concepts. The compound statements or block. 

A block is a group of statements which are seperated by semicolons (;) like all C++ statements, but grouped together in a block enclosed in curly braces {};

e.g :- 
{
    int a;
    int b;

    return a+b;
}

most of the control structures that we will see in this post require a generic statement as part of its syntax. A statement can be either a simple statement ( a simple instruction ending with a semicolon) or a compound statement ( several instructions grouped in a block) , like the one just described. In the case that we want the statement to be a simple statement, we do not need to enclose it in braces {}. But in the case that we want the statement to be a compound statement it must be enclosed between curly braces {}. forming a block.

A list of Conditional structures in C++

  • if and else
  • Iteration structures (loops) - while, for, do-while
  • Jump statements -break, continue, goto, exit,
  • Selective structure -switch
I'll explain these conditional statements one by one with necessary code snippets. In future posts, I can explain you some meaningful programs to show the actual use of these.

if and else

if (condition)
{
   // your statement goes here
}

Where condition is the expression that is being evaluated. If this condition is true, statement is  executed. If it is false, statement is ignored and the program continues right after this conditional structure. See the below code block for clarification.

if ( marks > 100)
{
  cout<< "Invalid mark entered, please try again";
}

marks =(marks/100) *10;
cout<<"You have scored "<<marks <<" out of ten";

note that, since the above code snippet, we have only one line of code to be executed if the condition is true, so you can even forget about the curly braces that I have explicitly mentioned above to show the code block clearly. even you had the curly braces after any conditional structure, the first line of code (statement) will definitely be executed. But this will not happen if you have more than one statement to be executed after any conditional statement. See the below code.

  1. if ( marks > 100)
  2.   cout<< "Invalid mark entered";
  3.   cout<< "Please reenter the mark again";
  4. marks =(marks/100) *10;
  5. cout<<"You have scored "<<marks <<" out of ten";

in the above code, if the condition is true, only the first message will be printed on terminal but line number 3 will simply be ignored as a line to be executed if the condition is true since we have not told the program to execute both line-2 and line-3 if the condition is true. to do so, simply wrap the statements using curly braces.

if ( marks > 100)
{
  cout<< "Invalid mark entered";
  cout<< "Please reenter the mark again";
}

Now, think what if we need to do something if the condition is true we have to do something and meanwhile we have to do something else if it is false. we have two options. One is to use an if condition and mention all the statements in one block if the condition is true. Same as that, put all the rest of the code (code to be executed if the condition is false) outside the conditional code block. 

if ( marks > 100)
{
  cout<< "Invalid mark entered";
  cout<< "Please reenter the mark again";
}

marks =(marks/100) *10;
cout<<"You have scored "<<marks <<" out of ten";


But, what if you have to check the mark's validity from the if condition and then decide the scored grade of the mark to display. Your option are,

use another if condition

if ( marks > 100)
{
  cout<< "Invalid mark entered";
  cout<< "Please reenter the mark again";
}

if ( marks > 85 )
{
  cout<< "Grade A";
}

marks =(marks/100) *10;
cout<<"You have scored "<<marks <<" out of ten";

you may note some logical issues in the above code like even though the mark is invalid, the program will output the mark out of ten but for the moment ignore it because I'm just focusing on the way the code blocks work there.

use else if condition

if ( marks > 100)
{
  cout<< "Invalid mark entered";
  cout<< "Please reenter the mark again";
}

else if( marks > 85 )
{
  cout<< "Grade A";
}
  marks =(marks/100) *10;
  cout<<"You have scored "<<marks <<" out of ten";

 the if else  structures can be concatenated with the intention of verifying a range of values. The following example shows its use of telling if the value is in a range, how to make decisions and make proper output.

if ( marks > 100)
{
  cout<< "Invalid mark entered";
  cout<< "Please reenter the mark again";
}

else 
{
  if(marks > 85)
 {
   cout<< "Grade A";
 }

  if(marks > 65 && marks <= 85 )
 {
   cout<< "Grade B";
 }

  if(marks > 45 && marks <= 65 )
 {
   cout<< "Grade C";
 }

 else
 {
   cout<< "Fail";
 }
  marks =(marks/100) *10;
  cout<<"You have scored "<<marks <<" out of ten";
}

So, I think the if-else concept is clear for you now. Now, let's move to the next control structure.

Iteration structures (loops)

while loop

The format of writing a while loop is,

while(expression)
{
 statement

While loop's  functionality is simply to repeat statement while the condition set in expression is true. For an example, we are going to make a program to count numbers from one to 100. 

OK, my first option is having  variable called sum and assigning 1+2+3+4+...+100 to sum and then print the value.

And my second option is to have a variable, assign 1 to it and have a while loop to increase its value one by one meanwhile adding it to sum to get the output (sum of 1 to 100)

So, what will you prefer? I'm sure that you won't go to the first option because you wont type from 1 to hundred in the source code if you have a simpler option by using a loop. see the code below.

int number,sum;
number=1;
sum=0;


while(number<=100)

{
  sum=sum+number;
  number++;
}

cout<<"The count of 1 to 100 is "<<sum<<endl;

whatever the code written inside the while block will be executed repeatedly until the condition of while becomes false. once it becomes false, the while loop will no longer be executed.

do-while loop

do  
{
  statement
}
while (condition)

above is the format of a do-while loop. It simply says to do something until some condition is true. Its functionality is exactly the same as the while loop, except that condition in the do-while loop is evaluated after the execution of statement instead of before, granting at least one execution of statement even if condition is never fulfilled. For example, examine the following code.

int number,sum;
number=1;
sum=0;


do

{
  sum=sum+number;
  number++;
}
 while(number<=100);

cout<<"The count of 1 to 100 is "<<sum<<endl;

Both the above shown example for while loop and do-while loop work same. In do while loops, first it executes the statements in the block and then checks for the condition but in while loops, first the condition is being checked before executing the code block.


The major difference between while loop and do while loop is while loop executes 0 to more times but do-while loop executes 1 to more times. even though the condition is false, in do-while the block executes at least once because it says "first do and then check!"


for loop


The format of writing a for loop is ,


for(initialization ; condition ; increase or decrease)
{
  statement;
}

the main function of a for loop is to repeat statement while condition remains true, like the while loop. But in addition, the for loop provides specific locations to contain an initialization statement and an increase/ decrease statement. So this loop is specially designed to perform a repetitive action with a counter which is initialized on each iteration.

you may see its format bit new since its different than while and do-while. Following step will show you how it really works.

  1. initialization is executed. Mostly it is an initial value assigned to a counter variable and this is executed only once.
  2. condition is checked. If it is true, then loop continues ( statement will be executed) else, the loop ends and statement is skipped.
  3. statement  is executed. As you already know, it can be a single statement ( if so, you don't need the curly braces to mark the block) or a block of statements (you must use the curly braces).
  4. Finally, whatever is specified in the increase/decrease field is executed and the loop gets back to step 2.
I'll show you how the above shown example of while and do-while could be achieved via the for loop.

int number,sum;
sum=0;


for(int number=1 ; number <=100 ; number ++)

{
  sum=sum+number;
}

cout<<"The count of 1 to 100 is "<<sum<<endl;


Also note that the initialization and increase fields are optional. They can remain empty, but in all cases the semicolon signs between them must be written . Observe the below shown lines


int number=1;

for( ; number <=100 ; number ++)

Above line is just as same as shown in the example above if you are using a variable in the for loop is already declared and initialized. you can also write as below


int number=1;

for( ; number <=100 ; )

{

  sum=sum+number;
  number++;

}

Optionally, using the comma operator (,) we can specify more than one expression in any of the fields included in a for loop , like in initialization, for example. The comma operator (,) is an expression separator, it serves to separate more than one expression where only one is generally expected. Examine the below shown code where we wanted to initialize more than one variable in our loop.

for( n=0 , i=100 ; n!=i ; n++ , i--)
{
   //statments
}

Jump statements 

The break statement

Using break statement we can leave a loop even if the condition for its end is not fulfilled. It can be used to end  an infinite loop or to force it to end before its natural end. For an example, observe the below code.

//purpose :- I want to print numbers starting from 1 until i meet the first number divisible by 11.

#include<iostream>
using namespace std;

int main()
{
        int num=1;

        while(true)                            //to make the condition always true until we explicitly quit the loop
        {
                if(num/11 == 1)            //if the number is divisible by 11
                {
                 break;                         //go out of the loop
                }

                else
                {
                cout<<num<<endl;     // if not, print
                }
        num++;                               //increase num by 1
        }
        return 0;
}

Output of the running program is shown as below.













The continue statement

The continue statement causes the program to skip the rest of the loop in the current iteration as if the end of the statement block had been reached, causing it to jump to the following iteration. Note how the same example shown in break works with the continue with a little alteration.


//purpose :- I want to print all the numbers starting from 1 to 20 but not 11.

#include<iostream>
using namespace std;

int main()
{
        int num=0;

        while(num<20)                  
        {
                num++;
                if(num%11 == 0)            //if the number is divisible by 11
                {
                 continue;                       //stop the current execution of loop but go back
                }

                else
                {
                cout<<num<<endl;     // if not, print
                }
                              
        }
        return 0;
}


Since I have told the program to stop the current execution of the loop if it meet a number divisible by 11 in between 1 and 11, the program does not print 11 but print all the other numbers from 1 to 20. See the output of the program as below.



















The goto statement

goto allows to make an absolute jump to another point in the program. We should use this feature with caution since its execution causes an unconditional jump ignoring any type of nesting limitations.

It's just a simple concept as you say to one of your friend to go to some location if she/ he wants to buy something. If you say someone to go to somewhere, you must state them 'Where to go?' as well. Which means go to needs some destination point.

The destination point is identified by a label , which is used as an argument for the goto statement. A label is made of a valid identifier followed by a colon (:)

Actually, this instruction has no concrete use in structures or object oriented programming aside from those that we see in low-level programming.


#include<iostream>
using namespace std;

int main()
{
        int num=0;

        while(num<=20)                  
        {
                if(num%11 == 0)     //if the number is divisible by 11
                {
                 goto a ;                   //do not execute any statement but execute from the label a
                }

                else
                {
                cout<<num<<endl;   // if not, print
                }
                
              a : num++;                  //the statement labeled as a
        }
        return 0;
}


















you can see that the above program gives you the same results that we got from the continue example as well.

The exit function 

exit is a function defined in the cstdlib library which is used to turminate the current program with a specific exit code. It's method signature is,

void exit (int exitcode);

the exitcode is used by some operating systems and may be used by calling programs. By convention, an exitcode of 0 means that the program finished normally and any other value means that some error or unexpected results happened.

Selective structure -switch

The syntax of the switch statement may be a bit unfamiliar to you. Its objective is to check several possible constant values for an expression. Something similar to what we did at the beginning of this section with the concatenation of several if and else if instructions. Its form is the following:
switch (expression){        case constant1:
            group of statements 1;            break;

         case constant2:            group of statements 2;            break;           .           .           .        default:
          default group of statements
}


Once you know how the switch statements work, it'll be easy for you to work with it. 

switch evaluates expression and checks if it is equivalent to constant1 , if it is so, it then executes group of statements 1 until it finds the break statement. When it finds this break statement the program jumps to the end of the switch selective structure.


If expression was not equal to constant1 it will be checked against constant1 . If it is equal to this, it will execute group of statements 2 until a break keyword is found, and then will jump to the end of the switch selective structure.

Finally, if the value of expression did not match any of the previously specified constants (you can include as many case labels as values you want to check), the program will execute the statements included after the default:label, if it exists (since it is optional).

Note that a switch structure can be represented by if-else blocks as well. Observe the following code to see such example.



switch exampleif-else equivalent
switch (x) 
{
  case 1:
    cout << "x is 1";
    break;
  case 2:
    cout << "x is 2";
    break;
  default:
    cout << "value of x unknown";
  }
if (x == 1) 
{
  cout << "x is 1";
  }
else if (x == 2) {
  cout << "x is 2";
  }
else {
  cout << "value of x unknown";
  }




The switch statement is a bit odd within the C++ language because it uses labels instead of blocks. This forces us to put break statements after the group of statements that we want to be executed for a specific condition. Otherwise the remainder statements including those corresponding to other labels will also be executed until the end of the switch selective block or a break statement is reached.

For example, if we did not include a break statement after the first group for case one, the program will not automatically jump to the end of the switch selective block and it would continue executing the rest of statements until it reaches either a break instruction or the end of the switch selective block. This makes it unnecessary to include curly braces { } surrounding the statements for each of the cases, and it can also be useful to execute the same block of instructions for different possible values for the expression being evaluated. For example: 

switch ( number )
{
   case 1:
   case 2:
   case 3:
      cout << "number is 1, 2 or 3" ;
      break;

   default :
      cout <<"number is not 1, 2 or 3" ;

}

Also remember that switch can only be used to compare an expression against constants and therefore we cannot put variables as labels or ranges because they are not valid C++ constants.

But don't worry, you can use if-else blocks to check values that are not constants.

If you want more meaningful little programs to clarify theses control structures, please go through the next post as well.