Skip to main content
Programming from zero

Loops theory + first problem: print every port from 8000 to 8010

easyLoops Must-do

Problem statement

A loop repeats a block of instructions without you writing it out by hand each time. Instead of eleven separate print lines for ports 8000 through 8010, a loop runs one print line eleven times, changing a variable each time through.

flowchart LR A["port = 8000"] --> B{"port <= 8010?"} B -->|"yes"| C["print port"] C --> D["port += 1"] D --> B B -->|"no"| E["done"] classDef start fill:#DBEAFE,stroke:#2563EB,color:#1E3A8A classDef check fill:#FEF3C7,stroke:#D97706,color:#92400E classDef action fill:#E0E7FF,stroke:#4F46E5,color:#312E81 classDef done fill:#D1FAE5,stroke:#059669,color:#065F46 class A start class B check class C action class D action class E done

Common mistake: an off-by-one error, stopping one short of the last value.

TEXT
Wrong (Python): for port in range(8000, 8010):

Python's range(8000, 8010) stops before 8010, so it prints up to 8009 only. To include 8010, the range needs to end one past it: range(8000, 8011). Java and C++ don't have this specific trap the same way, since their loop condition is written directly (port <= 8010), but it's worth double-checking either way.

Your task: print every port number from 8000 to 8010, inclusive, one per line.

Approach

Each language counts up with a loop, the syntax differs but the idea is identical: start at 8000, keep going while the value is at most 8010, print, then move to the next number.

  • Python's for port in range(8000, 8011): handles the counting automatically; remember the range's second number is exclusive, so it needs to be one past the last value you want.
  • Java and C++ use a for loop with all three parts spelled out: the starting value, the condition to keep looping, and how to move to the next value.
for port in range(8000, 8011):
    print(port)