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// Copyright (c) 2020 Mr. Coxall All rights reserved.
 2//
 3// Created by: Mr. Coxall
 4// Created on: Sep 2020
 5// This program uses a for loop
 6
 7#include <stdio.h>
 8
 9int main() {
10    // this function uses a for loop
11    int positiveInteger;
12
13    // input
14    printf("Enter how many times to repeat: ");
15    scanf("%d", &positiveInteger);
16    printf("\n");
17
18    // process & output
19    for (int loopCounter = 0; loopCounter < positiveInteger; loopCounter++) {
20        printf("%d time(s) through the loop.\n", loopCounter);
21    }
22
23    printf("\nDone.\n");
24    return 0;
25}

Example Output

Code example output