The барои loop
In this lesson: you will repeat commands several times with a loop.
Lesson 10
барои loopбарои loopIn this lesson: you will repeat commands several times with a loop.
барои loopIn this lesson: you will repeat commands several times with 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 is the start: it runs once, before the loop.и <= 5 is the condition: the loop goes on while it is дуруст.и++ runs after each step: it makes и one bigger (и = и + 1).1тағ н = хонданиРақам();2тағ ҷамъ = 0;3барои (тағ и = 1; и <= н; и++) {4ҷамъ = ҷамъ + и;5}6чоп("Ҷамъ:", ҷамъ);
10
ҷамъ ("sum") is 0 before the loop, and at each step и is added to it. ҷамъ = ҷамъ + и can also be written shorter: ҷамъ += и.
How many times does чоп run in this loop?
1барои (тағ и = 0; и < 3; и++) {2чоп(и);3}
1тағ н = хонданиРақам();2барои (тағ и = 1; и <= 10; и++) {3чоп(н + " × " + и + " = " + н * и);4}
7
барои (тағ и = 1; и <= 5; и--). Here и gets smaller, so the condition is always true. The playground stops the program after a few seconds.; in the brackets of барои.Read the number н and print the numbers from 1 to н, each on a separate line.
Input: One number: н.
Output: The numbers from 1 to н.
Read the number н and print the sum of all the numbers from 1 to н.
Input: One number: н.
Output: The sum.
Read the number н and print its factorial: 1 × 2 × … × н. The factorial of 0 is 1.
Input: One number: н.
Output: The factorial.
Read the number н and print all the even numbers from 2 to н, each on a separate line.
Input: One number: н.
Output: The even numbers.