Algonquin College Computer Studies CST 8110 Introduction to Computing

Ian D. Allen

Rideau B215A

idallen@freenet.carleton.ca

 

Welcome to Algonquin College

Focused on Your Career

Customized Training

Workplace Skills

Quality Instruction

Instructor Ian D. Allen

B.A.
Honours Psychology
University of Waterloo
1980

MMath
Computer Science
University of Waterloo
1985

Contact Information

Ian D. Allen

idallen@freenet.carleton.ca

Rideau B215A

Telephone (727-4723) x5949

Office hours

see my office door

Notes and Course Outlines

online:

http://idallen.com/teaching/ http://www.algonquincollege.com/cst/8110/

in library, if needed

Things You Should Know

Your Student Number

marks are grouped by number

Your Course Number

CST8110 section 010 - Ian Allen

Course Times

Lectures: two hours / week

010 Mon 14:00-14:50 RB163

    Fri 11:00-11:50 RB163

Labs: two hours / week

011 Wed 14:00-15:50 RC205

012 Thu 11:00-12:50 RC204

013 Thu 14:00-15:50 RC205

CST 8110 Course Outline

course outlines are available online

please review academic policies

withdrawing

repeating courses

probation

academic discipline

Course Learning Requirements

Lectures

2 hours Class

2 hours Lab (mandatory)

Evaluation / Earning Credit

35% in-class tests & quizzes

40% final examination

25% assignments

Assignment Late Penalty

up to one week ... 20%

after one week ... 100%

Marking Scheme

A: 80-100 
An outstanding level of achievement has been consistently demonstrated.

B:  70-79 
Achievement has exceeded the required level.

C: 60-69
 Course requirements are met.

D: 50-59
 Achievement is at a marginal level.  Consistent, ongoing effort is required for continuing success in the program.

CST 8110 Major Academic Events

Midterm #1

in class

Monday, June 2, 1997

Midterm #2

in class

Friday, July 4, 1997

Statutory Holidays

three

Final Exam Period

August 18 - 22 (inclusive)

How to Succeed in this Course

Do the assignments

understand the theory

apply the theory

practice

Attend Lectures and Labs

remember your diskettes

back up your diskettes!

be on time

ask questions

Learn the tools

memorization isn’t enough

Lab and Lecture Dialogue Protocol

There are no dumb questions

ask

ask

ask

Stop me if I go too fast

assist me in knowing your learning styles

Do your homework

use class time to ask questions

Lab and Lecture Dialogue Protocol

Be here

Lab attendance is mandatory

Be on time

use class time well

Listen

to me

to questions (and answers!)

Focus

don’t distract me or others

don’t distract yourself

Required for Laboratories

Diskettes

3 ½ inch

high density (HD)

disks for assignments

spare disks for back-up

You

sign in

please be on time

attendance is mandatory

missed labs result in no course credit: see the course outline

CST 8110 Assignment 0

Generate your accounts

you must do this for e-mail

see the Student Monitors

Labs: C204, C205, C207, +?

Choose a good password

you can remember it

other people can’t guess it

Use your account!

ask for assistance

find the course outline

send your neighbour some e-mail

How a Computer Works

Addressable Memory

composed of binary digits: bits

bits grouped by 8 into bytes

each byte has an address

bytes grouped into words

Central Processing Unit (CPU)

reads bytes and words from memory

operates on the bits (adds, shifts, etc.) based on the numeric instruction code also read from memory

writes bytes and words into memory

Input and Output (I/O)

printers, terminals, modems, etc.

Computer Programs

are simply numbers stored in the main memory of the computer

the numbers have special meaning when read by the Central Processing Unit (CPU)

the CPU reads the numbers as instruction codes that tell it to perform some actions

the action taken by the CPU upon reading a numeric instruction code from memory depends on the type of the CPU, e.g. PC, Macintosh, Atari

Problem Solving and Stepwise Refinement

Text: Section 1.5 - 1.6

Blue Book: Stepwise Refinement (p. 12-24)

Problem Solving:

Define the problem

Determine the Outputs

Determine the Inputs

Derive the Algorithm

Stepwise Refinement of an Algorithm:

Steps are followed in order

Each stepwise refinement is indented

Each indentation explains how to do the higher-level step above it

No more than half a dozen steps at any level of indentation

Don’t focus on detail and refinement until all the higher-level steps are understood

Problem: Feed Me

Get Food

Obtain Money

go outside and unlock bicycle

pedal over to bank machine and get cash

Go Shopping

pedal to local market with cash

purchase macaroni and cheese dinner

Come home

put cheese dinner ingredients in bicycle bag

cycle home (lock bike; go inside with food…)

Prepare Food

Prepare Water

add salt to water

heat water on stove until boiling

Prepare Macaroni

place macaroni in boiling water

wait until cooked just right

drain macaroni

Add Magic Cheese Sauce

mix magic cheese powder into macaroni

mix butter and milk into macaroni

Serve Food

Set table for one

Turn on nice dinner music

Light candles

Place pot of food on dining room table

Put some food from pot onto plate

Eat Food

Place fork into delicious food

Lift fork with food into face

Repeat until food is gone or face is full

Algonquin Pseudocode Basics

Blue Book: p.10-11,
Appendix A

Use pseudocode to express the details of your Algorithms

Pseudocode is English text combined with key programming words

Less strict than programming languages

More strict than English

Algonquin Pseudocode Rules

Pseudocode should be well structured and pleasing to the eye.

Each statement must be concise.

Omit words such as "the" and "and".

Start each line with a capital letter.

Use lower case English with upper case programming keywords.

Keywords are used for:

input and output: GET, PUT

decisions: IF, ELSE

looping: FOR, WHILE

comparison: EQUAL, LESS

Algonquin Pseudocode Keywords

Input:

GET

Output:

PUT

Decisions:

IF …  ELSE … ENDIF

Looping:

FOR … ENDFOR

WHILE … ENDWHILE

DO … WHILE

Proper indentation must be used for each type of statement.

Indent three spaces for all compound statements and all statements within loops.

C Language Basics

Text: Chapter 2

Number Systems

Natural Numbers

1, 2, 3, ...

Whole Numbers

0, 1, 2, 3, ...

Integers

… , -2, -1, 0, 1, 2, …

Rational Numbers

22/7, 1/3, etc.

Irrational Numbers

PI=3.14159265358979323…

Positional Notation Base 10

4,295 base 10

4 x 10 to the power 3 = 4,000

2 x 10 to the power 2 = + 200

9 x 10 to the power 1 = +  90

5 x 10 to the power 0 = +   5

                       ------

  as a base 10 number = 4,295

3.1415 base 10

3 x 10 to the power  0 = 3.0

1 x 10 to the power -1 = +.1

4 x 10 to the power -2 = +.04

1 x 10 to the power -3 = +.001

5 x 10 to the power -4 = +.0005

                        -------

   as a base 10 number = 3.1415

Base 8 Octal

7162 base 8

7 x 8 to the power 3 = 3,584

1 x 8 to the power 2 = +  64

6 x 8 to the power 1 = +  48

2 x 8 to the power 0 = +   2

                      ------

 as a base 10 number = 3,698

2.1730 base 8

2 x 8 to the power  0 = 2.0

1 x 8 to the power -1 = +.125

7 x 8 to the power -2 = +.109375    

3 x 8 to the power -3 = +.0058593

0 x 8 to the power -4 = +.0000000

                       ----------

  as a base 10 number = 2.2402343

More Digits for Base 16 - Hexadecimal

Base  2 digits: 0,1

Base  8 digits: 0,1,2,…,6,7

Base 10 digits: 0,1,2,…,8,9

Base 16 digits:
0,1,2,…,8,9,A,B,…,E,F

A is a digit with value 10

B is a digit with value 11

C is a digit with value 12

D is a digit with value 13

E is a digit with value 14

F is a digit with value 15

F + 1 = 10 base 16

D + E = 1B base 16

C - 7 =  5 base 16

F - E =  1 base 16

Base 16 Hexadecimal

719F base 16

7 x 16 to the power 3 = 28,672

1 x 16 to the power 2 = +  256

9 x 16 to the power 1 = +  144

F x 16 to the power 0 = +   15

                       -------

  as a base 10 number = 29,087

F.1C3 base 16

F x 16 to the power  0 = 15.0

1 x 16 to the power -1 = + .0625

C x 16 to the power -2 = + .046875

3 x 16 to the power -3 = + .000732

                        ----------

   as a base 10 number = 15.110107

Any Base to Base 10

Conversion of a whole number in any base to decimal (base 10):

Multiply each digit in the number by the base raised to the power corresponding to the position of the digit in the number

The rightmost digit is multiplied by the base raised to the power zero, next digit is multiplied by the base raised to the power 1, etc.

Sum the resulting products

Base 10 to Any Base

Left-to-Right:

Start dividing by the largest power of the base that is less than or equal to the value; continue with all the lesser powers of the base in order.  Write down the quotient digits from top-to-bottom and left-to-right.

Right-to-Left:

Keep dividing by the base until the quotient is zero.  Write down the remainder digits in order from top-to-bottom and right-to-left.

Base 10 to Binary: Left-to-Right

Start dividing by the largest power of the base that is less than or equal to the value; continue with all the lesser powers of the base in order:

1933 base 10 to binary (base 2):

1933 div 2**10 = 1 rem 909

 909 div 2**9 = 1 rem 397

 397 div 2**8 = 1 rem 141

 141 div 2**7 = 1 rem  13

  13 div 2**6 = 0 rem  13

  13 div 2**5 = 0 rem  13

  13 div 2**4 = 0 rem  13

  13 div 2**3 = 1 rem   5

   5 div 2**2 = 1 rem   1

   1 div 2**1 = 0 rem   1

   1 div 1**0 = 1 rem   0

= 11110001101 binary
 ( top-to-bottom and left-to-right )

Base 10 to Hex: Left-to-Right

Start dividing by the largest power of the base that is less than or equal to the value; continue with all the lesser powers of the base in order:

1933 base 10 to hex:

1933 div 16**2 =  7 rem 141

 141 div 16**1 =  8 rem  13

  13 div 16**0 = 13 rem   0

= 78D hex (base 16)
 ( top-to-bottom and left-to-right )

Note that 13 is written as the digit ‘D’ in hexadecimal notation.

Base 10 to Binary:  Right-to-Left

Keep dividing by the base until zero; write all the remainder digits down from right-to-left:

1933 base 10 to binary (base 2):

1933 div 2 = 966 rem 1

 966 div 2 = 483 rem 0

 483 div 2 = 241 rem 1

 241 div 2 = 120 rem 1

 120 div 2 =  60 rem 0

  60 div 2 =  30 rem 0

  30 div 2 =  15 rem 0

  15 div 2 =   7 rem 1

   7 div 2 =   3 rem 1

   3 div 2 =   1 rem 1

   1 div 2 =   0 rem 1

= 11110001101 binary
( top-to-bottom and right-to-left )  

Base 10 to Hex:  Right-to-Left

Keep dividing by the base until zero; write all the remainder digits down in order from top-to-bottom and right-to-left:

1933 base 10 to hex:

1933 div 16 = 120 rem 13

 120 div 16 =   7 rem  8

   7 div 16 =   0 rem  7

= 78D hex (base 16)
( top-to-bottom and right-to-left )  

Note that 13 is written as the digit ‘D’ in hexadecimal notation.

Between Binary, Octal, and Hexadecimal

Bases 2, 8, and 16 are easily related

Binary: Consider a two-byte value:

10110100 11000110

Octal: group/ungroup by 8’s (3 bits)

1 011 010 011 000 110

1   3   2   3   0   6

=> 132306 base 8

Hex: group/ungroup by 16’s (4 bits)

1011 0100 1100 0110

   B    4    C    6

=> B4C6 base 16

1323068 = B4C616 = 46,27810

Conversion Summary Sheet

Decimal to other bases

For positive or unsigned numbers:

Use the right-to-left or left-to-right dividing-by-the base method

Other bases to decimal

For positive or unsigned numbers:

Multiply each digit by its corresponding power of the base

Add up the products

Among binary, octal, and hex

For all bit patterns, whether signed or unsigned, just group and ungroup bits:

Octal: group/ungroup by 3 bits

Hex: group/ungroup by 4 bits

Short Cuts in Number Systems

Note that 0111111 base 2 is one less than 1000000 base 2

Note that 0777 base 8 is
one less than 1000 base 8

Note that 0999 base 10 is
one less than 1000 base 10

Note that 0FFF base 16 is
one less than 1000 base 16

Numbers to Characters 7-Bit ASCII

American Standard Code for Information Interchange

An interpretation of 7-bit numbers

7 bits means 128 values (characters)

the value of  '  '  (space) = 32

Upper-case:  'A' = 65  'Z' = 90

Lower-case:  'a' = 97  'z' = 122

ASCII characters are 7-bit numbers:

'A' + '  ' = 'a' (= 97)

'B' + '  ' = 'b' (= 98)

'a' + 2 = 'c' (= 99)

Unsigned 8-bit Integers

Consider one-byte (8-bit) integers:

2**8 = 256 possible numbers:

0000 0000   0016    0

0000 0001   0116    1

0000 0010   0216    2

0000 0011   0316    3

   . . .

0111 1110   7E16  126

0111 1111   7F16  127

1000 0000   8016  128

1000 0001   8116  129

1000 0010   8216  130

1000 0011   8316  131

   . . .

1111 1101   FD16  253

1111 1110   FE16  254

1111 1111   FF16  255

Signed (+/-) 8-bit Integers

Consider one-byte (8-bit) integers:

2**8 = 256 possible numbers:

0000 0000   0016    0

0000 0001   0116    1

0000 0010   0216    2

0000 0011   0316    3

   . . .

0111 1110   7E16  126

0111 1111   7F16  127

1000 0000   8016 -128

1000 0001   8116 -127

1000 0010   8216 -126

1000 0011   8316 -125

   . . .

1111 1101   FD16   -3

1111 1110   FE16   -2

1111 1111   FF16   -1

Signed (+/-) 16-bit Integers

Consider two-byte (16-bit) integers:

2**16 = 65,536 possible numbers:

000016         0

000116         1

000216         2

000316         3

. . .

7FFE16    32,766

7FFF16    32,767

800016   -32,768

800116   -32,767

800216   -32,766

. . .

FFFC16        -4

FFFD16        -3

FFFE16        -2

FFFF16        -1

Observations on Signed Integers

Since half the bit values are used for negative numbers, signed integers have half the positive range of unsigned integers

16 bit unsigned: 0 … 65,535

16 bit signed: -32,768 … 0 … +32,767

The most positive value and most negative value are adjacent bit patterns

adding one to the most positive value generates the bit pattern for the most negative value ("integer overflow")

the bit pattern for the most positive value is the complement of the bit pattern for the most negative value: 7FFF and 8000, 7FFFFFFF and 80000000

-1 is always "all bits turned on"

8 bits: FF

16 bits: FFFF

32 bits: FFFFFFFF

adding 1 to -1 turns all bits off: zero

Observations on Signed Integers II

The same bit pattern may be interpreted as either signed or unsigned.  We say N is a signed integer if, when we interpret N, we interpret all bit patterns with the sign bit set as negative numbers.

If N is a signed integer, then its bit pattern is to be read as signed, and the leftmost (top) bit is known as the sign bit.  If N is signed and the sign bit is set, the bit pattern will be interpreted as a negative number.

Note: If the sign bit is zero, the bit pattern has the same numeric value whether interpreted as signed or unsigned.

If the number is a signed number, zero is positive (the sign bit is not set).

Operations on Signed Integers

Negating signed binary, octal, hex

invert all the bits: 1 => 0,  0 => 1
(same as subtracting from -1)

then add 1

i.e.  -N = ((-1) - N) + 1

e.g. to negate C0F6 (negative):

= ((-1) - C0F6) + 1

= (FFFF - C0F6) + 1

= 3F09 + 1

= 3F0A (positive)

Converting negative decimal numbers

convert the positive equivalent

then negate it (using the above method)

e.g. to convert decimal -16,138

= -(16,138)  - make positive

= -(3F0A)  - convert

= C0F6  - negate

Operations on Signed Integers II

Numbers with the sign bit set

Only signed numbers can be negative, and negative only if the sign bit is set
e.g. C0F6, 80A7, FFFF

To convert signed, negative numbers from binary, octal, and hex to decimal

negate the number (make positive)

then convert to decimal

then change the sign

e.g. to convert signed C0F6 (negative)

= -(3F0A) - negate

= -(16,138) - convert

= -16,138 - change sign

e.g. to convert signed 10101010

= -(01010110) - negate

= -(86) - convert

= -86 - change sign

Conversion of Signed Integers

From signed, negative bit patterns to negative decimal numbers

negate the negative bit pattern to make it a positive bit pattern

convert the positive bit pattern to a positive decimal number

change the sign on the positive decimal number to make it negative again

From negative decimal numbers to signed, negative bit patterns

change the sign on the negative decimal number to make it positive

convert the positive decimal number to a positive bit pattern

negate the positive bit pattern to make it a negative bit pattern again

Floating-Point Numbers I

see "Scientific Notation" p.5 in the Algonquin CST8110 Blue Book

Floating-point numbers are stored as separate mantissa (fraction) and exponent

.31415926 E+1

Limits on the size of the mantissa and exponent limit the precision (accuracy) and range of floating-point numbers

precision:  # bits used in mantissa

1.234567 E1

1.234567890123456789 E1

range: # bits used in exponent

1.0 E38

1.0 E300

Floating-Point Numbers II

Arithmetic Overflow: Some real numbers are "too big" to represent in a given number of bits of storage:

e.g.  1.0 E+500

Arithmetic Underflow: Some real numbers are "too small" to represent using a fixed number of bits:

e.g.  1.0 E-500

Numbers nearer to zero are closer together than numbers with larger exponents:

because the mantissa multiplies the exponent; successive numbers in the mantissa multiply the larger exponents, and the numbers space farther

Cancellation Error: Adding a relatively small number to a large one may not change the large one if the difference in magnitude is greater than the precision:

e.g. 1.0E30 + 1.0E1 = 1.0E30

the number with the smaller exponent has no effect if the magnitude of the two numbers differs by more than the number of digits of precision

the mantissa may not have enough precision to reflect the addition of such a relatively small number

Floating Point Limitations

Binary values between 0 and 1 are sums of products of negative powers of two; they do not always accurately express sums of products of negative powers of ten.

Similar problem: 1/3 cannot be exactly expressed as a finite decimal number:

0.333333333333333333…

1/10 (0.1 decimal) cannot ever be accurately represented in base 2, 8, or 16:

0.000110011001100… base 2

0.0631631631631… base 8

0.19999999999… base 16

a sum of ten binary "tenths" will not be exactly 1 due to this representation error

Using Floating Point

Be aware of round-off error occurring due to the limited number of bits available for each of the mantissa and exponent.

Make sure you pick a storage type with enough bits for precision and range to accurately represent the numbers you use.

Note that a four-byte integer has more bits of precision than a four-byte floating-point number.  A four-byte integer has less range than a four-byte floating point #.

Never compare floating-point numbers for exact equality; test for "close enough" against a "reasonably" small value:

absolute_value(f1 - f2)  <  epsilon

Floating Point Implementations

For general use, the C language on most computers defines a float floating-point storage type, 4 bytes long, that handles approximately 6-7 decimal digits of mantissa and an exponent between -38 and +38

The C language double floating-point storage type, 8 bytes long, handles approximately 17-18 decimal digits of mantissa and an exponent between -308 and +308

Remember: Bits are bits.  The same bit pattern may be a signed or unsigned integer, a character, or a floating-point number, depending on how it is used.

Floating Point Imprecision

main()

{

        int i;

        float x;

        double y;

 

        printf("\nFloats:\n");

        for( i=0; i <= 9; i++ ){

                x = 1.0 + (i / 10.0);

                printf("Expect 1.%d - actual is %.42f\n",

                        i, x);

        }

        printf("\nDoubles:\n");

        for( i=0; i <= 9; i++ ){

                y = 1.0 + (i / 10.0);

                printf("Expect 1.%d - actual is %.42f\n",

                        i, y);

        }

}

Output of Imprecise Floats

 

Floats:

Expect 1.0 - actual is 1.000000000000000000000000000000000000000000

Expect 1.1 - actual is 1.100000023841857910156250000000000000000000

Expect 1.2 - actual is 1.200000047683715820312500000000000000000000

Expect 1.3 - actual is 1.299999952316284179687500000000000000000000

Expect 1.4 - actual is 1.399999976158142089843750000000000000000000

Expect 1.5 - actual is 1.500000000000000000000000000000000000000000

Expect 1.6 - actual is 1.600000023841857910156250000000000000000000

Expect 1.7 - actual is 1.700000047683715820312500000000000000000000

Expect 1.8 - actual is 1.799999952316284179687500000000000000000000

Expect 1.9 - actual is 1.899999976158142089843750000000000000000000

 

Doubles:

Expect 1.0 - actual is 1.000000000000000000000000000000000000000000

Expect 1.1 - actual is 1.100000000000000088817841970012523233890533

Expect 1.2 - actual is 1.199999999999999955591079014993738383054733

Expect 1.3 - actual is 1.300000000000000044408920985006261616945267

Expect 1.4 - actual is 1.399999999999999911182158029987476766109467

Expect 1.5 - actual is 1.500000000000000000000000000000000000000000

Expect 1.6 - actual is 1.600000000000000088817841970012523233890533

Expect 1.7 - actual is 1.699999999999999955591079014993738383054733

Expect 1.8 - actual is 1.800000000000000044408920985006261616945267

Expect 1.9 - actual is 1.899999999999999911182158029987476766109467

The simple IF statement makes a yes/no decision

Any time execution encounters the simple IF statement, a choice is made whether or not to execute the enclosed set of statements:

IF control_expression

 Statement 1

 Statement 2

 …

ENDIF

If control_expression tests true, execute the set of statements between the IF and the ENDIF.

If control_expression tests false, skip all the statements and continue execution with whatever comes after the ENDIF.

IF is not a loop.  When the simple IF statement is encountered, the set of enclosed statements is only executed once, or not at all.

Examples of the simple IF statement in C language

#define LOW_LIMIT 0

if ( num < LOW_LIMIT )

{

   printf("Error: %d is smaller than %d\n",

      num, LOW_LIMIT);

   printf("Resetting number to %d.\n",

      LOW_LIMIT);

   num = LOW_LIMIT;

}

 

 

#define MAXDAYS 10

if ( days > MAXDAYS )

{

   printf("Warning: %d days > %d\n",

      days, MAXDAYS);

}

 

 

#define T_LETTER ‘T’

if ( letter != T_LETTER )

{

   printf("You typed %c instead of %c\n",

      letter, T_LETTER);

}

Why C has a compound IF statement

Consider the following pair of of double-if statements, with the first IF being done if the control_expression is TRUE, and the second one being done if the expression is FALSE (NOT TRUE):

 

IF control_expression

 A first set of one
 or more statements …

ENDIF

IF ! control_expression

 A second set of one
 or more statements …

ENDIF

 

This pairing happens often enough that C allows the above two IF statements to be written as one IF/ELSE statement:

 

IF control_expression

 A first set of one
 or more statements …

ELSE

 A second set of one
 or more statements …

ENDIF

The meaning is identical in both cases. The IF/ELSE version is more efficient, since it only has to test the condition once. If the condition is TRUE, the first set of statements is executed. If the condition is FALSE, the second set is executed instead.

The compound IF statement gives two choices (once)

Any time execution encounters a compound IF statement, one of two sets of statements are chosen:

IF control_expression

 A first set of one
 or more statements …

ELSE

 A second set of one
 or more statements …

ENDIF

If control_expression tests true,
execute the first set of statements, once.

If control_expression tests false,
execute the second set of statements, once.

When this style IF statement is encountered, one or the other of the sets of statements is done.

Never both sets of statements; never no set

Always one set or the other

Examples of the compound IF statement in C language

evencount = oddcount = 0;

if ( (num % 2) == 0 )

{

   printf("%d is an even number.\n", num);

   ++evencount;

}

else

{

   printf("%d is an odd number.\n", num);

   ++oddcount;

}

 

 

 

#define FEB_NOLEAP_DAYS 28

#define FEB_LEAP_DAYS (FEB_NOLEAP_DAYS+1)

if ( isLeapYear(year) )

{

   febDays = FEB_LEAP_DAYS;

}

else

{

   febDays = FEB_NOLEAP_DAYS;

}

printf("February has %d days in %d\n",

   febDays, year);

The nested IF statement

A nested IF statement is an IF statement inside an IF statement.  The nesting might occur in either part of the IF, and the nested IF may or may not itself be a compound IF statement. Nesting can go to any level.

IF control_expression_1

 IF control_expression_2

    A nested set of one
    or more statements …

   ENDIF

ELSE

 IF control_expression_3

    A nested set of one
    or more statements …

   ELSE

    A nested set of one
    or more statements …

   ENDIF

ENDIF

Examples of the nested IF statement in C language

evencount = oddcount = 0;

 

if ( (num % 2) == 0 )

{

   printf("%d is an even number.\n", num);

   ++evencount;

 

   if( (num % 4) == 0 )

      printf("It is divisible by 4\n");

 

   if( num == 0 )

   {

      printf("It is zero.\n");

      printf("That isn’t interesting.\n");

   }

}

else

{

   printf("%d is an odd number.\n", num);

   ++oddcount;

 

   if( (num % 9) == 0 )

      printf("It is divisible by 9\n");

   else

      printf("It is not divisible by 9\n");

}

The Decision Table IF statement

A decision table IF statement selects among more than two alternatives.  This form of IF statement avoids deep nesting.  Usually, each control_expression tests the same variable against different constant values.

IF control_expression_1

 A first set of one
 or more statements …

ELSE IF control_expression_2

 A second set of one
 or more statements …

ELSE IF control_expression_3

 A third set of one
 or more statements …

ELSE

 A final set of one
 or more statements …

ENDIF

 

Example of the Decision Table IF statement in C language

Note the use of brace brackets {} to enclose multiple statements, where needed.

The order of the tests is very important. Testing for "less than" must proceed from smallest to largest.  Testing for "greater than" must proceed from largest to smallest.

 

void

noise_print(int noise_db)

{

   if( noise_db <= 50 )

      printf("quiet\n");

   else if ( noise_db <= 70 )

      printf("intrusive\n");

   else if ( noise_db <= 90 )

      printf("annoying\n");

   else if ( noise_db <= 110 )

      printf("very annoying\n");

   else

   {

      printf("\nNoise level %d ",

         noise_db);

      printf("is uncomfortably loud!\n");

   }      

}

How to Construct a Loop

Initialization

What variables need starting values, once, before we begin the loop?

Variables used in the control_expression?

Variables used in the loop body?

Condition (control_expression)

Determine the terminating condition that makes the logical control_expression false and thus tells when to stop looping.

Increment / decrement

What variable or variables must change value during the looping, so that the terminating condition eventually happens?

Usually done at the end of the loop body.

Body

The statements that are repeated in the loop.

The WHILE statement loops zero, one, or many times

The WHILE looping statement iterates zero or more times:

WHILE control_expression

 Statement 1

 Statement 2

 …

ENDWHILE

While the control_expression tests true at the start of an iteration of the loop, execute the set of statements between the WHILE and the ENDWHILE.

When the control_expression tests false at the beginning of an iteration of the loop, skip all the statements and continue execution after the ENDWHILE.

Some statement within the loop must cause some value in the control_expression to change from true to false, otherwise the control_expression will never test false and the looping will never stop.

If the control_expression is not true when the WHILE statement is first encountered, the set of statements is not executed even once.

The DO/WHILE statement loops one or many times

The DO/WHILE looping statement iterates one or more times:

DO

 Statement 1

 Statement 2

 …

WHILE control_expression

Execute the set of statements between the DO and the WHILE, and then repeat while the control_expression tests true at the end of an iteration of the loop.

When the control_expression tests false at the end of an iteration of the loop, continue execution after the line containing the WHILE; don’t do any more iterations.

Some statement within the loop must cause some value in the control_expression to change from true to false, otherwise the control_expression will never test false and the looping will never stop.

Because the control_expression is tested at the end  of the loop, the set of statements is always executed at least once, even if the control_expression is false.

The FOR statement loops (zero, one, or many times)

The FOR looping statement iterates zero or more times:

FOR var from N1 up/down to N2

 Statement 1

 Statement 2

 …

ENDFOR

Execute the statements between FOR and ENDFOR with the var (variable) first set to the value N1.  Redo the same statements with var taking on the next value (up or down) toward N2.  Continue until var is equal to N2.

If N1 is already past N2 when the FOR statement is first encountered, the set of statements is not executed even once.  Execution continues after the ENDFOR.

Definitions

Variable: a named location in memory

Iterate: to loop; to do something more than once

Increment: to increase the value in a variable, usually by 1

Decrement: to decrease the value in a variable, usually by 1

Termination condition: the condition that terminates a loop (the complement of the loop expression)

Problem 1 in English

Problem: Numbers will be input from keyboard one at a time.  Find the sum of the positive numbers and the sum of the negative numbers.  Display both results.

Use a loop controlled by a character from the keyboard.

After each number, the user will be asked if he/she wishes to enter another number.  If the response is 'Y', get the next number and sum it. Terminate input for any other response character.

 

Semi-English solution:

         

Initialize positive sum, negative sum

DO

   Prompt user for a number

   Get and echo number

   IF number >= 0

      Add to positive sum

   ELSE

      Add to negative sum

   ENDIF

   Prompt user for a Y response

   Get and echo response

WHILE response is Y

Display both sums

Problem 1 in Pseudocode

PosSum <-- 0

NegSum <-- 0

 

DO

   PUT "Enter a number: "

   GET Number

   PUT "You entered: " Number

   IF Number >= 0

      PosSum <-- PosSum + Number

   ELSE

      NegSum <-- NegSum + Number

   ENDIF

   PUT "Type a ‘Y’ to continue"

   GET Response

   PUT "Your response was: " Response

WHILE Response EQUALS ‘Y’

 

PUT "The positive sum is: " PosSum

PUT "The negative sum is: " NegSum

Problem 2 in English

Problem: The marks for 70 students are to be entered.  Find and display the average mark.

Use a loop controlled by a counter set to 70 when the program begins.

 

Semi-English solution:

 

Initialize counter, sum, maxmark

WHILE counter <= maxmark

   Prompt for the mark

   GET mark

   Echo the mark

   Add mark to sum

   Increment counter

ENDWHILE

Calculate average using sum, maxmark

PUT average

Problem 2 in Pseudocode

 

Sum <-- 0

Counter <-- 1

MaxMark <-- 70

WHILE Counter <= MaxMark

   PUT "Enter Mark #" Counter ":"

   GET Mark

   PUT "You entered:" Mark

   Sum <-- Sum + Mark

   Counter <-- Counter + 1

ENDWHILE

Average <-- Sum / MaxMark

PUT "The average of " MaxMark

PUT " marks is " Average

 

Pseudocode Exercises

  Write the pseudocode for the following problems:

1. Accept numbers from keyboard.  Use 9999 to terminate.
Find and display largest number (excluding 9999).

2. To count the number of times it takes player #2 to guess a number between 1 and 100 that is input by player #1.
When the guess is too high or too low, display appropriate messages.  When a correct guess is made, display an appropriate message and the number of guesses taken.

3. Accept positive numbers from keyboard.
Terminate with a negative number.
Determine the smallest and largest positive number that was entered.  Display both.

4. Accept student test marks from the keyboard.
Terminate with a -1.   Display each mark.
Count the number of marks that correspond to each letter grade: A, B, C, D, and F.  Display the five counts.