Arrays with Loops
Learn to use arrays with the help of loops in Ruby.
The for
loop with arrays
The individual values in an array are accessed through an index number. The for
loop variable can be used as an index number. However, the array values can also be used directly in the for
loop.
The following program demonstrates the various ways of accessing array elements:
vals = [-5, 'Ruby', 3.8]print("Using loop variable as an array index","\n")for i in [0,1,2]print(vals[i]," ")endprint("\n")print("Directly accessing the elements","\n")for v in valsprint(v," ")endprint("\n")mix = ['a',1,2.5,'i',50,6,'m',4.4,6.7,'s','@educative']print("Array index using \".length","\n")for v in [0...mix.length]print(mix[v]," ")end
In the code above:
- The first
for
loop accesses the array values with the help of the loop variablei
. - The second
for
loop directly accesses the array values. - The third
for
loop accesses the array values with the help of loop variable,v
, and the functions,...
andlength
.
The while
loop with array
We usually use the while
loop to deal with arrays when the number of iterations is not fixed. For a simple example, say we want to generate n
terms of a Fibonacci sequence and store it in an array, where n
is the user input.
A Fibonacci sequence is a sequence in which each number is the sum of the two preceding ones, except the first two terms.
Let’s start by noting a few terms of this sequence: . Here’s how to solve this problem:
- Start with an empty array of elements.
- Store at the index number and at the index number .
- Compute the next value by adding the two previous values. Consider the array name
fib
, and computefib[2] = fib[0] + fib[1]
. - Keep performing the step above for each next element in the array until elements are generated.
We can demonstrate this process with the help of the following code:
print("Enter the number of terms (maximum 20) for the Fibonacci sequence: ") n = Integer(gets) if n < 2 or n > 20 print("It seems the number of terms for the Fibonacci sequence has an invalid value:",n,"\n") else fib = [0] * n print("First ",n," terms of Fibonacci sequence are:","\n") if n > 1 fib[1] = 1 # Assigning 1 to 2nd index of array fib end count = 2 while count < n # This loop will terminate when the count is not less than n fib[count] = fib[count-2] + fib[count-1] # Adding last two values count += 1 end print(fib,"\n") end print("*** Finish generating Fibonacci Numbers ***\n")
In the code above:
- The variable,
n
, shows the total number of terms in the Fibonacci sequence input by the user. - The use of the first
if
statement means that the value ofn
can’t be less than1
or greater than20
. - One new item in the program above is
fib = [0] * n
. The syntax[0] * n
is used to create an array ofn
elements, each having a value of0
. - This array of
n
zeros is stored in the variablefib
. This is an easy way to generate large arrays or arrays ofn
values without having to write out too many individual values. We may choose any other value instead of0
as needed. - The use of the second
if
statement checks the value ofn
. If it’s greater than1
, then1
is assigned tofib[1]
. - We use the variable
count
to store the number of terms. The current number of terms is2
. - In the
while
loop, the statementfib[count] = fib[count - 2] + fib[count - 1]
generates the Fibonacci sequence. We repeat this process while the value ofcount
is less thann
.
Practice array manipulation with loops
Following are a few program examples to practice writing the programs in Ruby to play with arrays using loops. There are built-in operations for some tasks mentioned below. However, doing them without those built-in functions is for the practice of using arrays.
By clicking the “Show Solution” button, you may find a program that solves the respective problem. You can copy and paste the given solution into the code widget to make sure the output of your solution matches the given solution. There may be several ways of writing correct solutions in programming.
Palindrome test
Write a program that checks whether or not an array is a palindrome.
Sample input 1
u = [1,2,3,4,5,6,7,8,9,10,11,12,21,11,10,9,8,7,6,5,4,3,2,1]
Sample output 1
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 21, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] is NOT a palindrome!
Sample input 2
v = [1,2,3,4,5,6,7,8,9,10,11,12,11,10,9,8,7,6,5,4,3,2,1]
Sample output 2
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] is a PALINDROME!
# Write your program here.
Sort an array
Sorting is a technique to arrange the list of items into a particular order.
Write a program to sort the array values in ascending order. An array with integer values in it is given, which has to be sorted in the order such that the smallest element is at the start of the array and the greatest at the end.
Sample input
[5,2,7,9,1]
Sample output
The sorted array
[1, 2, 5, 7, 9]
# Write your program here.
Fibonacci sequence
Write a program to check if an array contains the terms of the Fibonacci sequence.
Sample input 1
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 60, 987, 1597, 2584, 4181]
Sample output 1
It's not a Fibonacci sequence due to the value 60 at index 15.
Sample input 2
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]
Sample output 2
Hurrah ... we've got a Fibonacci array.
# Write your program here.