Search⌘ K
AI Features

Arrays with Loops

Explore how to use for and while loops to access and manipulate array elements in C++. Understand how to build and process arrays through practical examples such as generating Fibonacci sequences, checking palindromes, and sorting values. This lesson helps you develop fundamental skills in array handling and loop control essential for programming 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:

C++
#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 ...