Arrays and Vectors Introduced, Explained with Code Examples

UPI Study › Courses › C++ Programming › Free lessons › Lesson 6.1 Free with a free account

Arrays and Vectors Introduced

C++ Programming · Chapter 6: ArraysSection 6.1 · lesson 37 of 84video coming soon

← Real-World Repetition ScenariosNext lesson: One-Dimensional Arrays →

Earn 3 college credits for C++ ProgrammingRecommended for credit by NCCRS · Computer Science 242 · self-paced · one payment, lifetime access

In this lesson

Grouping related values under one name.

  • See why separate variables can't handle a collection
  • Select an element by index, counting from zero
  • Picture contiguous storage and what it implies
  • Choose between an array and a std::vector

Transcript

Everything said in the video, section by section (1,357 words). Read along, or search it.

Opening Problem

When Values Arrive in Quantity

Everything so far has held one value per name. That works until the values arrive in quantity. 200 temperatures. Every sale of the day. One entry per person. At that point, naming them individually stops being tedious, and starts being impossible. What's needed is a way to select a value by number instead of by name. That single change is what makes collections work.

Why Variables Fail

Five Variables Collapse Under Pressure

Suppose five temperature readings must be stored. With what you know so far, the answer is five variables. It works, and it collapses under any realistic pressure. Everything must be written out. Totaling 200 readings means naming 200, in 200 lines that differ by one digit. The count is fixed in the source, so code written for 5 is simply wrong for 6. And the count is often unknown until the program runs. But the fatal one is the last. A name can't be computed. You can't write a loop that visits temp 1 through temp 5, because a variable's name is fixed in the text. So the fix is to stop selecting values by name, and start selecting them by number.

Definition

One Name, Numbered by Index

A collection gives the whole group one name, then distinguishes the members with a number in square brackets after that name. That number is called the index, or the subscript. Temps, index 2, is the element numbered 2, which here holds 19.8. Because the index is an ordinary number, it can be an expression, and in particular, it can be a loop counter. That's the entire payoff. Instead of adding temp 1 through temp 5 by name, a loop adds temps of i, for i from 0 up to 5. Two hundred values become as easy to handle as five.

Key Rule

Counting Starts at Zero

The first element is at index 0, not 1. So a collection of 5 elements uses indexes 0, 1, 2, 3, and 4. The last valid index is always one less than the number of elements. Index 5, one past the end, doesn't exist. This isn't an arbitrary decision to trip you up. An index is best read as a distance from the start, rather than a position in a queue. The first element is zero steps along, and the second is one step along. Read it that way, and the arithmetic stops feeling strange.

Quick Check

Counting Passes in the Totaling Loop

One off-by-one follows directly from counting from zero. Here's the totaling loop again, with one small change. Quick check: i starts at 0, and the loop runs while i is at most 5. How many passes does it make, and which index does the last pass read? Pause, and count.

Common Mistake

Six Passes and One Past the End

Six passes, and the last one reads index 5: one past the end. So a loop over n elements uses i less than n, not less than or equal to n. Nothing stops you. It's undefined behavior: the program reads whatever memory happens to sit there, and carries on as though the value were real. Run it twice, and the answer can differ: one run printed a huge nonsense number, another printed the right total by luck. A checking build catches it. This is among the most common faults in the language. It produces results that look almost right, which is what makes it so hard to spot.

Memory Picture

Contiguous Cells at Equal Spacing

The elements of a collection are stored contiguously: laid end to end in memory, with no gaps, all of the same type, and therefore all the same size. Here, five doubles of 8 bytes each start at address 2000. Element 1 is at 2008, element 2 at 2016, and so on. The program can confirm the sizes: it prints 8 bytes for one element, and 40 for all five. Because the cells are equal-sized with no gaps, the position of any element can be calculated, rather than searched for. That single picture explains most of how collections behave.

Consequences

What the Memory Picture Explains

Here's what the picture explains. Every element must be the same type. A collection holds many of one thing, never a mixture. Reaching any element costs the same, because the position is computed by arithmetic. Element 900 is no slower to reach than element 2. Indexes run from 0 to size minus 1, because the index is a distance from the start. And going past the end isn't detected. Nothing special is stored at the end. Memory continues, and an out-of-range index simply reads whatever is there.

Two Tools

Fixed Array Versus Growing Vector

C plus plus offers two ways to hold a collection like this. They're indexed identically, and they differ over one question: is the size decided when you write the program, or while it runs? A fixed-size array is declared as double temps, 5. A vector is declared as s t d vector of double, and values are added with push back. The array's size is decided when the program is written, and can't grow. The vector's is decided while the program runs, and it grows as values are added. The array doesn't know its own size, so you must keep track of that yourself. The vector reports it with size. Both read an element with square brackets, and neither checks the range.

Decision Guide

Choosing Between Array and Vector

So how do you choose? Do you know the exact count now, and will it never change? If yes, use a fixed-size array: days of the week, months of the year, squares on a board. If not, or if you're not sure, use a vector: readings, entries, anything the user supplies. The second branch is taken far more often, and a vector is the sensible default. It costs very little, it removes an entire class of mistake, and it can answer questions about itself that an array can't.

Vector Operations

Four Operations for Real Work

Four operations are enough to do real work with a vector. Declaring s t d vector of double, v, creates a vector holding doubles. It starts empty, with no elements at all. V dot push back of x adds x to the end, making the vector one element longer. V dot size reports how many elements it currently holds. And v, index i, is the element at index i, for reading, or for storing into.

Worked Example

A Sentinel Loop Fills a Vector

Here's a working program. It starts with an empty vector of temperatures. A sentinel loop reads readings until minus 999, and pushes each one onto the end, so the vector grows by one each time. Then a totaling loop runs from 0 while i is less than temps dot size, adding each element. Read what the program doesn't have to know. It never states how many readings there'll be. The totaling loop asks the vector how far to go. Nothing would change if there were three readings, or three thousand. And with none at all, the loop simply doesn't run.

Key Points

Empty Vectors and the Last Index

Two things to hold on to. Size reports the count, so the last valid index is size minus 1. Writing v, index v dot size, is always one past the end. And a newly declared vector is empty. Writing v, index 0, equals 10, before anything has been added, doesn't create an element. There's nothing there to store into. Values get in through push back. After pushing 10, v index 0 holds 10.

Vocabulary

Key Terms for Collections

A few key terms. An element is one value stored inside a collection. An index, or subscript, is the number in square brackets: a distance from the start. Zero-based counting begins at zero, so the last index is one less than the number of elements. Contiguous storage means elements end to end in memory, with no gaps, all one type and size. And out of range means an index outside 0 to size minus 1.

Key Takeaways

Summary and Eight-Element Question

To summarize. A loop can't vary a variable's name, but it can vary an index, and that's what makes collections work. Indexes start at zero, and the last is size minus one. So loop with i less than n, never less than or equal to n. Elements sit in contiguous cells, all the same type, each costing the same to reach. And default to s t d vector, adding values with push back. Here's something to think about. A collection holds 8 elements. What's the index of the first, and of the last? And what does index 8 refer to?

About C++ Programming at UPI Study

C++ Programming (Computer Science 242) is a self-paced online course of 84 video lessons in 11 chapters, from your first program to decisions, loops, arrays, functions, classes, files, pointers and inheritance. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Why take it here

Why students take C++ Programming with UPI Study

Your first real programming languageC++ teaches how programs really work: variables, control flow, functions, memory and objects. It is the base for data structures, algorithms, systems and game programming, and for most computer-science degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

C++ Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Arrays and Vectors Introduced

Why can't I just use separate variables like temp1, temp2, temp3 to store many values in C++?
Separate variables break down because a variable's name is fixed in the source code, so a loop can't visit temp1 through temp5 by name. You would also have to write out every name, and the count is locked in when you write the code. An array or vector solves this by selecting values by number.
Why do C++ arrays and vectors start counting at index 0?
C++ starts at index 0 because an index is a distance from the start of the collection, and the first element is zero steps along. A collection of 5 elements uses indexes 0 through 4, so the last valid index is always one less than the element count. Index 5 would be one past the end.
What happens if my loop goes one past the end of an array in C++?
Reading one past the end is undefined behavior. C++ does not stop you, and the program reads whatever memory happens to sit there as if it were a real value. The result may be a huge nonsense number or may look right by luck. To avoid this, loop with i < n rather than i <= n.
Should I use an array or a std::vector in C++?
Use a fixed-size array only when you know the exact count now and it will never change, such as the days of the week. Otherwise use a std::vector, which grows with push_back and reports its length with size(). Vector is the sensible default for readings or user input. Both index with square brackets and neither checks the range.

About the C++ Programming course

How many college credits is C++ Programming?
C++ Programming (Computer Science 242) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does C++ Programming cost and what is included?
$250, paid once, with lifetime access: all 84 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does C++ Programming take?
It is self-paced with no deadlines. The 84 lessons total about 0 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in C++ Programming.

84 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

C++ Programming
3 credits · NCCRS
Enroll →