Thursday, July 22, 2010

C++: while loop - repeating certain part of a program

So far, we have worked with so-called "procedural" or linear programs where
the program runs from beginning to end. But what if we want to repeat
certain section (a block) of a program until a condition is met? The answer
is that is perfectly possible. This algorithm (precise steps) is called a
loop ( circle, perhaps). There are many ways of achieving this, including
setting a defining condition so that the program runs repeatedly until this
condition is met, or run a block of a program for a certain number of times
before continueing with the rest of the code. What I've just described are
called "while" and "for" loops, respectively, but in this post, let's go
over the simplest one first: the while loop.

A while loop, as described earlier, means that a computer will run a section
of a program repeatedly until a certain condition is met. For example,
suppose if we are to write a number guessing game with a fixed number as the
guess. We could describe the algorithm as:
First, display the prompt so that a user can write guesses. Then have the
user enter the guess. If the entered guess is not what the program is
looking for, tell the user to write the guess again. Repeat the last step
until the correct guess has been entered.

Do you have any idea on how to convert this into something we can use in
writing this sort of program? As it turns out, the while loop consists of
only seven to ten lines of code: (code from C++ A Dialog by Steve heller
with my modification):
// The usual start of a program that includes iostream and string.
// The program starts (int main();).
cout << ""Enter a guess between 0 and 9:" << endl;
int guess = 4;
int number;
cin >> number;
while (guess != number)
{
cout << "Huh? You typed a wrong number. Try again:" << endl;
cin >> number;
}
cout << "You are correct!" << endl;

Few notes to consider: you might have guessed that the actual while
statement tests whether a number entered is the same as the guess value (4)
and runs the block if it is not. Also, you might have noticed that I wrote
two input statements, one right before the loop and another within the loop.
Can you guess as to why is was done like that? The answer: as in common
sense, we need to test what we are actually testing to see if we are right
or wrong - in this case, we are testing the value that the user enters in
the beginning. If the user enters the right value, this is great - we don't
have to enter the loop (I consider you a genius). However, the objective
here is, "what if the user types wrong value in the beginning," thus we had
a provision for having the while statement. Also, at the end of the while
loop, we had to ask because we want to make a decision to enter the loop
when a user types the wrong number, thus repeating the process over again.
Hope you understand this, as this notion of a loop becomes important as we
continue with for loop later.

Using wile loop, we can perform all sorts of conditional repetetive tasks,
including guessing games, getting a number of user input to be processed
later (via functions) and displaying the contents of a file (file
input/output, or I/O will be discussed much later). As for conditions, we
can have all sorts of them, including checking whether a user typed correct
number or a letter, provide provission for continued execution of a program
to even ending a loop. An example is getting two or more numbers, provided
that the second number onwards is greater than zero, or typing "-1" to quit
a program, as in case of some of my first assignments with while loops.

But be careful with loops though: Have you wondered why some programs never
terminate with our without displaying something to the user, requiring
programs such as Task Manager to help you clean it out? This is in response
to a well-known "bug" called an "infinite loop" i.e. a loop procedure that
never ends. This, according to what I read and experiences , is mostly
caused by a loop that doesn't have conditional statement, or a loop that has
a nested ones of their own (logicaly called nested loops) without a clear
way of terminating it. For example, what if our guessing game code above
didn't have a clear condition i.e. the actual number to terminate the loop?
The result is that the program will ask you SO MANY TIMES(in a never ending
cycle) to ask you to type in a number to be guessed. Also, if a program
eats, or allocates memory during while loop without ending it, we could run
into a potential problem called "memory leak." The only way to end this sort
of program is using intervention from an operating system, such as Task
manager or typing CTRL+C under Windows/Command Prompt. P.S. The concept of
memory leak will be discussed in more detail when i post notes on working
with dynamic memory allocation.

Now, I guess it's time for a fun exercise (maybe to help you get started
with while loops): suppose if we want a user to type a letter and see if it
matches the command that the computer is looking for. for this one, let's
ask the user to type a letter. If the letter is "J", let the computer say,
"Jackpot," otherwise let the user type a letter again. Sounds a bit
complicated this time, but I'm sure we can do it. But there is a provision:
you need to do it; but I'll give you some hints:
1. You might want to create a character variable to store your guesses. For
now, initialize (or assign) this variable to the letter "J".
2. Try out an "if" statement first and put the condition so that when the
user types "J", the computer would print out, "Jackpot," otherwise print
"Huh, what are you saying?".
3. This time, try out the while loop version with a condition that the
letter is not equal to "J". If that's the case, have the computer print out,
"Huh, try again. There is a letter I'm looking for." If the user types "J",
say, "Jackpot!".
4. Try compiling your results (twice, one after writing the if version and
once more after replacing the if with while). Do you see any differences?
The answer to this quiz (at least how I would do it, along with an example
program that you can download (if possible)) will be posted at the end of
this section (not this post, but later).

Postscript: As it turns out, there is a variation of our while loop
statement: the "do-while" loop, which means that we want to run the code
within the while loop at least once before continuing with the looping
process. I'll discuss the difference between "while" and "do-while" in more
detail later when I have time with an example of a more complete guessing
game program. But just for sake of our discussion, think of while loop as an
enhanced version of "if" statement that checks the condition first (in the
beginning) before entering the loop, whereas the "do-while" first runs the
loop (like the program) and checks the condition at the end to determine
whether to continue or not.

Next: An exercise...
// JL

No comments:

Post a Comment