csc110: 2010 03 04

Posted in csc110 by bnmng on 2010 03/04

Homework Due Thursday March 25 (see paper).

Program 2
Sample Test 2
Homework 5

Loops have initialization, … ..

Entering a character when the program expects a numeric can yield unexpected results. Can even result in endless loop.

As usual it’s hard to translate the class notes into a cohesive set, but here’s some tidbits that we went over regarding loops:
1) Ensure your test is valid. Say you start with 1, increment by 2, and you test something like a!=10 to determine when the loop ends. Such a loop would never end because the value would jump from 9 to 11, never equaling ten.

2) In an incremental loop that tests a value, put your increment in the appropriate place.

In a loop, the test is the control structure.

while ((n!=-1) && cin) {
blah; blah; blah;
cin >> n;

The test cin, results in a “false” if the input is corrupt. Testing far a false cin is a way to keep corrupt inputs from ruining your program.

Example Program
cin >> ch; // This is a prime. Its an input that starts before the loop.
while ch is not q
read < u d

Note: There’s an important table in Chapter 4, page 136, on precedents of operators.

Notes about the previous homework

Note: if converting a [switch] structure which doesn’t have a default to an [if/else] structure, then the [if/else] structure won’t have a final [else].

Note: if a condition is never met for an [if/else] which doesn’t have a final [else], or a condition is never met for a [switch] without a default, then nothing happens.

Note if(number==3 or 4) // this is always true no mater what the number is, because 4 is always true.
if(number==3 or number==4) // this would be better.

Note Go through all the stages of the inner loop for each iteration of the outer loop.

Note: Remember that in a counting loop, you want to put the incrementing statement last. At least that’s what Dr. Sterling says, but in reality there might be reasons to put it in different places. Always keep in mind the order in which lines are run.

A for loop is like a while loop but it initializes a variable and increments it.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: