Selection Structures

Read Complete Research Material

SELECTION STRUCTURES

Selection Structures



Selection Structures

We will learn about several different forms of decision patterns, of loop patterns, and about how and when to use these different patterns.

This is problem-solving … developing tools and recognizing when to use them.

Decisions in programs

Example 1:

if (toupper(dchar) == 'M') then

draw_Mfig();

else

draw_Ffig();

How does this work - i.e., what does it do? We need to read it out loud!!

Once you can read this, you can read and understand almost everything in Chapter 4 of the book. (But of course, that is no excuse for not reading the Chapter. There is a lot of other information in there that you need to know.)

Decision structures

Allow programs to follow different courses of action or execute different tasks depending on the data values

Psuedo-code examples of conditional statements and branching

Example 2: if x is not equal to zero then

divide y by x

This is a single-alternative decision pattern.

It can be read as follows: If the condition "x is not equal to zero" is TRUE, divide the value of y by the value of x

Otherwise (else), the condition "x is not equal to zero" is FALSE. In this case, no alternative action is taken because no alternative actions have been specified if the statement is FALSE

Example 3: if x is not equal to zero then

divide y by x

else // otherwise

display an error message

This is a double-alternative decision pattern.

We read it as follows: If the condition "x is not equal to zero" is TRUE, divide the value of y by the value of x

Otherwise, the condition "x is not equal to zero" is FALSE. Display an error message.

Thus, the only possible values of the expression “x is not equal to 0” (or in C,

x != 0) are true or false.

What are the possible values for the integer expression

2 * k / (3 + m)

What are the possible values for the float expression

2.5 * x / (3.75 + w)

Example 4: if x is less than zero then set y equal to -1 else if x is equal to zero then set y equal to 0 else

set y equal to 1

This is a multiple-alternative decision pattern.

We can read it as follows: If the condition "x is less than zero" is TRUE, set the value of y to -1

Otherwise, the condition "x is less than zero" is a FALSE. So if the condition "x is equal to ...
Related Ads