MosheZada
MosheZada

Reputation: 2399

Loop through an array in V

How can I loop over an array of strings in the V programming language?

For example:

langs := ['python', 'java', 'javascript']

Upvotes: 6

Views: 1685

Answers (2)

navule
navule

Reputation: 3624

Method 1: For loop with an index

langs := ['python', 'java', 'javascript']

for i, lang in langs {
    println('$i) $lang')
}

Method 1 Output:

0) python
1) java
2) javascript

Try method 1 on the V main site's playground here.

Method 2: For loop without an index

langs := ['python', 'java', 'javascript']

for lang in langs {
    println(lang)
}

Method 2 Output:

python
java
javascript

Try method 2 on the V main site's playground here.

Method 3: While loop style iteration using for in V

You can do this too. The following loop is similar to a while loop in other languages.

mut num := 0
langs := ['python', 'java', 'javascript']

for{
    if num < langs.len {
        println(langs[num])
    }
    else{
        break
    }
    num++
}

Method 3 Output:

python
java
javascript

Try method 3 on the V main site's playground here.

Method 4: Looping over elements of an array by accessing its index

langs := ['python', 'java', 'javascript']

mut i := 0
for i < langs.len {
    println(langs[i])
    i++
}

Method 4 Output:

python
java
javascript

Try method 4 on the V main site's playground here

Method 5: Traditional C-Style looping

As suggested by @Astariul in the comments:

langs := ['python', 'java', 'javascript']

for i := 0; i < langs.len; i++ {
    println(langs[i])
}

Method 5 Output:

python
java
javascript

Try method 5 on the V main site's playground here.

You can check out this playlist for more interesting V tutorials.

Upvotes: 8

MosheZada
MosheZada

Reputation: 2399

V has only one looping construct: for. In order to loop over the array langs, you need to use the for loop.

langs := ['python', 'java', 'javascript']
for lang in langs {
    println(lang)
}

The for value in the loop is used for going through elements of an array. If an index is required, an alternative form, for index, value in, can be used.

Upvotes: 1

Related Questions