Sei sulla pagina 1di 19

Section 2.

Topics:

loops Boolean expressions


parallel input/output

selection structures
character variables

Introduction
Most programs require that some code, if not most of the program, is executed repeatedly
in a loop. For instance, a program to control the temperature in a plant will spend
most of the time repeatedly checking the temperature and making the required
adjustments. This type of continuous looping is common in embedded systems. In the
case of a PC, the program may prompt the user to repeat (the program) by entering Y or
N. Often a loop will only be executed if some condition exists (is TRUE). Also, it is
the case that data (tables in particular) requires loops to efficiently process them. The
following section describes the structures available in the C programming language.
The do-while loop
This loop structure is described with a simple example and flowchart as follows: Key
words are in bold to highlight them.
do

/* keyword at start of loop */

/* braces enclose the loop statements */


printf( this is in the loop\n\n)
printf(enter 1 if you wish to repeat the loop)
scanf(%d,&input)

}
while (input = =1);

/*end of loop*/

In this case while the value entered and stored in the variable input is 1, the loop is
repeated. The expression in brackets is known as a Boolean expression (see following
section) and evaluates to be TRUE or FALSE. Thus, we could describe the loop as,
do

{ LOOP BODY}

while (EXPRESSION IS TRUE)

17

FLOWCHART for do-while loop


ENTER LOOP

LOOP STATEMENTS

TRUE
Boolean
Express

FALSE =>EXIT LOOP

The loop statements may be any amount of program code, perhaps most of the program.
Boolean Expressions
The Boolean expression is used in the above structure to decide if the loop is to repeat
and as previously stated it must be TRUE or FALSE. It is constructed using the relational
operator = = which determines equality. In the example the = = checks if the value on
the left-hand side of the operator is equal to the value on the right hand side. If they are
equal then the expression is TRUE.
To avoid confusion with the numbers 1 and 0, which are associated with Boolean logic,
the words true and false are used when describing the condition of the expression.
However, when such an expression is evaluated, the resulting true/false result may be
assigned to an integer variable as the value 1/0. For instance , in the following code what
are the values printed?
int

true/false;
true/false = 7<12

/* variable with the unlikely name true/false */


/* since 7 is less than 12, the expression is true */

printf(the result is %d,true/false);

/*what is printed? */

18

ANS: Since 7 is less than 12, then the Boolean expression 7<12 evaluates to be TRUE
and thus the value 1 is assigned to the variable true/false and the result is 1 is printed.
This can be useful if you wish to construct a loop that repeats always. Consider the
following code
do
{
puts( does this ever stop?)
} while(1);

/* loop always */

This is commonly used for in C-code for embedded systems when the entire program is
repeatedly looping test the previous examples of code for yourself.
Relational and Boolean Operators
A relational operator checks the relationship between the data values on either side of it.
Most of them are common in mathematics. They are,
==

Is equal to

!=

Is not equal to

>

Is greater than

<

Is less than

>=

Is greater than or equal to

<=

Is less than or equal to

It is possible to construct longer Boolean expressions with several operators by using


Boolean (logical) operators. These are
&&

ANDING,

||

ORING,

19

NOT

For example,
do
{
/* some process involving fans and heaters */
}
while ( temp<max && temp>min );
Note that the precedence of the AND operator is lower than that of the relational
operators. If you forget the rules of precedence then use brackets to clarify matters, in any
event it is often easier to read if they are used ( (temp<max) && (temp>min) )
EXERCISE: 2.1
Modify the my_sound function (see the exercise in previous section) to repeatedly read a
single digit number (1-9) from the keyboard and make a sound at a frequency which is a
multiple of that number i.e., multiply the value entered by a another value such as 400. To
exit the loop the user may enter the value 0. This is the condition checked for in the
Boolean expression. Also, permit the user to select the duration of the sound before the
loop is entered. Remember to save the previous program in a new file before modifying
it, and construct the program with the proper heading description, comments and
description to user function as previously described.
EXERCISE: 2.2

Modification to 2.1

In using the scanf() function it is necessary to press enter after every number entry. To
avoid this problem use getch() to process the numbers as a character first. This requires
the declaration of a character variable e.g., input. When the character has been read and
stored in the variable input, use the atoi() function (ASCII character code to integer value
conversion function) to convert the value to an integer. For example,
frequency = atoi(&input); /*the int variable frequency is assigned a value*/

20

Ensure that you have copies of each of the above programs, and any other exercises,
stored in your account and on a floppy disk. Also, print your code - particularly if you do
not have a computer at home. It is your responsibility to maintain copies of your work.
The while loop
Basically the same as the do-while loop. In the do while loop the statements in the loop
are executed at least once before the condition is tested. However, if it is required that the
condition is tested before the loop (and possibly no execution of the loop) then use the
while loop. In this case if the condition is true then the loop is executed. and then the
condition is tested again.
FLOWCHART for while loop
while(Boolean expression)
Boolean
Express

{
FALSE

TRUE

loop statements

LOOP STATEMENTS

For instance,
/* CODE FOR SIMPLE SIREN SOUND */
char

input;

/*variable for character */

int

count, /* var. for loop counter */

printf(Enter y to ring siren or any key to continue );


input = getch();
count=0;

/*read keyboard character */


/*initialise to zero */

21

while ( (input = =y)&&(count<10) )

/*note two conditions to be met

{
sound(1000);
delay(4000);
sound(5000);
delay(4000);
count++;

/*note this new operator which automatically adds 1


to the value in counter- an increment

*/

}
In this example the loop should only be executed when the user enters y. Thus, the dowhile loop would not be appropriate since it would have executed at least once before
testing the condition.
The for loop
In the previous example the loop was repeated a certain number of times depending on
the values associated with the variable named counter. It is common to require this for
some loops, and no other type of condition such as the user input in the previous
example. As a result there is a particular type of loop specifically designed for this the
for loop. It is demonstrated below with a simple example,
Int

count;

for ( count=1; count<= 1000; count++ )


{
printf( The count is

%d, count);

etc.
}

22

The expression following the keyword for is actually 3 expressions, not just a Boolean
expression. They are
for (1. initialise expression 2. Boolean expression

3. update expression )

The while loop could have done the same job but would require the extra statements to be
written separately,
count= 1;

while(count<1000)
{

etc.
count++;

}
Note that the for loop is very flexible in terms of the individual expressions. For instance
the update expression could be something like

y=(x++*5)+50

Or perhaps
char

test;

for( test=a;test<=z;test++)
printf(The ASCII code for %c is %d,test,test);
Try this code and refer to the note about ASCII codes at the end of this section
Note: Any of the loops described may be quit from within the body of the loop by using
the break statement which is simply

break;

This might happen if some condition

occurs during the execution of a loop which requires the sudden break. Usually this is
associated with if structure described in the next section. An example is given later.

23

It is also possible to jump to the loop test condition ( for instance the Boolean
expression following the while keyword) from any point within a loop (not just when the
final statement in the loop executes). This requires the continue statement which is
simply

continue;

.This is normally found associated with an if statement.

The if statement
In countless programs it is required to make a simple decision to do something or not to
do it. This is similar to the while loop but not involving a looping process. The if
statement permits this. Consider the following example,
if (temp>10 && temp<40)
printf( Temperature is under control);
As in the case of the loop structures the conditional statement is based on a Boolean
expression. In the above example the print statement is only executed if the Boolean
expression is TRUE. As in the case of loops, any number of statements may be executed
conditionally by enclosing them in braces to create a compound statement. The flowchart
is
FLOWCHART for if statement
if (Boolean expression)
Boolean
Express

{
FALSE

TRUE

statement()s

STATEMENT(S)

24

Consider the previous sample of code for the siren sound. Suppose that the user is to be
asked two questions namely do they want to sound the siren and for how long. To keep
things simple it makes sense to only ask the second question if the first is true. Thus, a
possible rewrite of this code would be

char

input;

/* variable for character */

int

count, n;

/* var. for loop counting */

printf(Enter y to ring siren or any key to continue );


input = getch();

/*read keyboard character */

if (input = = y)

/*start of if clause */

{
printf(How many loops );
scanf(%d,&count)
for(n=0;n<count;n++)
{
sound(1000);
delay(4000);
sound(5000);
delay(4000);
}
}

/*end of for loop */

/* end of if clause */

Note the use of indentation to make this code easier to read


The next example can be used to determine the largest positive value that may be stored
in an int variable and demonstrates how a break statement may be used to exit the loop if
you get bored!

25

int

sum = 1,test = 0;

while(sum>0)
{
printf( Enter a positive integer or 0 to exit );
scanf (%d,&test);
if(test = = 0)

/*exit loop */

break;
printf(\n\n sum so far is %d,sum);
}/* end of while probably a good idea to comment at the end of a loop */
A simple variation on the basic if structure is the if else. This is for two-way selection,
which means that the program decides to do one action (if the Boolean expression is
true) or else do another action. In general the structure is.
if ( Boolean expression)
{ do this if the expression is TRUE }
else
{ do this if the expression is FALSE}
and the
FLOWCHART for if statement

TRUE

Boolean
Express

FALSE (ELSE)
}
STATEMENT(S)

STATEMENT(S)

26

EXAMPLE

A leap year occurs every 4 years?


/* year is an int variable storing a year value*/
if ( year%4= =0)
printf( The year %d is possibly a leap year,year);
else
printf( The year %d is a not leap year,year);

The code detail is not important but in many applications it is necessary to check
conditions, as you will see from the lab exercises It is also possible to have the following
structure using the if statement.
if (Boolean exp.)
{

true clause

else if (Boolean exp.)


{ true clause 2 }
else
{ false clause }
The previous example to determine a leap year was simplistic. The actual method checks
to see if the year is also divisible by 100. In this case the year is not a leap year. That is
unless it is also divisible by 400! If you follow? (This is because it does not exactly take
365.25 days for the earth to revolve around the sun) Thus,
if ( year%4! =0)
printf( The year %d is a not leap year,year);
else if( (year%100= =0) && (year%400!=0))
printf( The year %d is a not leap year,year);
else
printf( The year %d is definitely a leap year,year);
check you understand the logic is there a different way to do it?

27

The switch structure


This is used for to make one selection when there are several choices available and is
easier to use than too many if

else if

else if

statements. In this case the value of an

expression or some piece of data, like a character, is tested to see if it matches against
various possible cases. If it does match then the statements following this particular
case are executed. This is best illustrated with a simple example.
printf(Enter a letter A, B, C and I will tell you an amimal . );
scanf(%c,&char_input);

/* char_input is variable name*/

switch(char_input)

/* switch is a keyword like if */

{
case

printf(\n A IS FOR APE);


break;

case

printf( \n B IS FOR BEAR);


break;

case

printf(\n C IS FOR CAT);


break;

default
}

printf( \n Incorrect selection! !);

/* end of switch */

Note that the keyword case preceeds the character constant e.g., A ,and this is followed
by the the colon :

which is then followed by the statement(s) to execute. The break

statement ensures that if a match occurs then after the corresponding statements are
executed the overall statement is finised no more matches are checked for. If more than
one statement is to be executed when a match occurs then use compound braces { }
case

{
printf(\n A IS FOR APE);
printf( \n A IS FOR ARDVARK);
}

28

The default keyword is optional and followed by a statement that does not require a
match. The value that is appears after the case keyword may be an expression, possibly
Boolean, which evaluates to some value. This expression may depend on some other user
input.
case

4*temp_reading_value

etc.

In this case the value being matched is whatever is in the variable temp_reading_value
scaled by the value 4. A Boolean expression is also possible but not so common in
conjunction with the case. As an exercise draw a flowchart to describe the case statement.
An exercise is described later which requires the use of the case structure.
Parallel input/output
Most industrial/domestic control applications require data to be transferred in or out of
the basic system via a parallel port. Typically this is a device which has at least 8 lines for
data and some other lines for special purpose control operations. In the case of the PC
there is a readily available port which was initially developed for connecting printers.
This is connected to a 25 way connector at the back of the PC, which makes it convenient
for us to access. Note that the connector is not the port device, which is the chip inside
the PC box. There are more details concerning the hardware issues in that section of the
course. For programming purposes all we need to know is how to access data from the
port or send data to the port. In particular we need to communicate with the laboratory
application card as described in the lab class.
An address number identifies the port device. In fact there are two numbers, one is for
accessing the 8 data lines, usually referred to as the data port, and the other is for access
to the control lines, and referred to as the control port. (In fact the control port has more
functions than this but only concerns us in a minor way). In the case of the PC these are
at fixed addresses in the case of the PC at 0x378 (data) and 0x37a (control). The x in this
number indicates we are dealing with a hexadecimal number the standard way for
representing binary numbers such as the address numbers in a computer.

29

To make programming life simple, we normally define an easy to remember name to for
these addresses guess what? This is done in the following manner at the top of the
program.
#define

data_port

0x378 /*location of I/O ports on PC */

#define

control_port 0x37a

Thus, to refer to the ports we now can use the names instead of the difficult to remember
(and distinguish between) address numbers. The define is described in more detail in
the next section of notes.
So how do you actually send data to the port if it is connected to an output system such as
LEDS? The outport() function is used. In general this is constructed as follows
outport( port_address, data to be sent to port);
In the lab, when using the application board, it is necessary to write the value 0x01 to the
control port first (in order to output data rather than input see lab class). Then this is
followed by writing to the data port . In the following example the binary combination
10101010 is written to the data port as the hexadecimal value 0xaa.
outport(control_port, 0x01);

/*sets up system for output operation */

outport(data_port, 0xaa);

/* output data 10101010

*/

An example of this is given on a sheet handed out in the lab. In order to input data a
different control word must be written to the control port, 0x20. Then the inport()
function can be used to assign a value, at the 8 data lines, to a variable in the program.

30

For instance, to read the status of the switches from the lab application board and store
this in a variable the following code is required.
int

switch_status;

outport(control_port, 0x20);

/*sets up system for output operation */

switch_status=inport(data_port); /* data read from port */


Exercise:

Simulate home alarm system using application board.


See lab for details.

Example:

Waveform generator.

The application board has a digital-to-analogue (DAC) converter system that has an 8-bit
input. This can be written to from the parallel port of the PC to generate analogue
waveforms signals using software. For example, a sawtooth (ramp) waveform can be
generated with a simple counter and loop structure (see below).
The minimum and maximum output from the DAC corresponds to digital inputs 00 H and
FFH respectively. (The actual voltages at the output are approximately 0v and 2.5 v).
Clearly the maximum frequency of the waveform is determined by how quickly the
outputs can be generate by the PC and how fast the DAC can convert this data (which of
these is the determining factor?). Assuming we need to change the frequency then to
values slower than the maximum then a simple delay can be included in our loop as
shown in the flowchart below. How would the peak-peak voltage the output of the DAC
be changed.
ANS: YOU WRITE
ALSO DRAW A BLOCK DIAGRAM ON THE BACK OF THIS PAGE

31

Flowchart for ramp function

START

Counter set to zero

Output
counter to
port

DELAY
INCREMENT
COUNTER

YES

Cou
nt<
FF

TO
TOP

The program code that follows asks the user to select the delay initially.
How would a triangle waveform be constructed? Draw the flowchart.
Is it possible to construct a function that gives the user the option of running a ramp or
triangle waveform? Draw flowchart.
The code for the above flowchart follows. Note that you should write this as part of a
total program with a main function that calls the ramp function.

32

void ramp(void)
{
int

ramp_counter;

int

del_val=500; /*this value may have to be changed as you test prog*/


/*it is used for controlling the delay */

outport(control_port,0x20); /* set up system for output operation */


do
{
ramp_counter=0;

/*clear counter */

do
{
outport(data_port,ramp_counter); /*OUTPUT TO DAC */
delay(del_val);

/*this will control the speed */


/* i.e., the frequency

*/

ramp_counter++;
}
while(ramp_counter<256) /* why 256???? */
}
while(1);
}

/* loops forever */
/* end of function */

The above code loops forever. Is there a simple way to allow the user to stop the program
looping forever? Hint: What input devices are on the application board?
NOTE: The DAC on the application board must be selected.

33

What does the following code produce on the output of the a DAC.
do
{
ramp_counter=0;

/*clear counter */

do
{
outport(data_port,ramp_counter);
delay(del_val);
ramp_counter++;
}
while(ramp_counter<256) /* why 256???? */
for(ramp_counter=255;ramp_counter>-1;ramp_counter--)
{
outport(data_port,ramp_counter);
delay(del_val);
}
}
while(1);

/* loops forever */

How would the above code be modified to allow the user to select either a ramp or what
is produced at the output?

34

35

Potrebbero piacerti anche