Login

Username:

Password: 

Join us Now |  Forgot Password? | Forgot UserName?

C++

Learn step by step



Flow Control

There are three basic flow control constructs - sequential, conditional (or decision), and loop (or iteration), as illustrated below.

Fig1.

Sequential Flow Control

A program is a sequence of instructions. In sequential programming statements are executed in the order that they are written - from top to bottom in a sequential manner.

Conditional (Decision) Flow Control

Few types of conditionals are if-then, if-then-else, nested-if (if-elseif-elseif-...-else), switch-case, & conditional expression.


Syntax Example Flowchart
// if-then if ( booleanExpression ) { true-block ; } if (mark >= 50) { cout << "Congratulation!" << endl; cout << "Keep it up!" << endl; }
// if-then-else if ( booleanExpression ) { true-block ; } else { false-block ; } if (mark >= 50) { cout << "Congratulation!" << endl; cout << "Keep it up!" << endl; } else { cout << "Try Harder!" << endl; }
// nested-if if ( booleanExpr-1 ) { block-1 ; } else if ( booleanExpr-2 ) { block-2 ; } else if ( booleanExpr-3 ) { block-3 ; } else if ( booleanExpr-4 ) { ...... } else { elseBlock ; } if (mark >= 80) { cout << "A" << endl; } else if (mark >= 70) { cout << "B" << endl; } else if (mark >= 60) { cout << "C" << endl; } else if (mark >= 50) { cout << "D" << endl; } else { cout << "F" << endl; }
// switch-case switch ( selector ) { case value-1: block-1; break; case value-2: block-2; break; case value-3: block-3; break; ...... case value-n: block-n; break; default: default-block; } char oper; int num1, num2, result; ...... switch (oper) { case '+': result = num1 + num2; break; case '-': result = num1 - num2; break; case '*': result = num1 * num2; break; case '/': result = num1 / num2; break; default: cout << "Unknown operator" << endl; }

"switch-case" is an alternative to the "nested-if". In a switch-case statement, a break statement is needed for each of the cases. If the break is missing, execution will flow through the following case. We can use either an int or char variable as the case-selector.

Conditional Operator: A conditional operator is a ternary (3-operand) operator, in the form of booleanExpr ? trueExpr : falseExpr. Depending on the booleanExpr, it evaluates and returns the value of trueExpr or falseExpr.



Syntax Example
booleanExpr ? trueExpr : falseExpr cout << (mark >= 50) ? "PASS" : "FAIL" << endl;

// return either PASS or FAIL, and put to cout

max = (a > b) ? a : b; // Result a or b

abs = (a > 0) ? a : -a; // Result a or -a

Braces: We omit the braces { }, if there is only one statement inside the block.

if (mark >= 50)
cout << "PASS" << endl; // Only one statement, can omit { } but not recommended
else { // more than one statements, need { }
cout << "FAIL" << endl;
cout << "Try Harder!" << endl;
}

However, I recommend that you keep the braces, even though there is only one statement in the block, to improve the readability of your program.


Loop Flow Control

Again, there are a few types of loops: for-loop, while-do, and do-while.


Syntax Example Flowchart
// for-loop
for (init; test; post-proc) { body ; }
// Sum from 1 to 1000
int sum = 0; for (int number = 1; number <= 1000; ++number) { sum += number; }
// while-do
while ( condition ) { body ; }  
int sum = 0, number = 1; while (number <= 1000) { sum += number; ++number; }
// do-while
do { body ; } while ( condition ) ;
int sum = 0, number = 1; do { sum += number; ++number; } while (number <= 1000);

Difference between while and do-while lies in the order of the body and condition. In while, the condition is tested first. And the body will be executed if the condition is true and the process repeats. In do-while loop, body is executed once and then the condition is tested. Note: the body of do-while will be executed at least once ( possibly zero for while-do ).

let us have a look at a countdown using a while-loop:


// custom countdown using while
#include <iostream>
using namespace std;

int main ()
{
int n = 10;

while (n>0) {
cout << n << ", ";
--n;
}

cout << "liftoff!\n";
}

Output

10, 9, 8, 7, 6, 5, 4, 3, 2, 1, liftoff!

Following program echoes any text the user introduces until the user enters goodbye:


// echo machine
#include <iostream>
#include <string>
using namespace std;

int main ()
{
string str;
do {
cout << "Enter text: ";
getline (cin,str);
cout << "You entered: " << str << '\n';
} while (str != "goodbye");
}

Output

Enter text: hello
You entered: hello
Enter text: who's there?
You entered: who's there?
Enter text: goodbye
You entered: goodbye

Below given countdown example using a for loop:


// countdown using a for loop
#include <iostream>
using namespace std;

int main ()
{
for (int n=10; n>0; n--) {
cout << n << ", ";
}
cout << "liftoff!\n";
}

Output

10, 9, 8, 7, 6, 5, 4, 3, 2, 1, liftoff!
Jump statements

Jump statements allow changing flow of a program by performing jumps to specific locations.

The break statement

break Statement leaves a loop, even if the end condition is not fulfilled. This can be used to end an infinite loop, or force it to end before its natural end.


// break loop example
#include <iostream>
using namespace std;

int main ()
{
for (int n=10; n>0; n--)
{
cout << n << ", ";
if (n==3)
{
cout << "countdown aborted!";
break;
}
}
}

output

10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!
The continue statement

Continue statement causes program to skip the rest of loop in the current iteration, as if end of the statement block had been reached, causing it jump to start of the iteration.


// continue loop example
#include <iostream>
using namespace std;

int main ()
{
for (int n=10; n>0; n--) {
if (n==5) continue;
cout << n << ", ";
}
cout << "liftoff!\n";
}

Output

10, 9, 8, 7, 6, 4, 3, 2, 1, liftoff!
The goto statement

Statement goto allows to make an jump to another point in the program. jump ignores nesting levels, and doesn't cause automatic stack unwinding. So, it is to be used with care, and preferably inside the same block of statements, considerably in presence of all local variables.

Destination point is identified by label, This Label is an argument for the goto. Label is made of a valid identifier(User Given Name) followed by a colon (:).

goto is generally assumed as a low-level feature, with no special use cases in modern higher-level programming generally used with C++. Example,


// goto loop example
#include <iostream>
using namespace std;

int main ()
{
int n=10;
mylabel:
cout << n << ", ";
n--;
if (n>0) goto mylabel;
cout << "liftoff!\n";
}

Output

10, 9, 8, 7, 6, 4, 3, 2, 1, liftoff!
Nested Loops

The following diagram illustrates a nested for-loop, i.e., an inner for-loop within the outer for-loop.

Fig 2.

In the Example we print all the combinations of the digits from 0 to 5.


#include <iostream>
using namespace std;

int main ()
{
int i, j;

for(i=0; i<=5; i++) {

for(j=0; j <= 5; j++) {
cout << i << j <<" \t";
}

cout <<"\n";
}

return 0;
}

Output:-

00 01 02 03 04 05
10 11 12 13 14 15
20 21 22 23 24 25
30 31 32 33 34 35
40 41 42 43 44 45
50 51 52 53 54 55


Related Videos