Arrays: Difference between revisions
(Changed CL code to match other languages) |
(added BASIC) |
||
Line 7: | Line 7: | ||
Please discusss at Village Pump: {{vp|Arrays}}. |
Please discusss at Village Pump: {{vp|Arrays}}. |
||
=={{header|BASIC}}== |
|||
<lang qbasic>DIM myArray(10) AS INTEGER |
|||
myArray(0) = -1 |
|||
myArray(10) = 1 |
|||
PRINT myArray(0) |
|||
</lang> |
|||
=={{header|C++}}== |
=={{header|C++}}== |
||
Revision as of 22:13, 5 August 2009
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array.
In this task, the goal is to show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element. (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it.)
Please discusss at Village Pump: Arrays.
BASIC
<lang qbasic>DIM myArray(10) AS INTEGER
myArray(0) = -1 myArray(10) = 1
PRINT myArray(0) </lang>
C++
<lang cpp>int* myArray = new int[10];
myArray[0] = 1; myArray[1] = 3;
cout << myArray[1] << endl;</lang>
Dynamic
<lang cpp>vector<int> myArray2;
myArray2.push_back(1); myArray2.push_back(3);
myArray2[0] = 2;
cout << myArray2[0] << endl;</lang>
C#
<lang csharp>int[] array = new int[10];
array[0] = 1; array[1] = 3;
Console.WriteLine(array[0]);</lang>
Dynamic
<lang csharp>using System; using System.Collections;
ArrayList<int> array = new ArrayList<int>();
array.Add(1); array.Add(3);
array[0] = 2;
Console.WriteLine(array[0]);</lang>
Common Lisp
<lang lisp>(let ((array (make-array 10)))
(setf (aref array 0) 1 (aref array 1) 3) (print array))</lang>
Dynamic
<lang lisp>(let ((array (make-array 0 :adjustable t :fill-pointer 0)))
(vector-push-extend 1 array) (vector-push-extend 3 array) (setf (aref array 0) 2) (print array))</lang>
Perl
Dynamic
<lang perl>my @arr;
push @arr, 1; push @arr, 3;
$arr[0] = 2;
print $arr[0];</lang>
Python
Dynamic
<lang python>array = []
array.append(1) array.append(3)
array[0] = 2
print array[0]</lang>
Ruby
Dynamic
<lang ruby>arr = Array.new
arr << 1 arr << 3
arr[0] = 2
puts arr[0]</lang>
Tcl
Tcl's lists are really dynamic array values behind the scenes. (Note that Tcl uses the term “array” to refer to an associative collection of variables.) <lang tcl>set ary {}
lappend ary 1 lappend ary 3
lset ary 0 2
puts [lindex $ary 0]</lang> Note also that serialization is automatic on treating as a string: <lang tcl>puts $ary; # Print the whole array</lang>