...

/

Arrays with Loops

Arrays with Loops

Learn to use arrays with the help of loops in C++.

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.

The following program demonstrates accessing the array elements using counter-controlled loop:

Press + to interact
#include <iostream>
#include<string>
using namespace std;
int main()
{
string vals[] = {"-5", "C++", "3.8"};
cout << "Accessing an array with for loop: " << endl;
for (int i = 0; i < 3; i++)
{
cout << vals[i] << endl;
}
return 0;
}

In the code above:

  • The for loop accesses the array values with the help of the loop variable i.

The while loop with arrays

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, … ...