For Loop

The For loop is another repetition structure. The advantage of using the For loop is that the structure itself keeps track of incrimenting the counter, so you do not have to. Usually by default, the counter is just incrimented by 1 each time you go through the loop. As normal, there is some way to exit the loop, usually by some kind of Boolean expression. Some For loops allow you to just specify how many times you would like to do the loop, by providing a number and no Boolean expression.

To use the For…Next loop, there will also be a loop counter that keeps track of how many times through the loop the program has executed. Each time the code inside the loop is executed, the loop counter is automatically incremented by 1. Then an expression checks to see that the predetermined number of times has been reached.

The For loop (in most computer programming languages) takes the generic form of:

FOR counter in range(n)
statement(s)
ENDFOR

or

FOR (int counter = 0; boolean expresion; counter++)
statement(s)
ENDFOR

In this example program, the user is asked to enter a posative integer and the program will count how many times it goes through the loop until it reaches that number.

Top-Down Design for the For loop

Top-Down Design for While loop

Flowchart for the For loop

For loop flowchart

Pseudocode for the For loop

GET positive_integer
FOR (int counter = 0; counter < positive_integer; counter++)
SHOW counter
ENDFOR

Code for the For loop

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Copyright (c) 2020 Mr. Coxall All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program uses a for loop

#include <stdio.h>

int main() {
    // this function uses a for loop
    int positiveInteger;

    // input
    printf("Enter how many times to repeat: ");
    scanf("%d", &positiveInteger);
    printf("\n");

    // process & output
    for (int loopCounter = 0; loopCounter < positiveInteger; loopCounter++) {
        printf("%d time(s) through the loop.\n", loopCounter);
    }

    printf("\nDone.\n");
    return 0;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Copyright (c) 2020 St. Mother Teresa HS All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program uses a for loop

#include <iostream>

int main() {
    // this function uses a for loop
    int positiveInteger;

    // input
    std::cout << "Enter how many times to repeat: ";
    std::cin >> positiveInteger;
    std::cout << std::endl;

    // process & output
    for (int loopCounter = 0; loopCounter < positiveInteger; loopCounter++) {
        std::cout << loopCounter <<" time through loop." << std::endl;
    }

    std::cout << "\nDone." << std::endl;
    return 0;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/* Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program uses a for loop
*/

using System;

/*
 * The Program class
*/
class Program {
    static void Main() {
        // this function uses a do ... while loop

        int positiveInteger;

        // input
        Console.Write("Enter how many times to repeat: ");
        positiveInteger = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine();

        // process & output
        for (int loopCounter = 0; loopCounter < positiveInteger; loopCounter++) {
            Console.WriteLine(loopCounter + " time(s) through the loop.");
        }

        Console.WriteLine("\nDone.");
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
 * Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program uses a for loop
 */

package main

import (
	"fmt"
)

func main() {
	// this function uses a for loop

	var counter int // in go no need to set to 0, it automaticall is!
	var positiveInteger int

	// input
	fmt.Print("Enter how many times to repeat: ")
	fmt.Scan(&positiveInteger)
	fmt.Println()

	// process & output
	for counter < positiveInteger {
		fmt.Printf("%d time(s) through the loop.\n", counter)
		counter++ // a short form for: counter = counter + 1
	}

	fmt.Println("\nDone.")
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/*
 * This program uses a for loop
 *
 * @author  Mr Coxall
 * @version 1.0
 * @since   2020-09-01
 */

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    // this function uses a for loop

    // create Scanner object for user input
    Scanner scanner = new Scanner(System.in);

    // input
    System.out.print("Enter how many times to repeat: ");
    String positiveIntegerStr = scanner.nextLine();
    System.out.println();

    // process & output
    int positiveInteger = Integer.parseInt(positiveIntegerStr);

    for (int loopCounter = 0; loopCounter < positiveInteger; loopCounter++) {
      System.out.println("%d time(s) through the loop.".formatted(loopCounter));
    }

    // close the Scanner object
    scanner.close();
    System.out.println("\nDone.");
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
/* Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program uses a for loop
 */

const prompt = require("prompt-sync")()

let counter = 0

// input
const positiveIntegerStr = prompt("Enter how many times to repeat: ")
console.log("")

// process & output
const positiveInteger = parseInt(positiveIntegerStr)

for (var loopCounter = 0; loopCounter < positiveInteger; loopCounter++) {
  console.log(`${loopCounter} time(s) through the loop.`)
}

console.log("\nDone.")
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/usr/bin/env python3
"""
Created by: Mr. Coxall
Created on: Sep 2020
This module uses a for loop
"""


def main() -> None:
    """The main() function uses a for loop, returns None."""

    # input
    positive_integer = int(input("Enter how many times to repeat: "))
    print("")

    # process & output
    for loop_counter in range(positive_integer):
        print(f"{loop_counter} time through loop.")

    print("\nDone.")


if __name__ == "__main__":
    main()

Example Output

Code example output