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.
/* 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 = %d\n", n); // Display name & value of n pause(500); // 0.5 s between reps } print("All done!"); // Display all done }
The for statement has three parameters: for(start index; condition; increment).
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.
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.
Here is a for loop that will count to 200 in steps of 5, just like the while loop you experimented with earlier.