Packet 3-16 - Control Structures

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 59

COP 3223

Slide Set #3
Program Control Structures

Basic Program Control


Structure

Most programming languages implement


sequential execution - one statement after
the other.
Unless told otherwise, the processor will
execute statements in the program in this
manner.
But there are some instructions that
redirect the execution to some other
statement(s).

The GOTO Statement

Certain instructions permit shift of


control away from the next statement to
something else.
The first and most basic of these is the
GOTO statement.
GOTO is a basic machine level
instruction,
- but its use in high level languages s
NOT desirable

Basic Program Control


Structure

Programs can be written without explicit


GOTO statements by the programmer
The basic computational structures in
High Level Languages are:
- The Sequential Structure
- The Selection Structure
- The Repetition Structure
This is called Structured Programming

The Sequential Structure

The sequential structure is the most basic


structure in computer programming, and
the basis of instruction sequences.
It is a block of code that is to be executed
in order of appearance execute the next
statement after the one above
Unless told otherwise, the processor
executes the next instruction in the
instruction sequence.

The Selection (or Conditional)


Structure

The Selection Structure

Many times decisions are to be made


depending on the answer to a question.
- Called Conditionals
We tend to use rules: If X is true, then Y
is also true (or do something specific).
- Called deductive logic
More complexly: If A and B are true, then
C is true (or do something specific).
Equally complexly: If A or B are true, then
F is true (ordo something specific).

The Selection Structure

More specifically in the context of


computer programming,
If A evaluates to True,
- then execute the following statement
(or block of statements)
- Else execute another statement (or
block of statements)
- Else, execute this statement (or block
of statements), or dont execute
anything at all.

The Selection Structure

Three types of selection structures


The if structure: executes a statement
only if the condition is true. If not true,
then skips that statement and continues:
- Also called single selection structure.
The if/else structure: executes a
statement only if the condition is true; if
not true, then it executes a different
statement.
- This is called a double selection
structure.

The Selection Structure

The if/elseif//else structure:


executes a statement if the first condition
is true; if not true, it evaluates a second
(and third, and fourth ) condition. When
the first of those is true, executes the
corresponding statement. If none, then it
will execute the else (which could be
nothing)
- This is called the multiple select.
structure.

The Selection Structure

There is another multiple selection


structure that does the same thing as the
if/elseif//else structure in a more
structured manner.
The switch structure: selects among
several different actions
- To be discussed later because it has a
very different syntax
Now for syntax and examples:

Single Selection Structure

Say we want certain code to be executed


only if certain conditions are met
The general form is:

if ( <condition> )
{
<code that is executed only if the
condition is true>
}
else
{
<code that is executed only if the
condition is false>
}

Single Selection Structure


More formally, it has the following syntax:
if (test)
<action>;
If the action is more than one statement,
then:
if (test){
<action1>;
<action2>;

Single Selection StructureExample


The following is an example of the if
structure:
if (grade >= 60)
printf(Passed\n);
<next statement>;
Note that nothing is printed if the grade < 60,
as it goes to the <next statement>,
whatever that may be.
Note also that there is no ; after the test
statement, nor after the brackets

Short-Circuit Evaluation

Weird things happen when statements in the test


condition are anded or ord
The Boolean operators && and || use what is called
the Short-circuit Evaluation
This means that C only evaluates all individual
expressions if it absolutely has to. For example,
- FALSE && <anything> false,
- TRUE || <anything> true
so C won't evaluate the rest of the expressions
when unnecessary
- C always evaluates the left-most side of && and
|| first, and then continues only if essential

Short-Circuit Evaluation

For example:
Lets say
float a = 10.0;
float b = -10.0;
if ( (a == 10.0) || (b > 0.0) )
printf(whatever);
The program will never evaluate the
(b>0.0) expression because (a==10.0)
turns out to be true, making the
compound expression true.

Short-Circuit Evaluation

Likewise,:
float a = 10.0;
float b = -10.0;
if ( (a != 10.0) && (b > 0.0) )
printf(whatever);
The program will never evaluate the
second expression because the first
turns out to be false, making the entire
expression false.

Short-Circuit Evaluation

A practical application of short-circuit


evaluation is that you can ask questions
that might cause a crash otherwise
Example:
int x;
if (15/x)
- is not safe because if x equals to 0, this will
blow up and crash the program, cause one
cannot divide by 0.
if ( (x==0) || (15/x) )
- is safe, because if x is zero, then the || will
come out true and it won't try to divide 15 by
zero If x is not 0, it will go ahead and do 15/x

Double Selection Structure

Allows the programmer to specify an


alternative statement to execute if the test
is not true. The syntax is:
if (test)
<statement>;
else
<alternative statement>;
Note the location of the semicolons!!

Double Selection Structure


If more than one statement comprises the
action or alternative actions, then we can
use a brace to group several statements.
if (test) {
<statement 1>;
<statement 2>;
}
else {
<alt. statement1>;
<alt. Statement2>; }

Double Selection Structure


An example of the IF-ELSE structure is as
follows:
if (grade >= 60)
printf(Passed\n);
else
printf(Failed\n);

Multiple Selection Structure

IF-ELSE structures can be nested so as to


perform other tests before another action
is executed. The syntax is:
if (grade >= 90)
printf(A\n);
else if (grade >= 80)
printf(B\n);
else
printf(Failed\n);
Note the implicit shortcut here!!
- (Explain)

Simplified Conditional Structure

The Single and Double selection


structures have a simplified version.
Its syntax is:

<control expression> ? <then statement>


: <else statement>

Example:
m>0 ? m+5 : m*2;

But like the GOTO Do NOT use it in this class!


- Ever!

The break Statement

Before describing the switch structure,


we must define the break statement
The break statement is important in the
definition of control structures.
When executed in a selection (and
repetition also) control structure, causes
an immediate exit from that structure, to
the first statement after the structure.
- By structure, it is meant block of code

switch statements

Sometimes you might want to write


something along these lines:

if(x == 1) {
<statement 1>;}
else if(x == 2) {
<statement 2>; }
else if(x == 3) {
<statement3>; }
else if (x == 4)
..
else {
<statement n>; }

switch statements

Switch statements are for just that purpose


The equivalent switch statement would be

switch(controlling expression)
{
case label_1:
<statement 1>;
break;
case label_2:
<statement 2>;
break;
case label_3:

default:
<statement n>;
}

switch statements

The label placed after the keyword case


represents the value returned by the control
expression when it is evaluated.
If the control expression evaluates to the label,
then if that is a match, the code (block)
underneath up to the break; statement is
executed.
Note that it's important to have a break at the
end of each case
-

If you don't put the break, the execution will continue


on into the next case

switch statement example

Lets write a simple program that uses the


switch statement
Use a switch statement to take an int
and prints out the word equivalent of the
integer, for numbers 1 through 3.

Sample Program with switch


main()
{
int n = 2;
switch (n)
{
case 1: {
printf(one\n);
break; }
case 2: {
printf(two\n);
break; }
case 3: {
printf(three\n);
break;
}

Error In Code

What is wrong with the code in the


program written before?

Repetition Structures

Repetition Structure

Sometimes we want to execute the same


block of statements several times
Repetition structures permit an action to
be repeated several times, as in a loop,
either
- as long as a specific condition is true
(called sentinel controlled)
- for a fixed number of times (called
counter controlled)

Repetition Structure

There are three of them:


- The for loop: counter control (entry
condition)
- The while loop: sentinel control
(entry condition)
- The do/while loop: sentinel control
(exit condition)
Lets now discuss sentinel/counter
control and entry/exit condition

Stopping Criteria

Sentinel control: The stopping criteria is set for a


sentinel variable and its value is checked at
every iteration. When the value reaches that
stopping criterion, the looping ends.
Counter control means that a variable is set that
counts the number of loops. When the count
reaches a pre-set number, the loop exits.
Entry condition is that the stopping criteria is
checked at the start of the loop. If the criterion is
met, the loop is not executed.
Exit condition means that the stopping criterion
is checked after the loop statements are
executed. Guaranteed to run at least once

The break Statement

The break statement is also important in


the definition of repetition structures.
When executed in a repetition control
structure, causes an immediate exit from
that repetition structure, to the first
statement after the structure.
It is important for use in some of the
repetition structures.

The continue Statement

Like the break, the continue statement


affects the execution of repetition
structures.
Causes the processor to skip the
remaining statements in the loop body,
but goes on to the next iteration.
Typically associated with a selection
structure.

The continue Statement

In the for loop, continue; causes the


increment expression to be executed and
the loop continuation test is evaluated
thereafter.
In the while loop, the loop continuation
test is evaluated immediately after the
continue statement.
In the do/while loop, the loop continuation
test is evaluated immediately after the
continue statement.

The for Structure

The most common loop structure in C


- It is counter controlled.
Very prescriptive and formalized
Requires control variable to be defined.
Handles details of running the loop
automatically.
Carries out the loop continuation test
immediately after the counter is
incremented (at top of loop).

for loops
for(<init>; <condition>; <increment>)
{
<statements>;
}

For loops work like so:


1. Executes the init statement
2. Evaluate the condition. If it's false, exit the
loop,
1.
otherwise go on to step 3
3. Execute the statements inside the loop
4. Execute the increment statements
5. Go back to step 2

The for Structure

Requires the following information:


- Name of the counter variable
- Initial value of counter variable
- Increment or decrement of the counter
- Final value of the counter variable.
Defines exit conditions.
Continues as long as test is true.
Programmer must ensure that the control
variable will converge to the final value.

Infinite Loops

One of the most hateful bugs in computer


programs.
- Truly hateful
Causes computation to continue forever
because end condition is never reached
The program wont crash unless it runs
out of memory
It will just go on and on and on and .

The for Structure


More formally, the syntax for the for loop is
as follows:
for (<ctrl var> = <init val>;
<ctrl var> is different from
<final value>
<incrementation def>) {
<body of loop>;
}

The for Structure

Final value and the increment can be


mathematical expressions.
The increment can be negative (a
decrement).
If loop continuation condition is initially
false, body will never be executed.
- Entry test
Counter variable does not normally used
in body of loop, but can be,
- such as for arrays (later).

Shorthand Assignment

Statements of the form:


x = x <operator> <number>
are so common that we have special notation:
x <operator>= <number>
Examples
- x += 5; means x = x + 5;
- y *= 3; means y = y * 3;
- z -= 1; means z = z 1; or z--;

For Loop Example


Example:
Say we want to add all numbers between 0
and 100. Our simple program is as such:
int main()
{
int sum = 0, n;
for (n=0; n<=100; n++)
sum = sum + n;
printf(Total = %d, sum);
return 0;
}

The for Structure


Example: What if I want to increment by 2?
int main()
{
int sum = 0, n;
for (n=0; n<=100; n+=2)
sum = sum + n;
printf(Sum = %d, sum);
return 0;
}

The while Structure

Much less structured than the for loop.


Specifies action to be repeated as long as
a specific condition remains true.
The loop continuation condition is bultin, but variable initialization and
updating has to be explicitly
programmed.
Checks for loop continuation at the
beginning of the loop body.

The while Structure

Basically a sentinel controlled loop, but


can also be used as counter controlled.
Can be used in place of the for loop in
most cases, but no real reason to do so.
One exception is when a continue is
used and the increment/decrement
expression is placed after the continue
statement
- Could be trouble. Unless that is really
what you want to do

The while Structure


More formally, the syntax is as follows:
cont_var = <initial val>;
while (loop continuation test on cont_var)
{
<statement1>;
<statement 2>;
<statement 3>;
<update cont_var somehow>;
}

The while Structure


Example:
int product = 2;
while (product <= 1000)
{
product = 2*product;
printf(whatever > %d, product);
}

Loops

For loops and while loops are equivalent

for(<init>; <continuing condition>; <increment>)


{
<statement>;
}

Is the same as:


<init>;
while(<end condition>) {
<statement>;
<increment>;
}

The do/while Structure

Same as the while loop, with the


exception that the loop continuation test
is done after the body of the loop has
been executed.
Thus, the body of the do/while loop is
guaranteed to be executed at least once.
Braces not required if only one statement,
but typically used anyway for clarity.

Do-while loops

The format of a do-while loop is:


do
{
<statements>
} while(<continuing condition>);
It works like so:
1. Executes the statements inside the braces
2. Evaluate the condition. If it's false, end the
loop,
1. otherwise go back to step 1

The do/while Structure


More formally, The syntax is as follows:
cont_var = <initial val>;
do {
<statement1>;
<statement 2>;
<statement 3>;
} while (loop continuation test on
cont_var);

The Comma Operator

The comma operator allows two


statements to execute on the same line,
like so: i = 0, j = 0;
In for-loops, though, it can be useful:
for(i = 0, j = 0; i + j < 20; i += 2, j++) {
<statements>;
}

Normally, you shouldn't do this, but in


some cases it is appropriate

Interesting Note

C++ allows the declaration of the counter


variables directly within the specification
of the repetition structure.
C (generally!) does not.
Example:
for (int n=0; n>=10;n++)
Same for the while and do/while.
In (traditional) C, the declaration must be
a separate statement

Control Structures - Summary

C only has seven control structures.


Structures are single-entry/single-exit,
which facilitate programming.
Repetition structures can be nested
within one another at an arbitrary level of
nesting.
This nesting can cause combinatorial
explosion.
-

Another nasty in computer programming

Random Numbers

To generate random numbers, use the


function
int rand();
found in <stdlib.h>
A call to rand() returns an integer between
0 and RAND_MAX (32,767 on my computer)
Usually, we're interested in smaller random
numbers,
- so mod divide by the maximum number
desired (explain)

Random Numbers

Computers always operate deterministically, so


these numbers aren't truly random
- but they look random enough for most
purposes
If you don't seed the random number generator,
rand() will produce the same sequence of
random numbers every time you run the program
To seed the random number generator, call
srand(time(NULL)); once at the start of your
program and use the preprocessor directive
(#include <time.h>) so you can use the time
function)

You might also like