Learn How to Program in Cby
|
Save your source code as numloop.c. Compile it. Link it. Run it. You will see this statement on your screen: Listing numbers and charactersOne of my favorite ways to use this type of for loop is to see what the character formats (%c) are for various numbers.
To do this, I create a loop that counts a specific list of numbers (from 3 to 6). Then I display a column of numbers (%d), followed by the tab escape character (\t), and then a column of corresponding characters (%c). Here is what it looks like:
Save your source code as floopy.c. Compile it. Link it. Run it. Depending on whether your computer interprets the numbers in ASCII format or not, you will get a different result in the second column. NOTE: If you are using the GCC compiler on a Unix system, this example will run but you won't see the second column. Drawing PicturesFor loops are useful for drawing pictures on the screen. In the previous example, we discovered the character format for the number 3. Let's use this character to draw a box. Here are the steps:
We must initialize two variables: one for the counter (loop < 6) and one for the number that we'll display as a symbol (3). Here is the script:
Save your source code as pic.c. Compile it. Link it. Run it. Depending on whether your computer interprets the numbers in ASCII format or not, you will get a different symbol for the box. NOTE: If you are using the GCC compiler on a Unix system, you will not see the box. Replace the symbol variable with a star (*) from your keyboard. Decrement for loopTo decrement means to loop again, counting down (... 4, 3, 2, 1) The symbol for decrement is -- The three parts of a decrement for loop are different from an increment for loop:
Putting these three parts together, we get this: Sample decrement for loopNow let's use a decrement for loop. This program gives the viewer 5 chances to answer the question "What year did Maryland become a state?".
We must initialize three variables: correct for the year Maryland became a state, attempt for the counter, and year for the viewer's guess.
Save your source code as decloop.c. Compile it. Link it. Run it. |
||||||||||
|
Copyright © 2001 Kristin Switala |
|||||||||||