for

Definition

The for statement is used to create a loop that is composed of three optional expressions in parentheses and separated by semicolons that execute a block of code as long as (while) the test condition is true. The test condition is evaluted at the start of the loop.

Syntax

for

A Java and JavaScript for statement has the following syntax:

for ( initialisation; condition; final_expression ) {
    block;
}
  • The initialisation is an expression or variable declaration. It is typically used to initialize a counter variable.
  • The condition is an expression that is evaluated at the start of each pass through the loop, and which evaluates to either true or false.
    The loop will stop executing when the condition becomes false.
  • The final_expression is an expression that is evaluated at the end of each loop iteration. This occurs before the next evaluation of condition. It is typically used to update or increment the counter variable.
  • The block is a block of code that gets executed while the condition evaluates to true.
for ( initialisation; condition; final_expression ) {
    block;
}
  • The initialisation is an expression or variable declaration. It is typically used to initialize a counter variable.
  • The condition is an expression that is evaluated at the start of each pass through the loop, and which evaluates to either true or false.
    The loop will stop executing when the condition becomes false.
  • The final_expression is an expression that is evaluated at the end of each loop iteration. This occurs before the next evaluation of condition. It is typically used to update or increment the counter variable.
  • The block is a block of code that gets executed while the condition evaluates to true.
for [iterating variable] in [sequence]:
    block 

Examples

Example 1: Multiplication Tables

Imagine that you want to print out the multiplication table for a given number. E.g., the times table for 6:
    1 times 6 = 6
    2 times 6 = 12
    3 times 6 = 18
    etc.

Let's look at some code to achieve this.

  1. We'll use a for loop and a variable timesLine will act as our counter. We want to go through the loop 12 times, so we will initialise timesLine to 1, and loop while it is less or equal to 12, and increment it by one at the end of each pass through the loop.
    // Repeat 1 to 12 times
    for ( var timesLine = 1; timesLine <= 12; timesLine++ ) {
        // Do something here
    }
    // Repeat 1 to 12 times
    for ( int timesLine = 1; timesLine <= 12; timesLine++ ) {
        // Do something here
    }
    # Repeat 1 to 12 times
    for timesLine in range(1,13) :
        # Do something here
    
  1. We will get the required number for the multiplication table from the user and store it in the timesTable variable.
    var timesTable;       // the times table value chosen
         
    timesTable = prompt( "Enter the times table required: " );
    	     
    // Repeat 1 to 12 times
    for ( var timesLine = 1; timesLine <= 12; timesLine++ ) {
        document.write(timesLine + " times " + timesTable + " = ");
        document.write((timesLine * timesTable) + "<br>");  // the answer
    }
    int timesTable;         // the times table value chosen
         
    Scanner input = new Scanner(System.in);
    System.out.println("Enter the times table required: ");
    timesTable = input.nextInt();
    
    // Repeat 1 to 12 times
    for ( int timesLine = 1; timesLine <= 12; timesLine++ ) {
        System.out.print(timesLine + " times " + timesTable + " = ");
        System.out.println((timesLine * timesTable));  // the answer
    }
    timesTable = int(input( 'Enter the mark for the times table' ))
    	
    for timesLine in range(1,13) :
        print( timesLine, " times ", timesTable, " = ", timesLine * timesTable )  

Example 2: Year Average

Imagine that you want to calculate the year average (in this case, a module is a course component, as university students would know it). The year is composed of 120 credits. For the sake of simplicity, we'll consider that the year is composed of six 20-credit modules.

Let's create the code for this, one step at a time.

  1. We'll use a for loop and the variable that will hold the number of marks entered: marksEntered will act as our counter. We want to go through the loop 6 times, so we will initialise marksEntered to 0, stop when it's less than 6, and increment it by one at the end of each pass through the loop.
    for ( var marksEntered = 0; marksEntered < 6; marksEntered++ ) {
        // Do something here
    }
    for ( int marksEntered = 0; marksEntered < 6; marksEntered++ ) {
        // Do something here
    }
    for marksEntered in range(6) :
        # Do something here
    
  1. We'll keep track of the marks entered by storing the new mark entered in the moduleMark variable and the sum of all the marks entered into the sumMarksEntered variable.
    var sumMarksEntered = 0, 
        moduleMark = 0;
    
    for ( var marksEntered = 0; marksEntered < 6; marksEntered++ ) {
        moduleMark = prompt( "Enter mark for module number " + ( marksEntered + 1 ) );
        sumMarksEntered = sumMarksEntered + parseInt( moduleMark );
    }
    int sumMarksEntered = 0, 
        moduleMark;
    Scanner sc=new Scanner(System.in);
    
    for ( int marksEntered = 0; marksEntered < 6; marksEntered++ ) {
        System.out.print ("Enter mark for module number " + ( marksEntered + 1 ) );
        moduleMark = sc.nextInt(); 
        sumMarksEntered = sumMarksEntered + moduleMark;
    }
    sumMarksEntered = 0 
    moduleMark = 0
    
    for marksEntered in range(6) :
        moduleMark = input( 'Enter mark for module number ' + str(marksEntered + 1) )
        sumMarksEntered = sumMarksEntered + int( moduleMark)
    	
  1. Finally, once the user has entered the 6 marks and we come out of the for loop, we'll calculate the year average by dividing the sum of all the marks entered (sumMarksEntered) by 6. We will use the yearAverage variable for this, and will display the output.
  2. var sumMarksEntered = 0, 
        moduleMark = 0;
        yearAverage = 0;
        
    for ( var marksEntered = 0; marksEntered < 6; marksEntered++ ) {
        moduleMark = prompt( "Enter mark for module number " + ( marksEntered + 1 ) );
        sumMarksEntered = sumMarksEntered + parseInt( moduleMark );
    }
    
    yearAverage = sumMarksEntered / 6;
    alert( "Your year average is " + yearAverage );
    int sumMarksEntered = 0, 
        moduleMark;
    double yearAverage;
    Scanner sc=new Scanner(System.in);  
    
    for ( int marksEntered = 0; marksEntered < 6; marksEntered++ ) {
        System.out.print ("Enter mark for module number " + ( marksEntered + 1 ) );
        moduleMark = sc.nextInt(); 
        sumMarksEntered = sumMarksEntered + moduleMark;
    }
    
    yearAverage = sumMarksEntered / 6.0;
    System.out.println( "Your year average is " + yearAverage );
    
    sumMarksEntered = 0 
    moduleMark = 0
    
    for marksEntered in range(6) :
        moduleMark = input( 'Enter mark for module number ' + str(marksEntered + 1) )
        sumMarksEntered = sumMarksEntered + int( moduleMark)
        
    yearAverage = sumMarksEntered / 6
    print( "Your year average is ", yearAverage )
    


To get a good understanding of the logic developed here and the for loop structure, view this in the Code Visualiser , or play with the code below (press the "Run Code" button to run the code): JS Bin on jsbin.com.