Arrays with Loops

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:

Press + to interact
vals = [-5, 'Ruby', 3.8]
print("Using loop variable as an array index","\n")
for i in [0,1,2]
print(vals[i]," ")
end
print("\n")
print("Directly accessing the elements","\n")
for v in vals
print(v," ")
end
print("\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 variable i.
  • 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, ... and length.

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: 0,1,1,2,3,5,8,13,21,34,0, 1, 1, 2, 3, 5, 8, 13, 21, 34, … . Here’s how to solve this problem:

  • Start with an empty array of nn elements.
  • Store 00 at the index number 00 and 11 at the index number 11.
  • Compute the next value by adding the two previous values. Consider the array name fib, and compute fib[2] = fib[0] + fib[1].
  • Keep performing the step above for each next element in the array until nn 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")
Generate the Fibonacci sequence using while loop

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 of n can’t be less than 1 or greater than 20.
  • One new item in the program above is fib = [0] * n. The syntax [0] * n is used to create an array of n elements, each having a value of 0.
  • This array of n zeros is stored in the variable fib. This is an easy way to generate large arrays or arrays of n values without having to write out too many individual values. We may choose any other value instead of 0 as needed.
  • The use of the second if statement checks the value of n. If it’s greater than 1, then 1 is assigned to fib[1].
  • We use the variable count to store the number of terms. The current number of terms is 2.
  • In the while loop, the statement fib[count] = fib[count - 2] + fib[count - 1] generates the Fibonacci sequence. We repeat this process while the value of count is less than n.

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!
Press + to interact
# For 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]
# Write your code here
# For 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]
# Write your code 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]
Press + to interact
# 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.
Press + to interact
fib = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]
# Write your program here.