Menu
Coddy logo textTech

The 'for' Loop

Part of the Fundamentals section of Coddy's Dart journey — lesson 42 of 94.

The for loop in Dart executes code repeatedly for a specific number of iterations when you know exactly how many you need.

void main() {
  for (int i = 1; i <= 5; i++) {
    print(i);
  }
}

When you run this code, it will output:

1
2
3
4
5

For loops have three components:

for (initialization; condition; increment) {
  // Code to repeat
}
void main() {
  int sum = 0;
  for (int i = 1; i <= 5; i++) {
    sum += i;
  }
  print("Sum of numbers from 1 to 5: $sum");
}
Sum of numbers from 1 to 5: 15
challenge icon

Challenge

Beginner

In this challenge, you'll practice using the for loop in Dart to print a sequence of numbers.

Your task is to create a program that:

  1. Reads a single integer n from the input
  2. Uses a for loop to print all numbers from 1 to n, each on a new line
  3. After the sequence, prints the sum of all numbers from 1 to n

For example, if the input is 5, your program should output:

1
2
3
4
5
Sum: 15

Notice that each number is printed on a new line, and the sum is printed after all numbers with the format Sum: X where X is the calculated sum.

Cheat sheet

The for loop executes code repeatedly for a specific number of iterations:

for (initialization; condition; increment) {
  // Code to repeat
}

Basic example:

for (int i = 1; i <= 5; i++) {
  print(i);
}

Using for loop to calculate sum:

int sum = 0;
for (int i = 1; i <= 5; i++) {
  sum += i;
}
print("Sum: $sum");

Try it yourself

import 'dart:io';

void main() {
  // Read the input number
  String? input = stdin.readLineSync();
  int n = int.parse(input!);
  
  // TODO: Write a for loop that prints numbers from 1 to n
  
  // TODO: Calculate and print the sum of all numbers from 1 to n
  
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals