Search…
Looping Constructs
There's only one type of loop in V language, like Go which can be used in many ways.

for loop

for loops offer a quick and easy way to do something repeatedly. They're handy, if you want to run the same code over and over again, each time with a different value. You can think of a loop as a computerized version of the game where you tell someone to take X steps in one direction then Y steps in another; for example, the idea "Go five steps to the east" could be expressed this way as a loop:
1
for i := 0; i < 5; i++ {
2
println('Walking one step')
3
}
Copied!
V has the for looping construct and the loop can be written in different ways:
  1. 1.
    in operator for array/map
1
ages := [18, 25, 32, 43, 50]
2
3
for age in ages {
4
println(age)
5
}
Copied!
Note: The value is read-only.
  1. 1.
    for loop with a condition
This is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. There are no parentheses surrounding the condition, and the braces are always required.
1
mut factorial := 1
2
mut counter := 1
3
4
for {
5
counter++
6
if counter > 5 {
7
println(factorial)
8
break
9
}
10
factorial = factorial * counter
11
}
12
13
println(counter)
Copied!
Output
1
120
2
6
Copied!
A for loop with a break statement can always be made shorter by placing the inverse condition right after for, making it equivalent with the while statement in other languages.
1
mut factorial := 1
2
mut counter := 1
3
4
for counter <= 5 {
5
factorial = factorial * counter
6
counter++
7
}
8
println(factorial)
9
println(counter)
Copied!
Output
1
120
2
6
Copied!
  1. 1.
    Traditional C style
1
mut factorial := 1
2
mut counter := 1
3
4
for counter = 1; counter < 6; counter++ {
5
factorial = factorial * counter
6
if counter == 5 {
7
print(factorial)
8
continue
9
}
10
println(counter)
11
}
Copied!
  1. 1.
    Infinite Loop
for loop can also be infinite
1
for {
2
println('foo')
3
}
Copied!

Exercises

  1. 1.
    Write a V program to display the first 10 natural numbers.
  2. 2.
    Write a V program to find the sum of first 10 natural numbers.
  3. 3.
    Write a V program to print the integers inside an array and also print their mean.
  4. 4.
    Write a V program to read 10 numbers from keyboard and find their sum and average.
  5. 5.
    Write a V program to display the cube of the number upto given an integer.
Copy link