Your browser doesn't support JavaScript Controlling Program Flow – Windows Programming

Controlling Program Flow

Conditional Execution

Conditional execution of code is implemented in C++ using the if, if…else, and switch…case statements.

The if Statement: The if statement selects and executes statement(s) based on a predefined condition. The statement(s) are only executed if the condition evaluates to true. If the condition evaluates to false, execution is skipped and the program control passes to the statement following the if statement.

The syntax of the if statement is

if (condition) { statement 1; statement 2; }

The if-else Statement: The if-else statement causes one of the two possible statement(s) to execute, depending upon the outcome of the predefined condition.

The syntax of the if…else statement is

if (condition) {// code block if condition is true Statement 1; Statement 2; } else {// code block if condition is not true Statement 3; Statement 4; }

The if…else if…else Statement – contains one or more if-else statements and is validated against several different conditions, which themselves may be dependent on the evaluation of a previous condition

if( expression1 ) // code block if expression 1 is true statement1; else if( expression2 ) // code block if expression 2 is true and expression 1 is false statement2; else // code block if previous conditions are all false statement3;

If expression1 is evaluated to true, statement1 is executed before the program continues. If the expression1 is not true, expression2 is checked and if it evaluates to true, statement2 is executed. If both expression1 and expression2 are false, statement3 is executed. Only one of the three statements is executed.

Conditional Processing Using Switch-Case

The switch-case conditional statement enables a check on a particular expression against a host of possible constant conditions and performs a different action for each of those different values. Each case statement ends with a break statement that causes execution to exit the code block.

The following is the syntax of a switch-case construct:

switch(expression) { case optionA: DoSomething; break; case optionB: DoSomethingElse; break; default: CatchAllWhenExpressionIsNotHandledAbove; break; }

Each case section will often end with a break statement, which causes execution to leave the switch statement. If break is omitted, execution continues into the following case section.

The Conditional Operator ‘? :

The conditional operator is similar to an if-else statement and selects one of the two values or expressions based on a given condition. The conditional operator produces one of two values or expressions depending on the condition. Unlike if…else, it is not used to execute separate blocks of statements.

in the example below the variable highvalue is set to the greater of two given numbers contained in variable num1 and variable num2

int highvalue = (num1 > num2)? num1 : num2;

Looping

Many tasks in a program are accomplished by carrying out a repetitive series of instructions, a fixed number of times or until a specific condition is met. A block of such code is called a loop. Each pass through the loop is called an iteration and the blocks of code are called compound statements.

While Loops

A while loop causes a code block to be executed repeatedly as long as a starting condition remains true. The while keyword is followed by an expression in parentheses. If the expression is true, the statements inside the loop block are executed and executed repeatedly until the expression is false. If the initial condition is not met code inside the block is not executed. In the following code sample, the while loop counts to 10 and exits the loop when the variable i is equal to 10

#include <iostream> 
int main() 
{
int i;
while (i <=10) //test condition
{
std::cout << ++i << "\n";//output value of i
}
}

The while keyword is proceeded by the condition within parentheses. To note, this statement does not end in a semicolon. The statements inside the loop are surrounded by {} braces indicating the start and end of a localised block of code. The loop has the conditional expression i < =10 . The body of code will be executed while the value of i is lower than 10.

Do-While Loops

A do-while loop is a control flow statement that executes a block of code at least once. In contrast to a while loop which starts with a conditional expression before code execution, the do-while loop checks the condition after the block is executed.

#include <iostream> 
int main() 
{
int i = 10;
do
{
std::cout << ++i << "\n";//output value of i
} while (i < 5);//test condition
}

This loop’s conditional statement is only true when i < 5 . Since i begins with a value of 10, this condition is never true however the body of the loop executes once. This occurs because the do-while loop does not evaluate the condition statement until after the loop’s statements are executed. A do-while loop always executes the body at least once.

For Loops

Is an iterative control flow statement that allows code to be executed a specific number of times. The condition is checked at the beginning of each iteration. If it is true, the loop body executes. After the body executes, the increment expression is evaluated before the condition is checked again.

for ( init; condition; increment ) { statement(s); }

The optional init step is executed first, and only once and allows the programmer to declare and initialise any loop control variables. If no initialisation is specified a semicolon must be used.

Following initialisation, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the for loop.

After the body of the for loop executes, the flow of control jumps back up to the increment statement. This process is repeated until the condition becomes false, after which the loop terminates

#include <iostream> 
int main() 
{
for (int i = 0; i < 10; i++)//initialise loop 
{
std::cout << i;//output value of i to screen
}
}

In the code section above, the for loop is declared and the variable i is initialised to 0. The value of i is checked and, if the condition i < 10 is true, the body is executed. If the condition is false, the loop terminates. The variable i is then incremented at the end of the loop and the process is repeated until the condition statement return false and the loop exits.

Leaving any of the three expressions in a for statement blank is permitted. If the condition is omitted, it is treated as always true, so for(;;) creates an infinite loop unless the loop is terminated by another statement.

Advanced for Loops – It is possible to create and run multiple loops within one statement. When the initialisation and action sections contain more than one statement, they are separated by commas –

for (int a = 0, b = 0; a < 10; a++, b++)

This loop has two variable initialisations: a and b, each separated by a comma. The loop’s test section tests whether a < 10 and both integer variables are incremented.

Nested Loops – Loops can be nested with one loop sitting in the body of another. The inner loop will be executed in its entirety for every execution of the outer loop. –

for ( init; condition; increment ) { for ( init; condition; increment ) { statement(s); } statement(s); // you can put more statements. }

The Range-Based For Loop –  Introduced in C++11 the range-based loop executes on a predefined range of values such as those contained in an array

For example, given an array of integers, you would use a range-based for loop to read elements contained in the array –

#include <iostream> 
int main() 
{
int myvalues[] = { 1, 88, 33, -5,13};
for (int aNum : myvalues) // range based for
{
std::cout << "The array elements are " << aNum <<"\n";
}
}

Continue and Breaking

The break statement causes a loop to end immediately, instead of waiting for its condition to be false. When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop

The continue statement skips the remainder of the current iteration and proceeds with the next iteration of the loop. The exact point at which execution resumes depends on the type of loop.

#include <iostream>
using namespace std;
int main () 
{
int a = 10;
do { 
a=a+1; 
if( a == 15) //check if a=15. skip to end of loop
{
continue;    
}   
cout << "value of a: " << a << endl;
} while( a < 20 );
return 0;
}

Usually, programmers expect all code in a loop to be executed when the loop conditions are satisfied. Continue and break modify this behaviour and can result in non-intuitive code. Therefore, continue and break should be used sparingly

The Goto Statement

The goto statement transfers program control directly to a labelled statement. Although it is part of C++, its use is generally discouraged because excessive use can make program flow difficult to understand and maintain.

The syntax for the goto statement is

{
Start: // Called a label
UserCode;
goto Start;
}

Exiting the Program

Under normal circumstances, a C++ program terminates when execution reaches the closing brace of the main() function.

Program termination can, however, be initiated by the program by calling the library functions exit(), abort(), and atexit(). To use these functions, a program must include the header file <cstdlib>

Exit Function

The exit function terminates a C++ program and the argument value supplied to the exit function is returned to the operating system as a return code. A status of zero conventionally indicates successful termination, while a non-zero status indicates some form of failure.The syntax of this function is

void exit ( int status );

In addition, the header file also defines two constants for use as arguments to the exit() function:

Abort Function

The abort function terminates the program immediately bypassing any of the usual run-time termination processing.
The syntax for the atexit function is

void abort();

Atexit Function

The atexit function is used to specify actions that execute before the program terminates. The syntax for the atexit function is

int atexit (void (*func)(void));

The following short program demonstrates how to call a function before closing the program

#include <iostream>
#include <cstdlib>
using namespace std;
void closing()
{
	cout << "Program closure successful";
}
int main()
{
	int x;
	x = atexit(closing);
	if (x != 0)
	{
	cout << "Program Failure";
	exit(1);
	}	
cout << "Program successful" << endl;
return 0;
}