Filling Arrays With Starting Data | C++ Programming

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

Filling Arrays With Starting Data

C++ Programming · Chapter 6: ArraysSection 6.3 · lesson 39 of 84video coming soon

← One-Dimensional ArraysNext lesson: Feeding Arrays Into Functions →

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

In this lesson

Initialization approaches and defaults.

  • Say exactly what a brace-initialized array holds
  • Predict the contents when the list is short
  • Explain why uninitialized arrays are dangerous
  • Choose how to fill: braces, const, loop, input, or fill

Transcript

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

Opening Problem

The Gap Between Reserved and Filled

Declaring an array reserves the space. It doesn't put anything sensible in it. That gap, between the room existing and the room being furnished, is the source of a whole family of faults. They produce plausible wrong numbers, rather than obvious failures. And the habit that closes the gap costs two characters of typing.

Core Problem

Uninitialized Arrays Hold Leftover Values

A declaration such as int values, 5, asks for enough room for five whole numbers, and gives that room a name. What it doesn't do is clear the room out. Inside a function, the space holds whatever the machine last left there. Reading it is undefined behavior: anything can print, and the program can misbehave. Add an empty pair of braces, and every element is zero, guaranteed. Two characters separate the two.

Why It Matters

Arbitrary Values Are Worse Than Crashes

Arbitrary is worse than broken. A program that crashes tells you where to look. A program reading arbitrary values usually doesn't crash. It adds them into totals, and reports an answer that's merely wrong. And reading them is undefined behavior, so nothing is promised. The values may even look stable, the same on every run, so the fault seems fixed, then returns when anything else changes.

Exception

Global Arrays Start at Zero

There's one exception worth knowing, so it doesn't confuse you later. An array declared outside every function starts with all elements set to zero, guaranteed. That's a property of where it lives, not of arrays. The arrays you write inside functions get no such promise. So it isn't a reason to leave the braces off. A habit that only works in one of the two places isn't a habit.

Brace List Forms

Listed Values, Then Zeros

The general form is a list of values in braces after the declaration. The compiler assigns them to elements in order, starting at position zero. Then it applies one rule that surprises people the first time: any element the list didn't reach is set to zero. So scores, with all five values listed, holds exactly those five. Counts, with just 3 and 1, holds 3, 1, then three zeros. Cleared, with empty braces, holds five zeros. And inferred, with the size left out and four values listed, has four elements, not five. A list of a single 7 gives 7, then four zeros. Not five sevens. That's the misreading worth guarding against.

Error Cases

Too Many Values Fail to Compile

Supply more values than there's room for, and the compiler refuses. It's an error, not a truncation. And with no braces at all, inside a function, the contents are unknown: reading before writing is undefined behavior.

Size Deduction

Lookup Tables With Empty Brackets

Leaving the size out has a real advantage. When the list is the definition of the data, such as the twelve month lengths, empty brackets mean the length can never disagree with the contents. Adding an entry updates the size automatically, and there's no second number to forget to change. A lookup table like this also replaces a long chain of decisions with a single subscript. The days in month m becomes one expression, rather than twelve comparisons.

Const Arrays

Marking Reference Data Fixed

Some arrays hold reference data: values decided once, by the nature of the problem, that no part of the program has any business altering. Marking those const says so, and the compiler enforces it. Any attempt to write into the array is refused before the program is ever built. The refusal is the smaller half of the benefit. The larger half is what a reader learns at a glance: this data is fixed, and can be relied on wherever it appears.

Const Facts

What Const Does and Does Not Do

What does marking an array constant actually do? Writing to an element becomes an error, caught when the program is built, so the mistake can't reach anybody. It documents intent to the next reader, which is arguably the main benefit. It must still be given its values at the declaration, because there's no later opportunity. It sometimes makes the array faster, but speed isn't the reason to write it. And it doesn't protect against bad subscripts. An index out of range is just as dangerous on a constant array.

Runtime Filling

Loops for Calculated and Input Values

A brace list only works for values you know while writing the program. Everything else is filled after the program starts. From a calculation: a loop sets each element of squares to i plus 1, squared. The last, squares 9, is 100. From the person running the program: a loop prompts for each mark, and reads it into marks, index i. Two details matter more than they look. The size is a named constant, used in both the declaration and the loop bound, so the two can never drift apart. And the prompt prints i plus 1 rather than i, because positions start at zero for the machine, and at one for everybody else.

Same Value Fill

Using std::fill for Non-Zero Starts

Sometimes every element should start as the same non-zero value, such as minus 1, meaning nothing recorded here yet. A loop works perfectly well. And s t d fill says the same thing in one line: the beginning of the array, the end of it, and the value to write. For plain zeros, you don't need it at all. The empty brace list already does that at the declaration, and does it sooner.

Decision Guide

Choosing How to Fill an Array

Choosing an approach comes down to a couple of questions. Do you know the values while writing the program? If so, and nothing will change them, use a brace list marked const. If they'll change, use a plain brace list. If you don't know the values, is it the same value in every element? For zeros, empty braces. For anything else, s t d fill. Otherwise, use a loop, one element per pass, either computed, or read from input with a prompt. A counting or accumulating array always starts with empty braces, because every total must start at zero.

Core Habit

Fill First, Then Think

One habit ties it together. Fill first, then think. Write the braces at the moment you write the declaration, before you've decided how the array will be used. It costs nothing when the array is filled properly later. And it removes the entire family of arbitrary-value faults, in the case where you get distracted halfway through, and the filling loop never arrives.

Key Terms

Initialization Vocabulary Review

A few key terms. Partial initialization is a brace list shorter than the array. The elements it doesn't reach are set to zero. Size deduction means leaving the length out, so the compiler counts the list. Arbitrary contents are what an uninitialized array inside a function holds. A constant array is marked const, so its elements can't be written after the declaration. And a lookup table is a fixed array that replaces a chain of decisions with a single subscript.

Summary and Puzzle

Why the Total Is Wrong

To summarize. A declaration reserves space. It doesn't clear it. A short brace list is completed with zeros, and empty braces are the shortest reliable start for a counting array. Mark reference tables const, and let the list set the length. Fill from calculations or input with a loop. Here's something to think about. This program adds up ten counts before anything has been counted. It prints a total that's simply wrong. Run it twice: here, the total changed between runs. Why is it wrong, and why might it repeat, or not? Pause, and think it through. Here's the answer. The array was never filled, so the loop adds up whatever bits were left in that memory. Reading them is undefined behavior. Those leftovers depend on what ran before, so the total may repeat, or change from run to run. Either way, it's wrong. The fix is the two characters from the start: empty braces, so every count begins at zero. Run it, and the total is zero, as it should be.

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 Filling Arrays With Starting Data

What does int counts[5] = {3, 1}; store in the array?
It stores 3, 1, 0, 0, 0. The compiler assigns listed values in order starting at position zero, then sets every element the list did not reach to zero. A list of a single 7 gives 7 followed by four zeros, not five sevens. Empty braces give all zeros.
Why is it dangerous to use an array without initializing it in C++?
An uninitialized local array holds leftover values, and reading them is undefined behavior. The program usually does not crash. It adds the junk into totals and reports an answer that is merely wrong. The values may even repeat between runs, which hides the fault until something else changes.
What happens if I put more values in the braces than the array can hold?
The compiler rejects the code with an error. It does not silently drop the extra values. For example, int a[3] = {1, 2, 3, 4}; will not compile. If you leave the size out, as in int a[] = {1, 2, 3, 4};, the compiler counts the list and makes four elements.
How do I choose between braces, const, a loop, input, or std::fill to fill a C++ array?
Use a brace list when you know the values while writing the program, and add const if nothing should change them. For all zeros, use empty braces. For one non-zero value in every element, use std::fill. Use a loop for computed values or values read from input.

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 →