Section 3.4 Repetition: A Simple for-Loop
Suppose you wanted to print the same line of text five times. Here is one way to do so:
admin.....open in new window
But imagine how many times youโd have to type the same line if you wanted to print it 100 times! Or imagine wanting to make a change to all of those lines, for example wanting two exclamation marks at the end of each output line. Here is a more elegant solution: a so-called
loop:
admin.....open in new window
Try it out right now by hitting that โRunโ button!
C actually supports multiple types of loops. This one is called a
for-loop; weโll learn about the other types of loops later. We will also soon learn more about the use of the rather mysterious-looking โ
iโ and the line โ
int i;โ. For now, just think of
i as something that can hold different values. In this particular example,
i takes on values between 1 and 5, and for each value of i between 1 and 5 this loop prints out
Hello, World!. That is,
Hello, World! is printed exactly 5-times.
Activity 3.4.
-
Try it out by clicking on the โRunโ button in the above window and verify that the same line is indeed printed 5-times.
-
Now modify the code so that it prints Hello, World! 10-times.
You can place multiple statements into your loops:
admin.....open in new window
Activity Activity
1. Study the code.
What do you think the above code will print to the screen? Will it print: