continue...
An alternative to "if" statement is "switch" statement. This is useful if
you want to incorporate a menu-like system where a user presses a command
and it would automatically execute a part of the program. A conventional
syntax is:
switch (menu_options)
{
case 1:
// Field 1.
break;
case 2:
// Anything else...
break;
...
default:
// A default message...
}
At the first glance, this sounds more like English...
As previously mentioned, it is perfectly possible to have nested loops -
even within for loops. But how does a program know what portion of the loop
to run? It looks for the inner of the loops to run before continuing with
the rest of the outer loop. For example, if I have a for loop inside a while
loop, the computer would run the for loop first, then check the condition to
whether repeat the while loop or not. This is called "scope," which we'll
talk more about when we get into functions.
Speaking of while loops, we can have a variation known as "do-while" loop.
This is useful if you want to run the code that normally belongs to the
while loop first before testing the condition. An example would be a
guessing game where the user would be prompted if the input number is higher
or lower than the guess that the computer had in mind (this was one of my
lab assignments to check for segmentation fault). A typical code might be:
do
{
// Whatever the program does...
} while (the condition);
In other words, we are checking the condition at the end, as opposed to the
while loop which checks the condition first.
//JL
No comments:
Post a Comment