Solution Review: Sequences and Loops

Learn to print different sequences using loops.

Printing number sequences using loops

In this lesson, we’ll go through the solutions of the problems in the previous lesson.

Multiples of 10

Our code should print the following sequence:

10 20 30 40 50 60

Solution

Let’s take a look at the solution.

Press + to interact
/*
This program should print the above number sequence
*/
#include<iostream>
using namespace std;
int main()
{
int limit = 6;
for(int i = 1; i <= limit; i++)
{
cout << i * 10 << " ";
}
return 0;
}

The number sequence above is simple. We use the for loop to print the sequence till the appropriate number.

In the editor above, in line 11, we initialize the i variable to 1. The condition i <= limit, in the same line, executes the body of the loop as long as i is less than or equal to the limit (6, in this case) entered by the user. We display the first six multiples of 10 by multiplying 10 with i which is initially 1 and is incremented by 1 after each iteration till it is less than or equal to 6. The incremental step i++ increments i by 1 after each iteration.

Odd sequence

Our code should print the following sequence:

1 3 5 7 9 11

Solution

Let’s take a look at the solution.

Press + to interact
#include<iostream>
using namespace std;
int main()
{
int limit = 11;
for(int i = 1; i <= limit; i+=2)
{
cout << i << " ";
}
return 0;
}

The above number sequence is also pretty straightforward. We get the next number by incrementing it by 2, that is, we’ll use i+=2.

Arithmetic sequence

Our code should print the following sequence:

1 1 3 6 5 11 7 16

Solution

Let’s take a look at the solution.

Press + to interact
#include<iostream>
using namespace std;
int main()
{
int first = 1;
int second = 1;
for(int i = 1; i <= 4; i++)
{
// printing the first and second numbers
cout << first << " ";
cout << second << " ";
// incrementing the first by 2 and second by 5
first = first + 2;
second = second + 5;
}
return 0;
}

In the number sequence above, we can see two different patterns. There is a number sequence of odd numbers 1, 3, 5, 7,… with the difference of 2 and then another sequence of 1, 6, 11, 16,… with the difference of 5.

So, to solve this exercise, we declare and initialize two variables first and second as the first two numbers of the sequence. Inside the body of the loop, we display the first and second variables (lines 12 and 13) and then increment the first number by 2 in line 15 and increment the second number by 5 in line 16.