C Programming Program Controls
C Programming Program Controls
Flow Charts
-controlling the program execution flow:
selection, repetition and branching-
www.tenouk.com, © 1/77
PROGRAM CONTROL
Program begins execution at the main() function.
Statements within the main() function are then
executed from top-down style, line-by-line.
However, this order is rarely encountered in real C
program.
The order of the execution within the main() body
may be branched.
Changing the order in which statements are
executed is called program control.
Accomplished by using program control statements.
So we can control the program flows.
www.tenouk.com, © 2/77
PROGRAM CONTROL
www.tenouk.com, © 3/77
PROGRAM CONTROL
Take a look at the following example
www.tenouk.com, © 4/77
PROGRAM CONTROL
www.tenouk.com, © 5/77
PROGRAM CONTROL
Selection Control Structure
www.tenouk.com, © 6/77
PROGRAM CONTROL
Selection: if, if-else, if-else-if
1. (condition) is evaluated.
2. If TRUE (non-zero) the statement is executed.
3. If FALSE (zero) the next_statement following the if statement
block is executed.
4. So, during the execution, based on some condition, some codes were
skipped.
www.tenouk.com, © 7/77
PROGRAM CONTROL
For example:
if (hours > 70)
hours = hours + 100;
printf("Less hours, no bonus!\n");
If hours is less than or equal to 70, its value will remain unchanged and the printf() will
be executed.
If it exceeds 70, its value will be increased by 100.
if(jobCode == '1')
{
carAllowance = 100.00;
housingAllowance = 500.00;
entertainmentAllowance = 300.00;
}
printf("Not qualified for car, housing and entertainment allowances!");
The three statements enclosed in the curly braces { } will only be executed if jobCode is equal
to '1', else the printf() will be executed.
www.tenouk.com, © 8/77
PROGRAM CONTROL
if (condition) if (condition)
statement_1; { a block of statements;}
else else
statement_2; { a block of statements;}
next_statement; next_statement;
Explanation:
1. The (condition) is evaluated.
2. If it evaluates to non-zero (TRUE), statement_1 is executed,
otherwise, if it evaluates to zero (FALSE), statement_2 is
executed.
3. They are mutually exclusive, meaning, either statement_1 is
executed or statement_2, but not both.
4. statements_1 and statements_2 can be a block of codes and
must be put in curly braces.
www.tenouk.com, © 9/77
PROGRAM CONTROL
For example:
if(myCode == '1')
rate = 7.20;
else
rate = 12.50;
www.tenouk.com, © 10/77
PROGRAM CONTROL
Program example 1: if
Program example 2: if-if
Program example 3: if-else
www.tenouk.com, © 11/77
PROGRAM CONTROL
The if-else constructs can be nested (placed one within another) to any depth.
General forms: if-if-else and if-else-if.
The if-if-else constructs has the following form (3 level of depth example),
if(condition_1)
if(condition_2)
if(condition_3)
statement_4;
else
statement_3;
else
statement_2;
else
statement_1;
next_statement;
www.tenouk.com, © 12/77
PROGRAM CONTROL
In this nested form, condition_1 is evaluated. If it is zero (FALSE),
statement_1 is executed and the entire nested if statement is
terminated.
If non-zero (TRUE), control goes to the second if (within the first if)
and condition_2 is evaluated.
If it is zero (FALSE), statement_2 is executed; if not, control goes
to the third if (within the second if) and condition_3 is evaluated.
If it is zero (FALSE), statement_3 is executed; if not,
statement_4 is executed. The statement_4 (inner most) will only
be executed if all the if statement are TRUE.
Again, only one of the statements is executed other will be skipped.
If the else is used together with if, always match an else with the
nearest if before the else.
statements_x can be a block of codes and must be put in curly
braces.
www.tenouk.com, © 13/77
PROGRAM CONTROL
The if-else-if statement has the following form (3 levels example).
if(condition_1)
statement_1;
else if (condition_2)
statement_2;
else if(condition_3)
statement_3;
else
statement_4;
next_statement;
www.tenouk.com, © 14/77
PROGRAM CONTROL
condition_1 is first evaluated. If it is non zero (TRUE),
statement_1 is executed and the whole statement
terminated and the execution is continue on the
next_statement.
If condition_1 is zero (FALSE), control passes to the
next else-if and condition_2 is evaluated.
If it is non zero (TRUE), statement_2 is executed and
the whole system is terminated. If it is zero (FALSE), the
next else-if is tested.
If condition_3 is non zero (TRUE), statement_3 is
executed; if not, statement_4 is executed.
Note that only one of the statements will be executed,
others will be skipped.
statement_x can be a block of statement and must be
put in curly braces.
www.tenouk.com, © 15/77
PROGRAM CONTROL
The if-else-if program example
www.tenouk.com, © 16/77
PROGRAM CONTROL
Selection: The switch-case-break
www.tenouk.com, © 17/77
PROGRAM CONTROL
The switch constructs has the following form:
switch(condition)
{
case template_1 : statement(s);
break;
case template_2 : statement(s);
break;
case template_3 : statement(s);
break;
…
…
case template_n : statement(s);
break;
default : statement(s);
}
next_statement;
www.tenouk.com, © 18/77
PROGRAM CONTROL
Evaluates the (condition) and compares its value with the
templates following each case label.
If a match is found between (condition) and one of the
templates, execution is transferred to the statement(s) that
follows the case label.
If no match is found, execution is transferred to the
statement(s) following the optional default label.
If no match is found and there is no default label, execution
passes to the first statement following the switch statement
closing brace which is the next_statement.
To ensure that only the statements associated with the
matching template are executed, include a break keyword
where needed, which terminates the entire switch statement.
The statement(s) can be a block of code in curly braces.
www.tenouk.com, © 21/77
PROGRAM CONTROL
The differences between nested if and switch:
1. The switch-case permits the execution of more than one
alternatives (by not placing break) whereas the if statement
does not. In other words, alternatives in an if statement are
mutually exclusive whereas they may or may not be in the case of
a switch-case.
2. A switch can only perform equality tests involving integer (or
character) constants, whereas the if statement allows more
general comparison involving other data types as well.
www.tenouk.com, © 24/77
PROGRAM CONTROL
The following flow chart examples represent C if selection
constructs.
Start
printf("");
scanf("”);
TRUE
intNum ==
3? printf("");
printf("");
FALSE
printf("");
www.tenouk.com, © 25/77
PROGRAM CONTROL
Start
G?
R?
The switch-case-
break program
T
T
source code example
printf(""); break;
Y? printf("");
F
printf("");
Stop
www.tenouk.com, © 26/77
PROGRAM CONTROL
if, if-else and switch-case-break flow charts
www.tenouk.com, © 27/77
PROGRAM CONTROL
Repetition: The for statement
Executes a code block for a certain number of times.
The code block may have no statement, one statement or more.
The for statement causes the for loop to be executed in a fixed number of times.
The following is the for statement form,
for(initial_value;condition(s);increment/decrement)
statement(s);
next_statement;
Evaluate initial_value
Do increment/ decrement
Stop
www.tenouk.com, © 29/77
PROGRAM CONTROL
A Simple for example, printing integer 1 to 10.
#include <stdio.h>
void main(void)
{
int nCount;
// display the numbers 1 to 10
for(nCount = 1; nCount <= 10; nCount++)
printf("%d ", nCount);
printf("\n");
}
www.tenouk.com, © 30/77
PROGRAM CONTROL
Its flow chart…
Start
nCount = 1
nCount++
Stop
www.tenouk.com, © 31/77
PROGRAM CONTROL
for loop is a very flexible construct.
Can use the decrementing counter instead of
incrementing. For example,
for (nCount = 100; nCount > 0; nCount--)
www.tenouk.com, © 33/77
PROGRAM CONTROL
The condition(s) expression that terminates the
loop can be any valid C expression.
As long as it evaluates as TRUE (non zero), the for
statement continues to execute.
Logical operators can be used to construct more
complex condition(s) expressions. For
example,
for(nCount =0; nCount < 1000 && name[nCount] != 0; nCount ++)
printf("%d", name[nCount]);
for(nCount = 0; nCount < 1000 && list[nCount];)
printf("%d", list[nCount ++]);
Note: The for statement(s) and arrays are closely related, so it is difficult to
define one without explaining the other (will be discussed in another
Chapter).
www.tenouk.com, © 34/77
PROGRAM CONTROL
The for statement(s) can be followed by a null (empty)
statement, so that task is done in the for loop itself.
Null statement consists of a semicolon alone on a line. For
example,
for(count = 0; count < 20000; count++)
;
www.tenouk.com, © 35/77
PROGRAM CONTROL
An expression can be created by separating two sub expressions
with the comma operator, and are evaluated (in left-to-right order),
and the entire expression evaluates to the value of the right sub
expression.
Each part of the for statement can be made to perform multiple
duties. For example,
"We have two arrays with 1000 elements each, named a[ ] and b[ ].
Then we want to copy the contents of a[ ] to b[ ] in the reverse order,
so, after the copy operation, the array content should be…"
www.tenouk.com, © 36/77
PROGRAM CONTROL
Another examples of the for statements,
nSum = 0;
for(iRow = 1; iRow <=20; iRow++)
nSum = nSum + iRow;
printf("\n Sum of the first 20 natural numbers = ");
printf("Sum = %d", nSum);
The above program segment will compute and display the sum of
the first 20 natural numbers.
The above example can be re-written as,
for(iNum = 1, nSum = 0; iNum <= 20; iNum++)
nSum = nSum + iNum;
printf("Sum of the first 20 natural numbers = %d", nSum);
Take note that the initialization part has two statements separated
by a comma (,).
www.tenouk.com, © 37/77
PROGRAM CONTROL
Another example,
for(iNum = 2, nSum=0, nSum2 = 0; iNum <= 20; iNum = iNum + 2)
{
nSum = nSum + iNum;
nSum2 = nSum2 + iNum * iNum;
}
printf("Sum of the first 20 even natural numbers = %d\n", nSum);
printf("Sum of the square for the first 20 even natural numbers =
%d", nSum2);
www.tenouk.com, © 38/77
PROGRAM CONTROL
We can also create an infinite or never-ending loop by omitting all
the expressions or by using a non-zero constant for condition(s) as
shown in the following two code snippets,
for( ; ; )
printf("This is an infinite loop\n");
or
for( ; 1 ; )
printf("This is an infinite loop\n");
www.tenouk.com, © 39/77
PROGRAM CONTROL
The program has two for loops. The loop index iRow for the outer (first)
loop runs from 1 to 10 and for each value of iRow, the loop index jColumn
for the inner loop runs from iRow + 1 to 10.
Note that for the last value of iRow (i.e. 10), the inner loop is not executed at
all because the starting value of jColumn is 2 and the expression jColumn
< 11 yields the value false (jColumn = 11).
www.tenouk.com, © 40/77
PROGRAM CONTROL
Another nested for example
1. In the first for loop, the initialization is skipped because the initial value of
row, 10 has been initialized; this for loop is executed until the row is 1
(row > 0).
2. For every row value, the inner for loop will be executed until col = 1 (col
> 0).
3. So the external for loop will print the row and the internal for loop will print
the column so we got a rectangle of #.
www.tenouk.com, © 41/77
PROGRAM CONTROL
Repetition: The while loop
Start
T Execute statement(s)
Evaluate
condition
Stop
www.tenouk.com, © 43/77
PROGRAM CONTROL
A simple example
// simple while loop example
#include <stdio.h>
int main(void)
{
int nCalculate = 1;
// set the while condition
while(nCalculate <= 12)
{
// print
printf("%d ", nCalculate);
// increment by 1, repeats
nCalculate++;
}
// a newline
printf("\n");
return 0;
}
www.tenouk.com, © 44/77
PROGRAM CONTROL
The same task that can be performed using the for
statement.
But, while statement does not contain an initialization
section, the program must explicitly initialize any
variables beforehand.
As conclusion, while statement is essentially a for
statement without the initialization and increment
components.
The syntax comparison between for and while,
www.tenouk.com, © 45/77
PROGRAM CONTROL
Just like for and if statements, while statements can also
be nested.
The nested while example
www.tenouk.com, © 46/77
PROGRAM CONTROL
The nested for and while program example
www.tenouk.com, © 47/77
PROGRAM CONTROL
Repetition: The do-while loop
Executes a block of statements as long as a specified condition is
true at least once.
Test the condition at the end of the loop rather than at the
beginning, as demonstrated by the for and while loops.
The do-while loop construct is,
do
statement(s);
while (condition)
next_statement;
Start
The statement(s)
are always executed
Execute statement(s) at least once.
for and while
loops evaluate the
T
condition at the start
Evaluate
condition of the loop, so the
associated
F
statements are not
Stop executed if the
condition is initially
FALSE.
www.tenouk.com, © 49/77
PROGRAM CONTROL
The do-while program example
www.tenouk.com, © 50/77
PROGRAM CONTROL
Other Program Controls
continue keyword
continue keyword forces the next iteration to take
place immediately, skipping any instructions that may
follow it.
The continue statement can only be used inside a loop
(for, do-while and while) and not inside a switch-
case selection.
When executed, it transfers control to the condition (the
expression part) in a while or do-while loop, and to
the increment expression in a for loop.
Unlike the break statement, continue does not force
the termination of a loop, it merely transfers control to the
next iteration.
www.tenouk.com, © 51/77
PROGRAM CONTROL
Consider the following continue keyword example
// using the continue in for structure
#include <stdio.h>
int main(void)
{
int iNum;
for(iNum = 1; iNum <= 10; iNum++)
{
// skip remaining code in loop only if iNum == 5
if(iNum == 5)
continue;
printf("%d ", iNum);
}
printf("\nUsed continue to skip printing the value 5\n");
return 0;
}
www.tenouk.com, © 52/77
PROGRAM CONTROL
Next consider the following continue keyword example,
#include <stdio.h>
int main(void)
{
int iNum, nSum;
for(iNum=1, nSum=0; iNum<20; iNum++)
{
// test value, 0 or non-zero
if (iNum % 2)
{
printf("iNum %% 2 = %d (skipped)\n", iNum % 2);
// executed if the test value is non-zero
// and repeat the for statement
continue;
}
// executed if the test value is zero and repeat the for statement
nSum = nSum + iNum;
printf("iNum %% 2 = %d (summed up), nSum = %d \n", iNum % 2, nSum);
}
return 0;
}
www.tenouk.com, © 53/77
PROGRAM CONTROL
This loop sums up the even numbers 2, 4, 6, ... and stores the value in the nSum
variable.
If the expression iNum % 2 (the remainder when iNum is divided by 2) yields a
non-zero value (i.e., if iNum is odd), the continue statement is executed and the
iteration repeated (iNum incremented and tested).
www.tenouk.com, © 54/77
PROGRAM CONTROL
If it yields a zero value (i.e., if iNum is even), the
statement nSum = nSum + iNum; is executed and
the iteration continued.
When a continue statement executes, the next
iteration of the enclosing loop begins.
The enclosing loop means the statements between the
continue statement and the end of the loop are not
executed.
Try another continue example
www.tenouk.com, © 55/77
PROGRAM CONTROL
goto keyword
www.tenouk.com, © 56/77
PROGRAM CONTROL
Try the following C goto keyword program example
www.tenouk.com, © 57/77
PROGRAM CONTROL
exit() function
exit(status);
Status Description
0 (zero) The program terminated normally.
Indicates that the program terminated with some sort
1 (or non-zero)
of error. The return value is usually ignored.
www.tenouk.com, © 58/77
PROGRAM CONTROL
We must include the header file stdlib.h (cstdlib if
used in C++ code).
This header file also defines two symbolic constants for
use as arguments to the exit() function, such as,
#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1
Or
exit(EXIT_FAILURE);
www.tenouk.com, © 59/77
PROGRAM CONTROL
atexit() function
www.tenouk.com, © 60/77
PROGRAM CONTROL
atexit() function takes a function pointer as its
argument and functions with atexit() must have a
return type of void.
The functions passed to atexit() cannot take
parameters.
atexit() uses the heap (instead of stack) to hold
the registered functions.
The following program pushes three functions onto the
stack of functions to be executed when atexit() is
called.
When the program exits, these programs are
executed on a last in, first out basis.
61/77 www.tenouk.com, ©
PROGRAM CONTROL
system() function
www.tenouk.com, © 62/77
PROGRAM CONTROL
For example, using an argument with the system()
function,
char *command = "dir";
system(command);
After the OS command is executed, the program
continues at the location immediately following the
system() call.
If the command passed to the system() function is not
a valid OS command, a bad command or file name error
message is displayed before returning to the program.
The command can also be any executable or batch file to
be run.
www.tenouk.com, © 63/77
PROGRAM CONTROL
Try the following system() program example
www.tenouk.com, © 64/77
PROGRAM CONTROL
return keyword
www.tenouk.com, © 66/77
PROGRAM CONTROL
Callee
printf(“…“) definition
Caller
#include <stdio.h>
int main(void)
{
int nNum = 20;
www.tenouk.com, © 67/77
PROGRAM CONTROL
#include <stdio.h>
Caller
// prototype
void DisplayInteger(int);
void main(void)
{
int nNum = 30;
DisplayInteger(nNum);
}
Callee
void DisplayInteger(int iNum)
{
printf("The integer is %d\n", iNum);
}
www.tenouk.com, © 68/77
PROGRAM CONTROL
The return keyword example 1
www.tenouk.com, © 69/77
PROGRAM CONTROL
break keyword Program example on using break in for loop
www.tenouk.com, © 70/77
PROGRAM CONTROL
abort() and terminate() functions
Function Description
Abort current process and returns error code defined in
abort()
stdlib.h
Used when a handler for an exception cannot be found. The
default action to terminate is to call abort() and causes
terminate()
immediate program termination. It is defined in except.h
(Microsoft uses eh.h and only compiled in C++).
1. The syntax is,
1. abort() does not return control to the calling process. By default, it terminates
the current process and returns an exit code of 3.
2. By default, the abort routine prints the message:
www.tenouk.com, © 72/77
PROGRAM CONTROL
terminate() function calls abort() or a function you
specify using set_terminate().
terminate() function is used with C++ exception handling
and is called in the following cases:
1. A matching catch handler cannot be found for a thrown C++
exception.
2. An exception is thrown by a destructor function during stack
unwind.
3. The stack is corrupted after throwing an exception.
terminate() calls abort() by default. You can change this
default by writing your own termination function and calling
set_terminate() with the name of your function as its
argument.
terminate() calls the last function given as an argument to
set_terminate().
www.tenouk.com, © 73/77
PROGRAM CONTROL
The terminate() program example (C++)
www.tenouk.com, © 74/77
PROGRAM
EOF
CONTROL
We use EOF (acronym, stands for End Of File), normally
has the value –1, as the sentinel value.
The user types a system-dependent keystroke
combination to mean end of file that means ‘I have no
more data to enter’.
EOF is a symbolic integer constant defined in the
<stdio.h> header file.
The keystroke combinations for entering EOF are system
dependent.
On UNIX systems and many others, the EOF is <Return
key> or ctrl-z or ctrl-d.
On other system such as old DEC VAX VMS or
Microsoft Corp MS-DOS, the EOF is ctrl-z.
www.tenouk.com, © 75/77
PROGRAM CONTROL
The EOF program example. (Press <Enter> + <Ctrl+z>
for EOF)
If the value assigned to grade is equal to EOF, the
program terminates.
www.tenouk.com, © 76/77
End of C Program
Controls + Flow
Charts
www.tenouk.com, © 77/77