Skip to main content
Logo image

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.

  1. Try it out by clicking on the “Run” button in the above window and verify that the same line is indeed printed 5-times.
  2. 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:
  • Hello World 3-times, then Today is Saturday 3-times?
  • Not quite...
  • Hello World. Today is Saturday. 3-times ?
  • Great job!
  • Something else?
  • Try again...