# 6.3 — Arrays and loops

Consider the case where we want to find the average test score of a class of students. Using individual variables:

That’s a lot of variables and a lot of typing -- and this is just 5 students! Imagine how much work we’d have to do for 30 students, or 150.

Plus, if a new student is added, a new variable has to be declared, initialized, and added to the totalScore calculation. Any time you have to modify old code, you run the risk of introducing errors.

Using arrays offers a slightly better solution:

This cuts down on the number of variables declared significantly, but totalScore still requires each array element be listed individually. And as above, changing the number of students means the totalScore formula needs to be manually adjusted.

If only there were a way to loop through our array and calculate totalScore directly.

Loops and arrays

In a previous lesson, you learned that the array subscript doesn’t need to be a constant value -- it can be a variable. This means we can use a loop variable as an array index to loop through all of the elements of our array and perform some calculation on them. This is such a common thing to do that wherever you find arrays, you will almost certainly find loops! When a loop is used to access each array element in turn, this is often called iterating through the array.

Here’s our example above using a for loop:

This solution is ideal in terms of both readability and maintenance. Because the loop does all of our array element accesses, the formulas adjust automatically to account for the number of elements in the array. This means the calculations do not have to be manually altered to account for new students, and we do not have to manually add the name of new array elements!

Here’s an example of using a loop to search an array in order to determine the best score in the class:

In this example, we use a non-loop variable called maxScore to keep track of the highest score we’ve seen. maxScore is initialized to 0 to represent that we have not seen any scores yet. We then iterate through each element of the array, and if we find a score that is higher than any we’ve seen before, we set maxScore to that value. Thus, maxScore always represents the highest score out of all the elements we’ve searched so far. By the time we reach the end of the array, maxScore holds the highest score in the entire array.

Mixing loops and arrays

Loops are typically used with arrays to do one of three things:
1) Calculate a value (e.g. average value, total value)
2) Search for a value (e.g. highest value, lowest value).
3) Reorganize the array (e.g. ascending order, descending order)

When calculating a value, a variable is typically used to hold an intermediate result that is used to calculate the final value. In the above example where we are calculating an average score, totalScore holds the total score for all the elements examined so far.

When searching for a value, a variable is typically used to hold the best candidate value seen so far (or the array index of the best candidate). In the above example where we use a loop to find the best score, maxScore is used to hold the highest score encountered so far.

Sorting an array is a bit more tricky, as it typically involves nested loops. We will cover sorting an array in the next lesson.

Arrays and off-by-one errors

One of the trickiest parts of using loops with arrays is making sure the loop iterates the proper number of times. Off-by-one errors are easy to make, and trying to access an element that is larger than the length of the array can have dire consequences. Consider the following program:

The problem with this program is that the conditional in the for loop is wrong! The array declared has 5 elements, indexed from 0 to 4. However, this array loops from 0 to 5. Consequently, on the last iteration, the array will execute this:

But scores[5] is undefined! This can cause all sorts of issues, with the most likely being that scores[5] results in a garbage value. In this case, the probable result is that maxScore will be wrong.

However, imagine what would happen if we inadvertently assigned a value to array[5]! We might overwrite another variable (or part of it), or perhaps corrupt something -- these types of bugs can be very hard to track down!

Consequently, when using loops with arrays, always double-check your loop conditions to make sure you do not introduce off-by-one errors.

Quiz

1) Print the following array to the screen using a loop:

Hint: You can use std::size (as of C++17) or the sizeof() trick (prior to C++17) to determine the array length.

2) Given the array in question 1:

Ask the user for a number between 1 and 9. If the user does not enter a number between 1 and 9, repeatedly ask for an integer value until they do. Once they have entered a number between 1 and 9, print the array. Then search the array for the value that the user entered and print the index of that element.

You can test std::cin for invalid input by using the following code:

3) Modify the following program so that instead of having maxScore hold the largest score directly, a variable named maxIndex holds the index of the largest score.

Quiz solutions

### 244 comments to 6.3 — Arrays and loops

• FarKiD

Hi, in quiz 2, there are no values considered for array [0], also most of my inputs, don't match the array numbers, for example when I put 8, it gives back 4, or when I put 2 in std::cin, it puts 5 on screen, instead of 7

• Arrays start at index 0

• FarKiD

I do understand, but consider these 3 times I ran the program :

https://imgur.com/a/ZY1fiTN

• That's the expected behavior. What don't you understand about it? Which output did you expect?

• FarKiD

isn't 2 supposed to give 7? how does it even give back 5?
and I just put 4, and I get a 0? I don't even have a zero in my array!

• It prints the index of the number you give it, not the other way around.

• FarKiD

I think I got it, thanks for your time, you are awesome :)

• Max Morgan

For quiz 2, I tried the method below. Guess was only known in the scope of my first function. Is there a way to bring the value of guess into main so that I can reference it in this second for loop? EDIT: I moved guess above the function and it works, but I know this is bad because it's a global variable. Thank you Nascar and Alex

• * Line 22, 24, 26, 30, 36: Initialize your variables with brace initializers. You used copy initialization.
* Line 5: Initialize your variables with brace initializers.
* Line 38: Limit your lines to 80 characters in length for better readability on small displays.
* Remove the ifs in @main

@enterNum never returns false, ie. the return value is unused. Change it to return @guess.

• buront

In the first example of loops and arrays,I tried to initialize const int by using {std::size(scores)}.
But it get an error about size.However, using = means no error.
Why is this?

• Alex

This happens because std::size returns an object of type size_t. A size_t is an unsigned value, whereas your integer is signed. Uniform initialization disallows narrowing conversions, and converting an unsigned value to a signed one is considered a narrowing conversion. Copy initialization still works because narrowing conversions are allowed.

• buront

Thanks Alex!

• magaji::hussaini

My solution snippets:
quiz1 & quiz2:

quiz3

• Quiz 2
* Line 5, 6: Initialize your variables. Enable compiler warnings and fix them.
* Line 8: @while wants a bool, give it a bool.
* Line 13

is easier to understand
* Use your editor's auto-formatting feature

Quiz 3
Looking good, apart from the formatting and that "if" floating around

I see you're using short ints. If you want to save memory, you might as well use @std::int_fast8_t.

• magaji::hussaini

Thanks!  ...copy that.

• Shawn

On quiz 3.

for (int student = 0; student < numStudents; ++student)

couldnt it be:

for (int student = 1; student < numStudents; ++student)

since you have maxIndex = 0; (skips first cycle).

• Alex

Yep. Quiz answer updated. Thanks for pointing that out.

• CoderC++

Why my shit broken?

#include <iostream>
#include <string>
using namespace std;

int main()
{
//Declaring Variables
int userDays;
float userTemp;

//Declaring the array
int array1[365] = {}; //Array for the Year

/*
DO { Please input temp for
Specific Day (1 - 365)

Enter 999 to quit.
}

While (user days <365)
enter temp
enter 999 to quit

*/

do
{
cout << "Please enter the Day you are inputing (1-365)" << endl;
cin >> userDays;

//Line Spacing
cout << "\n";
cout << "\n";

cout << "Please enter the Temperature" << endl;
cin >> userTemp;
cout << "\n\n";

array1[userDays] = userTemp;
}

while ((userDays <= 365) && (userDays >= 1));
for (int j = 0; j < 366; j++)
{
if (array1[j] != 0)
{
cout << "Day: " << userDays << endl;
cout << "Temperature: " << array1[userDays] << endl; //displays information

cout << "\n\n";
}
}

//prints the array from Void
return 0; //kills variables
}

• Sohini Ghosh

I tried to solve the 2nd question with a slightly different approach, but it is producing an infinite loop. Can you please help me out?

The solution to your problem is in lesson 1.4.

• marvix

Hi! This is my solution for quiz 2, any advice?

• Hi Marvix!

* Line 5: Use a while(true) loop
* Line 11: Don't pass 32767. Read the documentation of @std::basic_istream::ignore
* Line 23, 31, 32, 33: Initialize your variables with uniform initialization
* @findIndex will crash if @array doesn't contain @ins. You're checking @ins before calling @findIndex, so this won't happen. Either add a comment to @findIndex explaining that the caller must verify that the array contains @ins or pass the array's length to @findIndex and check there.
* Line 23: unsigned will cause you more trouble than good
* Line 24: Comparison of short to int
* Use ++prefix unless you need postfix++
* Line 24:

• hoon

Hi

• Hi Hoon!

* Initialize your variables with uniform initialization.
* Don't pass 32767 to @std::cin.get. Read the documentation or the lesson that introduced it.
* Missing trailing line feed in line 41

Structure and logic look good

• hoon

Have a good night

• Nayab Anjum

Did i do something wrong in below code for question 2?
Also both mine and your code doesnot work if we type any character(e.g 'e'). How do we fix this error? Kindly reply asap.

• Hi Nayab!

* Don't use "using namespace"
* Initialize your variables with uniform initialization
* Don't pass 32767 to @std::cin.ignore. See the documentation.
* Use ++prefix unless you need postfix++
* Line 31 is not part of the conditional block. Use the auto-formatting feature of your IDE and use curly brackets for if-statements.
* Inconsistent use of '\n' and @std::endl

> mine and your code doesnot work if we type any character
What do you mean by "doesn't work"? What do you expect the program to do, what does it actually do?

• My solution
2.
#include<iostream>

int main()
{
int number;
while(true)
{
std::cout<<"Enter an number between 1 and 9: ";
std::cin>>number;
if((number>=1)&&(number<=9))
break;
if(std::cin.fail())
{
std::cin.clear();
std::cin.ignore(32767,'\n');
}
}
int array[]={1,2,3,4,5,6,7,8,9};
int length=sizeof(array)/sizeof(array[0]);
for(int index=0;index<length;++index)
std::cout<<array[index]<<" ";
std::cout<<"\n";
for(int index=0;index<length;++index)
{
if(array[index]==number)
std::cout<<"The index of element "<<number<<" is "<<index<<std::endl;
}

return 0;
}
3.
#include<iostream>

int main()
{
int scores[]={84,92,76,81,56};
const int numStudents=sizeof(scores)/sizeof(scores[0]);

int maxIndex=0;

for(int student=0;student<numStudents;++student)
{
if(scores[student]>scores[maxIndex])
maxIndex=student;
}
std::cout<<"The best score was stored in index "<<maxIndex<<"\n";

return 0;
}

• Hi!