म
MarathiCodeby Sprout Tech
Documentation topicsLoops
MarathiCode v0.2.0

Loops

पर्यंत व साठी

MarathiCode has two loops: पर्यंत (while) and साठी (counted for loop).

पर्यंत (while)

Repeats a block as long as the condition is true. The condition is checked before every iteration.

while.mr
चल i = 1
पर्यंत i <= 5 {
    छापा(i)
    i = i + 1
}
Output (आउटपुट)
1
2
3
4
5
sum.mr
चल i = 1
चल बेरीज = 0
पर्यंत i <= 10 {
    बेरीज = बेरीज + i
    i = i + 1
}
छापा("१ ते १० ची बेरीज: " + बेरीज)
Output (आउटपुट)
१ ते १० ची बेरीज: 55
Write i = i + 1, not चल i = i + 1, inside the loop. With चल a new i is created inside the block each time and the outer i never changes, so the loop never ends.

साठी (for)

A साठी loop has three parts in parentheses, separated by semicolons:

for_syntax.mr
साठी (सुरुवात; अट; बदल) {
    // ...
}
  • सुरुवात (start) runs once: an assignment such as i = 0 or चल i = 0.
  • अट (condition) is checked before each iteration.
  • बदल (update) runs after each iteration. It must be an assignment such as i = i + 1; there is no i++.
for.mr
साठी (i = 1; i <= 5; i = i + 1) {
    छापा(i * 10)
}
Output (आउटपुट)
10
20
30
40
50

Counting down and stepping by more than one work the same way:

for_down.mr
साठी (i = 10; i > 0; i = i - 3) {
    छापा(i)
}
Output (आउटपुट)
10
7
4
1

Nested loops and lists

nested_for.mr
चल matrix = [[1, 2], [3, 4]]
साठी (i = 0; i < लांबी(matrix); i = i + 1) {
    साठी (j = 0; j < लांबी(matrix[i]); j = j + 1) {
        छापा("matrix[" + i + "][" + j + "] = " + matrix[i][j])
    }
}
Output (आउटपुट)
matrix[0][0] = 1
matrix[0][1] = 2
matrix[1][0] = 3
matrix[1][1] = 4

The loop variable

  • If the loop variable does not exist yet, it belongs to the loop and disappears afterwards.
  • If a variable with that name already exists outside, the loop uses and updates it.
  • साठी (चल i = 0; …) always creates a new variable for the loop, leaving any outer i unchanged.
loop_variable.mr
चल i = 100
साठी (i = 0; i < 3; i = i + 1) {
}
छापा(i)
साठी (चल i = 0; i < 10; i = i + 1) {
}
छापा(i)
Output (आउटपुट)
3
3

To leave a loop early or skip to the next iteration, see Break & Continue.