• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

C. Programming Concepts > Repeated Actions

Repeated Actions

Sometimes you want to repeat an action a specific number of times (“fill ten two-liter containers from a large water tank”). You use a for loop to do the first sort of task. It’s called a loop because, if you were to draw arrows representing the path the computer takes through your program, they would form a loop as the program repeated the actions. Here’s the container-filling scenario translated into ECMA Script, with variables for the water tank and the containers presumed to be defined. The loop body, that is, the actions we want repeated, are enclosed in curly braces.

var i;              // a counter variable
for (i = 0;         // start counting at zero
     i < 10;        // up to (but not including) 10
     i++)           // add one to the count at every repetition
{
    tank[i] = 2;                // fill container number "i"
    waterTank = waterTank - 2;  // take 2 liters out of the tank
}

PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint