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 let the programmer 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. 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. 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 expression evaluates to true, statement1 is executed. If the expression evaluates to false, control passes to the else statement and statement2 is then 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 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.
One-line statement - If there is only one statement to execute after the if condition then 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 of those different values. Each case statement is ended with an optional break statement that causes execution to exit the code block. In most situations you will want a break ending each section however in some situations you may want to execute multiple case statements. 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 blocks of code 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 value of the variable 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 initialize 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. In the code section below, the for loop is declared and the variable initialised i to 0. The value of value 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 is repeated until the condition statement return 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 that the condition will start with a null value. You can create an infinite loop by using for(;;)
Advanced for Loops – It is possible to create and run multiple loops within one statement. When the initialization 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);
}
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 the block is not executed –
while(condition)
{
statement(s);
}
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.
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 loops check 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=15. skip to end of loop continue; if (a==8) 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 is made of a valid identifier followed by a colon (:). It's advised to use goto statements with caution and preferably not at all 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.
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 function exit(). When the exit() function terminates a program and returns control to the operating system it can pass a status code to the operating system to indicate the program’s success or failure. The syntax of the exit() function is
exit(status);
If the status has a value of 0, it indicates that the program terminated normally. A value of 1 indicates that the program terminated with some sort of error.
To use the exit() function, a program must include the header file stdlib.h. This header file also defines two constants for use as arguments to the exit() function:
#define EXIT_SUCCESS
#define EXIT_FAILURE