a chance to enter a correct number with a do-while loop.
Assigning 0 to favRating and 10 to leastRating might seem confusing at first, but once you
are in the loop getting movie names and ratings, you need a baseline to compare each movie’s rating.
Initially, you want the lowest possible rating for favorite so that any movie rated will become the
favorite, and you want the highest possible rating for least favorite so that any movie rated will
become the least favorite. This means that the first movie (in the code sample, Veranda) will become
both the favorite and the least favorite movie of the user. But that makes sense—if you only saw one
movie, it would be both the best and the worst, until you had something to compare.
When you enter additional movies, the two if statements in the loop see whether you liked the next
movie more or less than your current top and bottom movies and make the appropriate change. In the
code sample, the second movie, Easiness, had a rating of 3. This rating is not higher than Veranda’s
7, so Veranda remains the highest movie; now Easiness is the least favorite movie.
You will be able to account for a few issues with this program as you learn more about C. First is the
limitation of scanf() when dealing with strings—it can only take one word without spaces.
Obviously, most movies have multiple words in the title. When you learn additional input/output
methods later in this book, you can adjust for this problem.
When you learn about other arrays, including pointer arrays, you will be able to keep all the movie
names in a program like this. You will also learn how to sort data, so you can revisit this program and
print a ranking of your favorite movies instead of listing just a favorite and a least favorite. The last
problem also would be fixed with this listing because the program saves only one movie for each
ranking; if the user enters two equal values (such as Kickpuncher and Celery, in the sample
output), only one can be listed as a favorite.
The Absolute Minimum
The goal of this chapter was to show you an additional way to form a loop of
statements in C. The for statement gives you a little more control over the loop than
either while or do-while. The for statement controls a loop with a variable that
is initialized and changed according to the expressions in the for statement. Key
concepts in this chapter include:
- Use a for loop when you want to increment or decrement a variable through a
loop. - Remember that the for loop’s relational test is performed at the top of the loop.
- Use a nested loop if you want to loop a certain number of times.
- Don’t forget the semicolons inside the for loop—for requires them.
- Don’t use an initial value that is less than the test value if you want to count down
with for.