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

Controlling Program Flow

Program flow is the order in which individual programming statements are evaluated. In C, execution starts at the beginning of the main() function and ends when the end of main() is reached however the C language includes a variety of program control statements that control the order of program execution.

The if Statement

The if statement evaluates an expression and executes statement(s) based on the outcome of this evaluation. These 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. Control over program execution is through the use of these compound statements which are blocks of code enclosed in brackets

The syntax of the if statement is

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

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;
}
else
{
// code block if condition is not true
Statement 2;
}

If the expression evaluates to true, statement1 is executed. If the expression evaluates to false, control passes to the else statement and statement2 is executed. 

Nested if-else – 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 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.

One-line statement – If there is only one statement to execute after the if condition the use of curly braces is optional. If there are multiple statements without curly braces then only the statement after the if condition gets conditionally executed; the rest of the statement will get executed separately and not as part of the expression. It is therefore considered good practice to use curly braces to prevent confusion and cover the possibility that the programmer may add statements to the block.

Switch Statement

The switch-case conditional statement checks a particular expression against a host of possible constant conditions and performs a different action for each value. Each case statement is ended with an optional break statement that causes execution to exit the code block. If a break statement does not end the statement sequence associated with a case, then all the statements at and below the matching case will be evaluated

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

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

Looping

Many tasks in a program are accomplished by carrying 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 code blocks are called compound statements.

The For Statement

Is an iterative control flow statement which allows code to be executed a specific number of times. The exit condition is checked at the beginning of every loop, and the variable value is incremented at the end of a loop. The syntax of a loop is –

 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 loop body does not execute and flow control jumps to the next statement just after the for loop.

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

In the code section below, the for-loop is declared and the variable i is initialised to 0. The value of i is then checked and if the exit condition (i<10) is not met the body is executed. The variable i is then incremented at the end of the loop and the process repeats until the condition statement returns false and the loop exits.

#include <stdio.h>
int main( void )
{
for (int i = 0; i < 10; i++)
{
printf("%i",i);
}
return 0;
}

Leaving any parameter blank in a for-next declaration means the condition will start with a null value. You can create an infinite loop by using for(;;)

Advanced for Loops – Multiple loops can be executed by separating each statement with a comma. –

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); 
}

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 until the expression is false.  If the initial condition is not met the block is not executed –

while(condition)
{
statement(s);
}

Do-While Loops

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

do
{
statement(s);
}
while(condition);

Ending Loops Early

The break Statement – 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 – Continue resumes execution from the top of the loop. The code following it within the block is skipped. Thus, the effect of continue in a while , do…while , or for loop is that it forces the next iteration of the loop to take place, skipping any code in between.

#include <stdio.h>
int main () 
{
int a = 0;
do { 
a++; 
if( a == 5) //check if a equals 5, skip to end of loop
continue; 
if (a==8)//if a equals 8, terminate loop
break;
printf("%i ",a);
} while( a < 20 );
return 0;
}

The Goto Statement

Goto performs a one-way transfer of control to another point in the program. This requires an unconditional jump ignoring any existing program flow such as nesting and does not cause any automatic stack adjusting. The destination point is identified by a label, which is then used as an argument for the goto statement. A label consists of a valid identifier followed by a colon (:). Since the use of goto statements can lead to an unpredictable flow of code, difficult-to-read programming (spaghetti code), and in some cases unpredictable variable states It’s advised to use goto statements with caution and preferably not at all s

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 stdlib.h.

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. Conventionally, a return code of zero means that the program was completed successfully and a value of 1 indicates that the program terminated with an error.

void exit ( int status );

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

define EXIT_SUCCESS
define EXIT_FAILURE

Abort Function

The abort function terminates the program immediately bypassing 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 <stdio.h>
#include <stdlib.h>;
void closing()
{
    printf ("Program closure successful");
}
int main()
{
    int x;
    x = atexit(closing);
    if (x != 0)
    {
    printf ("Program Failure");
    exit(1);
    }    
printf ("Program successful \n");
return 0;
}