Introduction to Loops
Learn the loops for a fixed number of iterations in Ruby.
We'll cover the following...
Repetition
The repetition of an instruction or a group of instructions is a commonly encountered phenomenon in programming called a loop. As an example, say we want our program to perform the following tasks:
- To read a document or data file line by line repeatedly until the end of the file.
- To draw an image pixel by pixel repeatedly using color values that show it on the screen.
- To iterate through a collection of variables one by one to process its values.
- To compute a result by applying a formula to several values.
The for loop
Let’s say we want to display integers from to . We can simply display the numbers to one by one using the print() statement. We can also use one variable and print its value repeatedly by changing the value of the variable, as shown below:
The code above clearly shows the repetitive use of print(a). The benefit of using a single variable is that we can convert this repetition into a for loop. In Ruby, we use a for loop to perform a process repeatedly for a fixed number of iterations. Let’s demonstrate this in the following program:
The for loop causes lines 1 and 2 to be repeated five times. So, we can say the loop has five iterations.
In the code above:
- We use
aas a variable that takes the values provided by the operatorin. - The
inoperator picks the values from[0,1,2,3,4]one by one at each iteration. - The body of the loop starts after specifying the values in the
forstatement. - The body of the loop contains only one statement,
print(a), caused by the indentation.
Let’s take an example of generating the first five non-negative even numbers—0, 2, 4, 6, and 8.
The end statement after lines 2 and 3 shows that these lines are the body of the loop.
Simple loops practice
The following are a few example programs to practice writing for loops in Ruby. The “Show Solution” button will provide one possible program that solves the respective problem. You can copy and paste the given solution into the code widget to execute it. It helps to verify that your solution’s output matches the given solution. There might be several ways of writing correct solutions in programming.
Odd numbers
Write a program that shows the first five odd numbers ,,,, and .
Arithmetic sequence
An arithmetic sequence is an ordered set of numbers that have a common difference between each consecutive term.
Write a program that shows the first five terms of the arithmetic sequence , , , , and .
Harmonic sequence
A harmonic sequence is an ordered set of numbers that have a common difference between the reciprocals of each consecutive term.
Write a program that shows the first five terms of the harmonic sequence , , , , and .
Geometric sequence
A geometric sequence is an ordered set of numbers that have a common multiplier between each consecutive term.
Write a program that shows the first five terms of the geometric sequence , , , , and .