Counting Loops
A for loop repeats a block of code, but it’s more configurable than a while loop. A for loop is also the preferred tool for counting tasks. while loops are better for repeating something “while” a condition is true. In contrast, for loops are better for repeating a block a certain number of times. This next program counts to ten with a for loop.
- Click SimpleIDE’s Open Project button.
- If you’re not already there, navigate to …SimpleIDELearnExamplesC IntroBasics.
- Open Count to Ten.side.
- Set the power switch to position 1 if it isn’t already (if applicable for your board).
- Click the Run with Terminal button, and verify that the program counts to ten.
/* Count to Ten.c Count to ten in SimpleIDE Terminal. */ #include "simpletools.h" // Include simpletools int main() // main function { for(int n = 1; n <= 10; n++) // Count to ten { print("n = %dn", n); // Display name & value of n pause(500); // 0.5 s between reps } print("All done!"); // Display all done }
How it Works
The for statement has three parameters: for(start index; condition; increment).
- start index – typically a variable that is assigned an initial value where the counting starts
- condition – a condition that has to be true for the loop to repeat
- increment – an operation that should be performed on the index variable with each loop repetition
In the Count to Ten program, the start index is int n = 1, a variable declaration that initializes the variable n to the value 1. The condition is n <= 10, which means that the loop will keep repeating while n is less than or equal to ten. The increment is n++, which is a shorthand form of n = n + 1. So with each repetition of the for loop’s code block, the value of n increases by 1.
Did You Know?
Increment operators — The ++ operator is called an increment operator. Although increment and decrement operators are especially useful in for loops, they can be used as shortcuts in many parts of your programs.
++ add 1 to a variable –– subtract 1 from a variable
Assignment operators — There are also some useful shortcuts for assigning values to variables. For example, instead of n = n + 5, you can use n += 5. As you might expect there are, shortcuts for subtraction –=, multiplication *=, division /=, and modulus (remainder) %=. These are called the assignment forms of the operators.
Try This
Here is a for loop that will count to 200 in steps of 5, just like the while loop you experimented with earlier.
- Use Save Project As to save your program as Count to 200 by 5s.
- Modify the for loop so that it looks like the this:
- Verify that it counts to 200 in steps of 5.
Your Turn
- Modify your program so that it counts up to 200 in steps of 5, then down to 0 in steps of 10.