Lesson 10

The барои loop

The барои loop

In this lesson: you will repeat commands several times with a loop.

The whole lesson on one page

The барои loop

In this lesson: you will repeat commands several times with a loop.

What is a loop?

To print the numbers from 1 to 5, you can write five чоп commands. But what about 1 to 1000? To repeat things, you need a loop (давра). барои means "for":

1барои (тағ и = 1; и <= 5; и++) {
2 чоп(и);
3}

The brackets of барои have three parts, separated by ;:

  1. тағ и = 1 is the start: it runs once, before the loop.
  2. и <= 5 is the condition: the loop goes on while it is дуруст.
  3. и++ runs after each step: it makes и one bigger (и = и + 1).

Sum of the numbers from 1 to n

1тағ н = хонданиРақам();
2тағ ҷамъ = 0;
3барои (тағ и = 1; и <= н; и++) {
4 ҷамъ = ҷамъ + и;
5}
6чоп("Ҷамъ:", ҷамъ);
Input
10

ҷамъ ("sum") is 0 before the loop, and at each step и is added to it. ҷамъ = ҷамъ + и can also be written shorter: ҷамъ += и.

Sum of the numbers from 1 to n

How many times does чоп run in this loop?

1барои (тағ и = 0; и < 3; и++) {
2 чоп(и);
3}
  • 2
  • 3
  • 4
  • 0

Multiplication table

1тағ н = хонданиРақам();
2барои (тағ и = 1; и <= 10; и++) {
3 чоп(н + " × " + и + " = " + н * и);
4}
Input
7

Common mistakes

  • A loop that never ends: барои (тағ и = 1; и <= 5; и--). Here и gets smaller, so the condition is always true. The playground stops the program after a few seconds.
  • A comma instead of ; in the brackets of барои.

Task: From 1 to n

Read the number н and print the numbers from 1 to н, each on a separate line.

Input: One number: н.

Output: The numbers from 1 to н.

Task: Sum from 1 to n

Read the number н and print the sum of all the numbers from 1 to н.

Input: One number: н.

Output: The sum.

Task: Factorial

Read the number н and print its factorial: 1 × 2 × … × н. The factorial of 0 is 1.

Input: One number: н.

Output: The factorial.

Task: Even numbers

Read the number н and print all the even numbers from 2 to н, each on a separate line.

Input: One number: н.

Output: The even numbers.