Search

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:

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 a number until they do. Once they have entered a number between 1 and 9, print the array. Then search the array for the number 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

1) Show Solution

2) Show Solution

3) Show Solution

6.4 -- Sorting an array using selection sort
Index
6.2 -- Arrays (Part II)

108 comments to 6.3 — Arrays and loops

  • Chad

    Shouldn’t you put a break in your if statement? If we know that each element of naArray is unique, we only need to search until we find what we want. Searching the rest of the array just wastes time.

    • Yup, if we can assume that each element of naArray is unique, then we could terminate the loop after finding an element that matches. I will clarify the solution.

  • Tom

    Hello Alex -

    Would this also be a correct way to do the search?:

    Thanks!

    • Your code is not quite correct -- what happens if it doesn’t find the number the user entered? In that case, iii will be 10 when the loop exits, and your code will still print that the number has index 10, which is not a valid index.

      As an aside, using a for loop to iterate through an array is usually better than a while loop because it contains the initialization and increment all within one statement, making it less likely you’ll forget them.

  • John

    The user is asked to enter a number between 1 and 9, but the array is indexed by 0 to 8, and the for loop runs from 0 to 8. This doesn’t make sense to me. Is this an error?

    • In C++, all arrays are 0-based, meaning the first element is numbered 0. In regular life, if we have 9 items, we’d count them like this: 1 2 3 4 5 6 7 8 9. However, in C++, we begin counting at 0, so we count 9 items like this: 0 1 2 3 4 5 6 7 8. That’s why the array is indexed 0 to 8.

    • Well, I actually used anArray[nNumber - 1] to give the correct element.

  • Zak

    Thanks a lot for these very helpful tutorials! Much appreciated.

  • Ben

    So trying to access an undefined array value (like

    in your example) will not return a compiler error?
    How come? It seems pretty dangerous.

    • anArray[5] won’t cause a compiler error, and it IS dangerous. C++ does not do any sort of compile-time bounds checking on it’s arrays -- and perhaps worse, it doesn’t do any runtime bounds checking either! This is one of those areas that definitely falls under “trust the programmer”.

      The underlying reason is due to the fact that arrays are implemented as pointers, and [] is implemented as a pointer addition operation. You’ll learn more about this in lesson 6.8.

      Once you learn about C++ classes, you’ll be able to write your own array classes that look and feel exactly like C++ built-in arrays, but can have additional safety features like runtime range checking.

  • runner

    Isn’t it better to do the array printing and the searching in the same loop?

    Also, entering a char input is leading to an infinite loop, why?

    • For efficiency purposes, yes, it’s better to only loop through the array once instead of twice. I personally would have written it the way you did, but I opted for a quiz solution that conformed more closely to the way the question was worded.

      As to your infinite loop question, I answered that one here. The issue here is the same.

  • Shai

    I’ve already fixed the following silly problem, but I thought I might as well share it 🙂

    It’s just wrong to try to do too many things with one variable. 😛

    It left me baffled for a while because most user inputs would print the correct element!

    • Yup, generally speaking it’s good to have a variable keep track of one and only one thing. Here, your nUserNum has two jobs: to accept the user input, and then later to store the index of the matching array element, which is a totally different thing!

      Although it may have taken you a while to find and fix the issue, it’s a good lesson to learn.

  • Mithrildor

    I made this one for question 2 is this oen right too?

    It looks easir to understand to me.

  • Matthew

    I’m getting a “syntax error : ‘<‘” when I try to compile; it’s pointing to this line:

    My code looks the same as yours!!!! This is driving me nuts! What have I done wrong?

  • Mattias

    For the second question, would this also work? (When each element in the array has a unique value of course)
    If it has any downsides please let me know.

  • Sagar

    [code] In solution number 2, shouldn’t it be nNumber > 1 || nNumber < 9 ?

    • Sergio Ramos

      No because that’s how the “Do While” loop works. A “Do While” loop will perform the “Do” statement (the request for a number 1 to 9) so long as it’s condition is true. So you want it to be false.

      Say, if nNumber is less than 1 or greater than 9, the entire condition will be true and the “Do While” statement will repeat, until the entire condition becomes false. !(9) or (>1 && <9).

      Review the "De Morgan’s law" section of "3.6 - Logical Operators" for further information.

  • Jesper

    Hey - the below code is copy pasted directly from Microsoft Visual 2010 and as far as i can see its exactly the same as the solution Alex posted.

    I’m new to learning c++, and I’m really enjoying following this tutorial.

    My question is this:
    When i run the program it correctly keeps asking for a number between 1 and 9 as long as i input a number when prompted. However if I input a letter (Tried it to see what would happen incase of a misstype) it seems to go into an endless loop. Is it supposed to do that (with the code written) or is there another way to avoid this problem I should implement?

    • Slotenmaker

      I had the same problem, it is because of cin.
      cin tries to stream a character inside an integer, which will fail. But the stream will stay in memory! So the next loop it will again try the same character, and again, and again, etc.

      If you put this code in the while loop it fixes this problem, you will also have to #include .
      It clears the stream:

      cin.clear();
      cin.ignore(numeric_limits<streamsize>::max(), '\n');

      Also you can use strings as an alternative.

  • Silvia

    For 6.3 — Arrays and loops - 2nd Quiz: If I run your code, and enter any letter instead of a number, it loops infinitely on printing the request. Why? (Entering any number other than 1..9 it works instead: it properly stops on asking)

    • Alex

      When you enter a non-integer, cin tries to extract this character into the integer variable but fails. The non-integer character is left in the stream. The loop conditions cause it to loop back to cin, and try again. But since the previous characters are still in the stream, cin tries to read them again, and fails again. It does this over and over.

  • it is a very good site to learn cpp programming.

  • Regarding the problem in question #2, when a non-numeric character is entered, I found a solution by doing the while loop using character values then converting the character input to a numeric by substracting 48. See my code below:

    //  Created by Cliff on 3/10/15.
    //  Copyright (c) 2015 Cliff. All rights reserved.
    //

    #include <iostream>

    int main() {
        
        using namespace std;
        char cInput(0);
        
        int anNumbers [9] {4,6,7,3,8,2,1,9,5};
        
        //Get user input
        do
            {   cout << " Please enter a number between 1 and 9 n";
                cin >> cInput;
            }
            while (cInput < ‘1’ || cInput > ‘9’); //Using char type to keep from loop with non-numeric input.
        
        // Print array
                for (int iii = 0; iii < 9; iii++)
                cout << anNumbers [iii] << " ";
        
        // Search array for user entered number to get index value.
        int jjj(0);
        cout <<endl;
        for (jjj=0; anNumbers[jjj] != cInput - 48; jjj++)
            ;
        // Print index
        cout << jjj + 1 << endl;
        
        return 0;
    }

  • MysteryLight

    Hi Alex!
    I’ve been writing code about Rock Paper Scissors with Arrays, and I want to know your idea about this code.
    Here is my code.

    What do you think?

    • MysteryLight

      sorry for bother i have use Arrays but don’t call them. This is my problem. my brother told to me that my code is wrong, so i check again and find this.

      • Alex

        Other issues:
        * rock_peper_scissors has a poor name.
        * as you’ve noted, you never use an array (I don’t know why you need it, just code the logic in main or in a function)
        * your function to do rand_range is very inefficient (I show a better method in lesson 5.9)
        * your input error handling doesn’t handle negative numbers

  • Viv

    I think this is a mistake?

    In the solution number two (modifying the piece of code), in the if statement, you are comparing “score[student]” to “maxScore”, which is no longer a declared variable since it was changed to maxIndex and shows up as an error. In the code to be modified in the original problem, the value being compared is “score[maxIndex]”, which in that case is not a declared variable, and which is what should be in the solution. I think these may have been switched?

  • When does std::cin.fail() evaluates to true in the #2 solution?

  • The correct solution for #2 will be:

    You forgot to write "std::" before cout + In quiz #3, you asked to write this to handle invalid input:

    Note the ‘n’ part in line 4. In the solution, you just wrote std::cin.ignore(32767).
    Thanks Alex…You are doing great.

  • Shane

    I found question 3 somewhat confusing due to its wording when it said print the array, what array?

    If question 2 was not in the middle it would have made much more sense.

  • Ishana

    #1 on the quiz, I don’t understand why using sizeof() function (instead of 9) in the for loop, gives a lot more bunch of numbers after the array is printed?

    • Alex

      Using sizeof on a fixed array returns the total size of the array (array length * element size). What you really want is the array length.

      The easiest way to do this is set the array length as a const int, and then use that. I’ve updated the quiz to use this method.

  • Eric

    I have really tried, but can’t find out what’s wrong in my code. If I enter a character instead of an integer the while loop gets stuck and cin.fail() triggers every time without letting me enter a new character/number. How can this happen when I used cin.ignore() and then clear the error flags with cin.clear()?

    • Eric

      Finally! Placing cin.clear() before cin.ignore() solved the problem. Seems like I had to clear the error flags before emptying the input buffer or else the buffer was not emptied? Does someone know why?

      …and thanks for a great tutorial Alex! I really like the quizzes and hope that you will find the time to add more summarizing quizzes to the end of the remaining chapters 😉

      • Alex

        Once cin is in the error state, it ignores other function calls until the error is cleared. Otherwise the output of those calls would be unreliable, as the stream might not be in a valid state.

  • Quang

    I think the solution for Quiz#1 has a problem, it should be arrayLength not arraySize Alex!
    Btw thank you so much for this great tutorial!

  • Question 2 quiz solution crashes if user gives it a letter instead of an integer! I always have trouble with "cin"! Apparently the special code to protect the buffer does not work.

    • Alex

      Where is it crashing? You should be able to use the debugger to step through and determine what line it’s crashing on. Once we know where it’s crashing, then we can figure out why.

  • This will print the best score and its index for question #3:
    =================================================
    // chap6.3ques3.cpp : Defines the entry point for the console application.
    //

    #include "stdafx.h"

    #include <iostream>

    int main()
    {
        const int numStudents(5);
        int scores[numStudents] = { 84, 92, 76, 81, 56 };
        int maxIndex = 0;
        int maxScore = 0; // keep track of our largest score
        for (int student = 0; student < numStudents; ++student) {
            if (scores[student] > maxScore) {
                maxScore = scores[student];
                maxIndex = student;
            }
        }
        std::cout << "The best score was " << maxScore << ", and its index is " << maxIndex << ‘\n’;

        return 0;
    }

  • Mr D

    Hi Alex,

    What is the purpose of the code (quoted below)?

    The quiz 2 program executes exactly the same, with or without it!

    • Gio

      I’m having trouble wrapping my head around the purpose of this code as well. If I comment it out, the program seems to run the exact same without it, as far as I can tell.

      On a side note, Alex,  this is my first time posting to this site, so I wanted to take the chance to say that these have been the most comprehensive programming tutorials I’ve ever delved into. Most other ones tend to throw users into learning if statements and loops in the very beginning without properly explaining things like #include <iostream> from the get go. Your progression of the lessons feels very spot-on and natural. Thank you!

      • Alex

        As I noted to Mr. D, the example was broken. 😐 It’s fixed now.

        Glad to hear you’re enjoying the lessons. Part of the reason they’re great is because of all the wonderful feedback readers have left me over the years! 🙂

    • Alex

      It was supposed to handle the user entering an invalid input (e.g. ‘p’), but I made a mistake in the code so it didn’t work correctly. I’ve updated the example. It should work now.

  • Mr D

    A question about quiz 3:

    In line 9 of the solution you have:

    but wouldn’t it have been simpler just to write:

    ????
    In your method you choose to compare each successive index to the first index [maxIndex == 0 == score of 84], but isn’t it simpler to just compare it directly to manIndex(0) as you did in an earlier example?

    By the way, in the code of the question part of quiz 3, shouldn’t line 9 read:

    ??
    As it is now, it doesn’t compile!

  • Mr D

    Wait, sorry, silly me, now i understand, you want to hold the index of the largest score, rather then the actual score!!

  • Aaron

    I’m having trouble understanding this section of code.

    What is the function of (std::cin.fail()? How does it know what a valid input is, if it hasn’t been told what is valid?
    Also, why is std::cin >> number; able to change the value of int = number; when it’s outside of block scope?

    • Alex

      When we try and do an extraction operation (using operator >>) such as this:

      … the following will happen:
      1) If there is no unprocessed input in cin, the user will be asked to enter something
      2) cin will attempt to extract data from the input stream into variable number
      3) If this fails, an internal flag will be set to indicate the failure. A failure will occur if the data is not the correct type for the variable being extracted to (such as trying to extract a letter into an integer variable).

      std::cin.fail() allows us to access this error flag, and returns a boolean indicating whether an error has occurred previously.

      > Also, why is std::cin >> number; able to change the value of int = number; when it’s outside of block scope?

      It’s not outside the block scope. number is declared within the block of the function, and only used within the block of the function. It is legal to access values from within a nested block. You get into trouble when you define a variable inside a block and try to access it outside of that block. A nested block doesn’t count as “outside”.

  • Satwant

    Quiz 3 has a type error.  
    if (scores[student] > scores[maxIndex]

    Max index not defined,  I think should be maxScore

  • Aymen

    For the second task would the following still be correct:

    Its less code but I don’t want to compromise on functionality. I then sent it to cout after the for loop.

  • saeid

    in quiz2 i write my own code to show who got that score from tutorials that i learned from you:

    is this good coding or i wrote useless code?

    • derpasaurus

      I would change some things, such as they will result in issues. Firstly, use a switch statement for getName(int):

      Also, the do while part:

      will have issues. What if you type 0, for Saeed or -8? Change it to

    • derpasaurus

      Forget the part about the do while. Im mistaken.

  • ZNI

    how can i solve this problem ? Guys, please help meeee T^T

    Write a program that use a structure named as Book containing members ISBN, year, price and title. The program able to prompt the user to enter items for three different books and calculate the total price and price after discount. Discount is given as below:
    •    If the total price is greater than or equal to 100, the discount is 20%
    •    If the total price is between RM50 and RM99, the discount is 10%
    This program have three functions:
    1.    Functions to receive input about the books
    2.    Functions to calculate the total price and discounted price
    3.    Function to print the summary of books and value that need to pay by the customer
    To solve the problem you need to use looping control structure and array.

    • Elpidius

      Hey ZNI, try this:

      Here are some sub-chapters (aside from this one) that you can refer to if you have any trouble with the code mentioned above:
      http://www.learncpp.com/cpp-tutorial/24a-fixed-width-integers/
      http://www.learncpp.com/cpp-tutorial/4-4b-an-introduction-to-stdstring/
      http://www.learncpp.com/cpp-tutorial/47-structs/
      http://www.learncpp.com/cpp-tutorial/57-for-statements/
      http://www.learncpp.com/cpp-tutorial/61-arrays-part-i/

      I hope this helps you!

      • Rachel Murray

        Hi, after going through all tutorials from start to this page I found your solution to question 2 confusing you haven’t covered cin.fail(), cin.clear() or cin.ignore() from a learning point of view I found this very confusing when you could have shown a solution using all the topics covered in previous tutorials. Will the solutions to other quiz be similar in this regard?

        • Alex

          For the most part, I try not to use concepts that I haven’t explained in depth. In this case, I’m providing you with a fairly small snippet of code that has comments indicating what each line does. You don’t have to understand how it works to use it, just what it does. This might be a little challenging, but I’m okay with that.

          I do think it’s worth writing a lesson about handling invalid input prior to this lesson though. I’ll look into that.

  • Deondre

    Hey Alex,

    Thanks for the tutorials, they’re really helpful!

    If I remember correctly, couldn’t you also use .at() with arrays to ensure that the index is valid? For example if you had a five element array;
    [int array[5] = {1, 2, 3, 4, 5 };]
    and attempted to access the 6th element in the array, if you used [array[5] = 6;], you’d get unexpected results, but if you used [array.at(5) = 6] the compiler would throw an error message without altering any of the data in that memory slot.

  • Pooja

    Hello Alex,

    Once again thanks for such a nice tutorial.
    Have been stuck in a do-while condition check. Can you please let me know what mistake I am doing?

    As far as I enter valid inputs (Eg: 0,1,2,3…) it works fine. When I enter an invalid input (Eg: loop, example…) it runs into a infinite loop even if I enter a valid input in next step.

    Output looks like:

    Please help me to find out what condition check has to be put for while loop here.

    • Alex

      This code, defining a variable length array:

      is illegal in C++ (though some compilers will allow it since it’s legal in C99).

      When I fixed that issue and ran your program, I didn’t get an infinite loop. The other problem I see is that array[i] is undefined if the input from cin fails, but you’re passing it as a parameter to bIsNumberValid. That’s likely to lead to unexpected behaviors.

      Finally, you should get rid of the variable prefix names (b, u32), especially for functions.

  • Nyap

    if you put a number thats out of the range of an array, could you mess with other programs memory? and if so, could I write a virus that makes itself start on boot and c̶o̶m̶p̶l̶e̶t̶e̶l̶y̶ to a certain extent ruin the host computer?

    • Alex

      Not on a modern operating system. If you try and access memory not owned by your process, the OS will terminate your application.

  • Jatin

    I think there is a typo in the solution of problem 1.You wrote "using namespace std;" and then later in the loop you wrote "std::cout". If you wrote std::cout there should not be any need of "using namespace std;".

  • Darren

    I feel I’m getting a bit picky with this one. It’s about code maintainability.

    With the following code:

    in order to add a new test score to the scores array you would have to both increase the numStudents as well as adding the new score. What would happen if you did one but not the other of those things? If you just added an entry to the array initialiser then the compiler will complain about the list having too many values. This is good we like compiler errors as we can generally fix them quickly. However, if we just increased the numStudents value then the code will compile without error or warning; it is syntactically correct. However, the averageScore will be computed incorrectly as we have actually added a score of zero to the array. This is a subtle bug and may not be picked up on straight away.

    What we want to happen is that someone should able to add an entry to the scores array initialiser and have the rest of the program work out the details. This can be done in the following way:

    By allowing the compiler to automatically detect the length of the array (using empty square braces) we can add entries to scores with impunity, and by using the sizeof(array)/sizeof(array[0]) trick the program computes the length of the array to be used elsewhere. The subtle bug has been avoided. But what if some numpty deletes all the initialiser entries? Not a problem as we get a compiler error (good thing) about invalid use of an empty initialiser on an array with an unspecified bound.

    Now the reason I said I was getting picky is that you wouldn’t use primitive arrays to do this in the first place once you learn about the standard template library (STL) container classes e.g. vector, list, and so on. (Also some may find the sizeof(array)/sizeof(array[0]) trick somewhat "hacky").

    • Darren

      Btw Alex, I’m commenting here because I’m refreshing my knowledge about C++ and I am impressed with your tutorials. There’s a lot of fundamental stuff and best practices I had forgotten that I’ve only been reminded about by reading your blog.

      (was that just the right amount of ass kissing or too much?:))

      • Alex

        One foot on each side. 🙂

        Unfortunately, C++ is a nuanced language, which necessitates a lot of best practices and caveating.

    • Alex

      You make a great point. I’ve updated the examples to derive the size rather than declare it explicitly, since it reduces the number of things that need to be modified if the array size is changed.

  • jo

    Hey, first things first: great tutorial, learned quite a lot in a short time! Thanks a lot!

    I did not read all the comments, so I hope this was not mentioned before:

    Imho the first example under "Loops and arrays" has a little mistake:

    The first line should be:  int scores[] = { 84, 92, 76, 81, 56 };
    instead of:                int scores[numStudents] = { 84, 92, 76, 81, 56 };

    since arrray size is given by the initalization list and we calculate numStudents in the second line, which itself includes a little typo:

    There is a ‘s’ missing in the sizeof(score[0]) at the end of that line.

  • Huiying

    #include<iostream>
    using namespace std;

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

        int minscore=100;
        for(int student=0;student<numstudents;++student)

                if (scores[student]<minscore)

                minscore=scores[student];
            cout<<"The best scores are"<<minscore<<endl;

    return 0;
    }

    Hi, this is my code to find the minimum score in an array, but say if i want to find the k lowest score(where k can be any unknown integer), then how would i modify the code above to do it?

  • Lam Gia Khang

    I don’t know what the number 32767 mean in this code:

    Can we use another number?

    • Alex

      It means to ignore up to 32767 characters, which is more than you’re likely to ever encounter before you run into a ‘\n’. You can use a different number if you want, but there isn’t much point.

  • Ye Kyaw Tun

    Dear Admin,

    In quiz number 3, when i am practizing, i found that i  the last line which produces output is wrong.  
    std::cout << "The best score was " << scores[maxIndex] << ‘\n’;

    only variable "maxIndex" is required to get the index of largest score.

    Thank you very much,
    Best Regards,
    Ye Kyaw Tun

    • Alex

      The sample program that you are given to modify prints the max score. So your program that uses maxIndex should also print the max score (not the index of the max score).

  • Kattencrack Kledge

    In Quiz #2, is it still good practice if I searched the index of the inputted number while printing my array at the same time, even if it costs me little extra space in the CPU?:

  • KIRPAL SINGH A/L HARWAN SINGH

    i was trying out this code: why is the value of array index 10 true when the size of array is only 10 and not 11.

    #include<iostream>
    using namespace std;

    bool check(int getNumber, int from_setNumber_index)
    {
        return getNumber==from_setNumber_index;
    }

    int main()
    {
        int setNumbers[10]={0,1,2,3,4,5,6,7,8,9};

        int getNumber;
        cout<<"\nPlease enter a number : ";
        cin>>getNumber;

        int index=0;

        for(index; index<=10; index++)
        {
            bool check_getNumber = check(getNumber, setNumbers[index]);
            cout<<"num "<<index<<": "<<check_getNumber<<"\n";

            if(check_getNumber==1)
            {
                cout<<"correct \n";
            }

        }

        return 0;
    }

    • Alex

      You’re walking off the end of your array and accessing whatever is in memory beyond the last element of the array. Because you’re assigning this to a bool, that garbage value is being interpreted as a bool. Since all non-zero values evaluate to true, and the garbage value is more likely than not to be non-zero, you’ll most often get a value of true (but occasionally you may get a false).

      • KIRPAL SINGH A/L HARWAN SINGH

        refering back to my question…

        bool check_getNumber = check(getNumber, setNumbers[index]);

        the above function will make a copy of data from  check(getNumber. setNumber[index]) and paste the values in the parameter below

        bool check(int getNumber, int from_setNumber_index)

        in this function i returned getNumber==from_setNumber_index  which should be false when it reads array index 10 which is beyond the size of the array. So if the array index 10 has garbage value such as "85693" when compared with getNumber it should return 0…

        sorry for my broken english… can you help me?

  • Eugene

    Hey Alex,

    just wanted to thank you for the work that you have done.
    These lesson a very well explained compared to other sites where it seams that the guys who wrote them lessons wanted to write em the most quickest way. You take your time to explain correctly things as they should be explained, with examples & stuff.

    We appreciate your effort.

  • Aditya Upadhyay

    Hey Alex,
    Is it possible to make 2-D arrays in which every row has different number of column.

    For example a[5][x]
    like 1 row has 4 columns
    2 row has 6 columns.

    And also pls move this leave a comment section to the top of comments.

  • "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."

    Hey Alex,

    if we try to access value [5], which we haven’t declared, don’t we get the default 0 value?

    • Alex

      No. The array only initialized elements 0 through 4. Element 5 is not initialized because it’s not part of the array, and was not provided an initializer.

  • Matt

    Under "Loops and arrays", in the second code example, you wrote:
    "int maxScore = 0; // keep track of index of our largest score".

    The comment is inaccurate. maxScore only keeps track of the biggest score, not the index for the biggest score.

  • Ekanem

    Hi. lol, i’m very new to this. My code works but it seems terribly simple compared to the solution in number 2. Just for future reference abd learning purposes, is there a reason why I shouldn’t write code like this again in future?

    int main()
    {
        const int arrayLength(9);
        int array[arrayLength] = { 4, 6, 7, 3, 8, 2, 1, 9, 5 };
        
    tryAgain:
        cout<<"Please pick a number between 1 and 9: "<<endl;
        int x;
        cin>>x;
        
        if (x < 1)
        {
            goto tryAgain;
        }
        else if (x > 9)
        {
            goto tryAgain;
        }
        else
            cout<<array[x-1]<<endl;
        
        return 0;
    }

    • Alex

      Use of goto should generally be avoided if a normal loop will suffice (such as a do loop, do while, for loop, etc…). The resulting code will generally be more readable and maintainable. It’s not as big a deal with simple code such as this, but better to start learning good habits now.

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter