loopsvlang

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']


Solution

  • 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.