Overview
In this example, you will learn how to create an array and use while loop to print out all the elements in the array
Example Code
Output
Start Codon greater than 1000000:
2755959
2755557
1371107
1370487
1370487
1369069
1885152
1079446
Decode
>> Line 4: my @startCodon;
An array is a list of elements. You can declare an array with @arrayname just like you declare a variable with $variablename.
>>Line 7: @startCodon=(1674782,1079446,346422,483161,1885152,1369069,1370487,137085,1370487,1371107,275553,275337,2755557,2755959,528407);
You can put elements into an array in many different ways. One way is to put a list of elements insid (). Eg, @myArray=(element1,element2,element3,element4)
To retrieve individual elements from an array, you use the index number starting from 0.
For the array @startCodon, $startCodon[0] will give you 1674782, $startCodon[1] will give you 1079446, etc.
Notice that when you retrieve individual elements from an array, you use $ not @ .
>>Line 10: my $index=scalar(@startCodon);
the function scalar(array) gives you the total number of elements stored in that array
>> Line 15: while loop
while(condison is true)
{
do sth
(change the condition)
}
In our example, the condition is ( $index > 0), we start the loop with $index=number of elements in the array=15 which is greater than 0.
At the end of each loop, we reduce $index by 1. ($index-- is the same as $index=$index-1) .
Eventually, after 15 loops, $index will become 0, and the condition ($index>0) is no longer true.
When writing a loop, you will need to define a condition and set it to be true initially. This condition must eventually become false, or else the loop will be infinite.
Exercise Six
Write a program to create array of 100 elements with the first element being 0, second element being 1,third element=second element+first element,
fouth element=thrid element+second element, fifth element= fouth element + third element ,etc.
In general, Kth element =Kth-1 element + Kth-2 element where k>1 (Fibonacci number)
For example, your first 10 elements will look like this (0,1,1,2,3,5,8,13,21,34 )
Print all 100 elements in this array.