A for loop repeats a function for a specific number of times.
Increment and decrement
For loops use increment and decrement operators.
- increment means to loop again, counting up (1, 2, 3, 4, …) The symbol for increment is++
- decrement means to loop again, counting down (… 4, 3, 2, 1) The symbol for decrement is —
Let’s study increment first. When you increment something, you add 1 to it. For example, if loop = 1, then ++loop = 2. If I increment again, then ++loop = 3.
NOTE: In simple for loops, we can write the increment before or after the variable: ++loop or loop++. In other expressions, however, these two are quite different.)
The for statement
To write a for loop, we must use the for statment, which contains three parts:
- initialize the counter: set the counter to begin at 1 (or any other number)
- set how many times you want it to loop
- increment the loop
Here is a sample for statement with these three parts:
This statement says, “Starting at 1, if the loop is less than 4, then loop again.” This means that you will loop 3 times, because when you reach 4, the loop will stop.
NOTE: You can use any variable in a for statement, instead of “loop”. Some programmers use “count” or “input”.
Simple for loop
Let’s write a simple for loop that repeats “Have a great day!” three times on the screen.
#include<stdio.h> void main( ) { int loop; for(loop = 1; loop < 4; ++loop) }
|
Type this source code in your editor and save it as floop.c then compile it, link it, and run it.
Now let’s write a for loop that repeats “Have you paid those parking tickets yet?” six times on the screen:
#include<stdio.h> void main( ) { int count; for(count = 1; count < 7; ++count) }
|
Notice that we have changed three things: the name of the variable (count), the number of times to repeat the loop count < 7; and the question.
Type this source code in your editor and save it as parking.c then compile it, link it, and run it.
Continue on to For Loops, Numbers and Pictures.
Leave a comment