Programming and Graphics

(Kiana) #1

3.3 Control structures 57


For example, consider the block of commands:

goto mark;
a=5;
mark:

The statementa=5will be skipped.

Fortran 77users are fondly familiar with theGo tostatement.Mat-
labusers are unfairly deprived of this statement.

Some programmers consider thegotostatement an anathema and a recipe
for “spaghetti code.” In the opinion of this author, this is only an exag-
geration.


  • while loop:


We use thewhileloop to execute a block of commands only when a
distinguishing condition is true.

For example, the followingwhileloop prints the integers: 1, 2, ..., 9,
10:

int i=0;

while(i<10)
{
i=i+1;
cout<<i<<"";
}

Note that the veracity of the distinguishing conditioni<10is checked
beforeexecuting the loop enclosed by the curly brackets.

The compiler interprets the expressioni<10as a Boolean variable that is
true, and thus equal to 1, or false, and thus equal to 0. Accordingly, the
loop

int i=1;

while(i)
{
i=i-1;
}

will be executed only once.
Free download pdf