Arrays
An array is a collection of items stored in contiguous memory locations. It's an aggregate data structure that is designed to store a group of objects of the same type. It's the most efficient data structure for storing and accessing a sequence of objects.
How to declare an array
Create an array that holds integer values:
Output
Or create an array that holds string values:
Output
Note: All elements must have the same type. The following code will not compile.
Output
Create an empty array
If you want to create a new empty array, just declare []
followed by the data type.
Accessing element of the array
Output
Append a value to an array
<<
is an operator that appends a value to the end of the array.
Output
It can also append an entire array.
Output
Length/size of an array
.len
method returns the length of the array.
Output
In operator
in
check if an element is inside an array.
Output
Slicing an array
It's easy to slice an array in V. You can slice an array with the default V slicing feature without having to call the slice ()
method. The syntax is like this my_array[start..end]
If you want to slice from the start of the index, just ignore it to put 0
and using instead my_array[..end]
or my_array[start..]
.
Exercises
Write a V program to store elements in an array and print it.
Write a V program to read n number of values in an array and display it in reverse order.
Write a V program to find the sum of all elements of the array.
Write a V program to copy the elements of one array into another array.
Write a V program to count a total number of duplicate elements in an array.
Last updated