C++ is using C like control statements. These statements are based on structured programming theory. Are designed to avoid _spaghetti code_ that use to be created using goto statement. Two most important structures are conditionals and iterations.

Conditionals

These statements based on  logical expressions. The most important is “if” statement. In next example we can see condition (num>4) is enclosed in round brackets. After condition there is one block {… } that is not executed since num == 4 that is not > 4.

#include <iostream>
using namespace std;
 
int main ()
{
   // Declaring local variable
   int num = 4;
 
   // check the boolean condition
   if( num > 4 )
   {
       cout << "num is greater than 4" << endl;
   }
   cout << "Given number is : " << num << endl;
 
   return 0;
}

 

Multi-Way Decision

In C++ we do not have elsif or elif like in other languages but we have else keyword.  This can be combined into a long decision chain or decision ladder. This is one of the most advanced selection statement that can be easy created in C++.

 

#include <iostream>
using namespace std;
 
int main ()
{
   // declare local variable
   int marks = 55;
 
   // check the boolean condition
   if( marks >= 80 )
   {
       // if 1st condition is true
       cout << "U are 1st class !!" << endl;
   }
   else if( marks >= 60 && marks < 80)
   {
       // if 2nd condition is false
       cout << "U are 2nd class !!" << endl;
   }
   else if( marks >= 40 && marks < 60)
   {
       // if 3rd condition is false
       cout << "U are 3rd class !!" << endl;
   }
   else 
   {
       // none of condition is true
       cout << "U are fail !!" << endl;
   }
 
   return 0;
}

 

Switch Statement

This is a selection statement that is also multi-way like previous ladder. The difference is we need a selector. That is a variable that can have different values. The selector can be an expression. In next example we have a selector variable “grade” that can be: A, B, C, D,E, F. This is specific to US in schools we have these 6 levels of graduation used for exams. Observe this statement has a single block {….} each case can have one or several statements up the the next case. Each case end with column “:”;

#include <iostream>
using namespace std;
 
int main ()
{
   // local variable declaration:
   char grade = 'C';

   switch(grade)
   {
   case 'A' :
      cout << "A grade" << endl; 
      break;
   case 'B' :
      cout << "B grade" << endl;
      break;
   case 'C' :
      cout << "C grade" << endl; 
      break;
   case 'D' :
      cout << "D grade" << endl; 
      break;
   case 'F' :
      cout << "E grade" << endl; 
      break;
   default :
      cout << "Invalid grade" << endl;
   }
   cout << "Your grade is " << grade << endl;
 
   return 0;
}

While loop

The most common loop in any language is the while loop. This is used to repeat execution of statement block as long as a given condition is true. In C++ zero value of an expression is considered false and one or any number greater then 0 is considered true. This is also known as entry controlled loop;

while(<condition>) 
{
  ...
}

 

Note:  If you are familiar with Level language you notice differences. The while loop here do not have a local scope. Also the condition is enclosed in parentheses and the “loop” keyword is not used. The block statement is as usually enclosed in brackets {…}

 

Here is a simple while loop:

#include <iostream>
using namespace std;
 
int main ()
{
   // Local variable declaration
   int num = 5;

   // while loop execution
   while( num < 10 )
   {
       cout << "Number : " << num << endl;
       num++;
   }
   return 0;
}

Do while loop

This loop is similar with while loop. The condition is at the end of the loop, therefore the loop is executed at least once. This is also called exit-controlled loop.

do {
  ...
} while( condition );

 

Note: This kind of loop does not exist in Level. Few developers are using this kind of loop. Most of the time a while loop is good enough to resolve all the cases.

 

#include <iostream>
using namespace std;
 
int main ()
{
   // Local variable declaration:
   int i = 0;

   // do loop execution
   do
   {
       cout << "value of i : " << i << endl;
       i++;
   }while( i < 10 );
   
   return 0;
}

 

For loop

The for loop is a little bit more complicated. This is created to repeat a block of code a predefined number of times. Usually this kind of loop is controller by a variable that is called control variable or index. The index is incremented each iteration with one. The final value will cause the loop to stop.

for ( init; condition; increment )
{
   ...
}
  • init: is a declaration of control variable like this: int i = 0;
  • condition: is usually a simple comparison like this: i<10;
  • increment: is an expression to calculate next value of i like this: i = i+1;

Here is an example:

#include <iostream>
using namespace std;
 
int main ()
{
   // for loop execution
   for(int i = 0; i < 10; i = i + 1 )
   {
       cout << "value of i : " << i << endl;
   }
   return 0;
}

 

Note: For efficient purpose increment can be (i++). That is a special feature of C++ to replace i=i+1.  If you are familiar with Level language we do not think this is a big deal. We do not use ++ or — operators. Instead we use only i+=1 operator that is also efficient.

Early termination

Any loop can be terminated before normal. For this we use “break” keyword. Usually a break is controlled by the if statement. In next example we stop execution when count> 5.

#include <iostream>
using namespace std;
 
int main ()
{
   // Declaring Local variable
   int count = 0;

   // do loop execution
   do
   {
       cout << "Count : " << count << endl;
       count++;
       if( count > 5)
       {
          // Terminate the loop
          break;
       }
   }while( count < 20 );
 
   return 0;
}

 

Iteration Shortcut

Sometimes we can reach a point where the loop must continue with next iteration and skip the other statement before the loop end. This is called “shortcut” or “continuation”. We use keyword “continue” to continue the loop with next iteration.

#include <iostream>
using namespace std;
 
int main ()
{
   int count = 0;
   do
   {	   
     count++;
     if(count > 5 && count < 7)
        continue;

     cout << "Count : " << count << endl;
   }while( count < 10 );

   return 0;
}

 

Note: The loop control is manually overwritten by using break and continue. This technique is also used in Level. We use keywords: “exit” and “skip”.

GOTO Statement

In Level we do not teach this statement. This is the enemy statement of structured programming  but it exists in C++. It has to be used with caution only when necessity dictate. This is also called “unconditional jump” statement.

label: statement;
 ... 
goto label;

Note: label can be backward or forward. So we can jump also forward.

#include <iostream>
using namespace std;
 
int main ()
{
   int num = 1;
   here:do
   {
     if( num == 5)
     {
        num = num + 1;
        goto here;
     }

     cout << "value of num : " << num << endl;
     num = num + 1;

   }while( num < 10 );
   return 0;
}

 

Function

Now the most powerful powerful control structure is the function. This is a group of statement that can be executed on demand. In any program we must have at least one function and this has a special name: main(). Functions are used to eliminate repetitive code.

NOTE: Here is an important catch. Functions in C++ are not called functions. Actually they are not called anything. We do not have a dedicated keyword to create a function.  This may look like very smart.  We do not have to type the keyword and that makes the program smaller. In fact we think the program is harder to read.

<return_type> function_name( <parameter_list> )
{
   ...
}

Example:

#include <iostream>
using namespace std;
 
// function declaration
int sum(int num1, int num2);
 
int main ()
{
   // local variable declaration:
   int a = 10;
   int b = 20;
   int result;
 
   // calling a function to get result.
   result = sum(a, b); 
   cout << "Sum is : " << result << endl;
 
   return 0;
}
 
// function returning the sum of two numbers
int sum(int num1, int num2) 
{
   // local variable declaration
   int res; 
   res = num1 + num2;

   return res; 
}

 

Next: Type System