Skip to content
Free public beta until December 4, 2026: every course is open, no card needed. After that, the first chapter of each course stays free and full access is a one-time $39 ($19 for up to 100 founding members chosen for helpful feedback). Your progress is kept. How the beta works

Just enough C++ II: arrays, structs and text

~35 min

The previous section covered single values. Real programs group values: a row of scores, a point with two coordinates, a name made of letters. This section covers the three ways C++ groups them, and how to print the result. Each one comes back later in the course, when you see how the machine lays it out and walks through it.

Arrays

An array is a row of boxes, all holding the same kind of value, standing side by side. You choose how many boxes when you make the row, and that number never changes. Here is a row of four scores:

std::int32_t scores[4] = {90, 72, 85, 64};

The kind of value each box holds comes first (std::int32_t, a whole number 32 bits wide from the last section). Then comes the name, scores. The 4 in square brackets is how many boxes there are, and the curly braces list what goes in them.

To reach one box, write the name and a position in square brackets. The surprise is that positions start at 0, not 1. scores[0] is the first box (90), scores[1] the second (72), and scores[3] is the fourth and last (64). Think of the number as "how many boxes to walk past from the start". To reach the first box you walk past none. So a row of four boxes has positions 0, 1, 2 and 3, and a loop that visits them all counts from 0 while the count is less than 4.

Two warnings for people coming from Java, C# or Python. First, a C++ array doesn't know its own length; there's no .length or len(). The tool std::size(scores) tells you there are 4. Second, C++ never checks whether a position is real. Ask for scores[4] and C++ won't stop you, even though there is no fifth box. The C++ rules call this undefined behaviour: anything may happen. You might see a nonsense number, the program might crash, or it might look fine and break later. Java would have stopped with an error. C++ trusts you, so you have to be careful.

This section covers three ways to group values. An array is a fixed number of values of one type, stored side by side in order. A struct is a group of named values kept together, and text is a row of characters. Arrays come first, then structs, then text. The declaration gives the element type, the name, and the count in square brackets:

#include <cstdint>

std::int32_t scores[4] = {90, 72, 85, 64};

scores[i] names the element i positions from the start, so the first element is scores[0] and the last is scores[3]. Counting from 0 is not a quirk to memorise. The number in the brackets says how far from the start to go, and the first element is zero steps away. A loop over every element therefore runs i from 0 while i < 4.

A C++ array's size is fixed when it is declared and can't grow. There is no .length on it: std::size(scores) (from <iterator>) gives the count, 4. C++ also never checks an index. scores[4] and scores[-1] are not part of the array, yet the program compiles and runs, and reading them is undefined behaviour: the C++ rules promise nothing about the result. It might print a strange number, crash, or seem to work. Chapter 13 shows what the processor does with such an index, and Chapter 37 shows why attackers look for this bug.

#include <cstdint>
#include <iostream>

int main() {
    std::int32_t scores[4] = {90, 72, 85, 64};
    std::int32_t total = 0;
    for (std::int32_t i = 0; i < 4; ++i) {
        total += scores[i];
    }
    std::cout << scores[0] << '\n';
    std::cout << scores[3] << '\n';
    std::cout << total << '\n';
}
90
64
311

Walk the array

Type exactly what the program prints. The answer came from compiling and running it with a real C++ compiler.

Loading interactive…

Correct! 🎉 Not quite.

Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.

What this task checks

Structure checked automatically. Whether your ideas are convincing isn't graded, so reread with the checklist.

The compiler says

A model answer

Correct answer

Also accepted:

Why

Why

temps[2] is the third element, because positions start at 0: 12 is position 0, 15 is 1, and 9 is 2. The loop keeps the largest value it has seen, so warmest ends at 20.

Worked example

Off by one: the loop that reads one box too many

  1. 1

    A loop meant to add up std::int32_t marks[3] = {5, 8, 6}; is written for (std::int32_t i = 0; i <= 3; ++i) { total += marks[i]; }.

  2. 2

    List the values i takes: 0, 1, 2, and then 3, because 3 <= 3 is true. That's four passes for three boxes.

  3. 3

    On the fourth pass the loop reads marks[3], which is not part of the array. C++ doesn't stop it, so total gets whatever happens to be there added in.

  4. 4

    Change <= to <. Then i takes 0, 1 and 2, just the three real positions, and total is 19. For an array of size n, the safe loop runs while i < n.

Check your understanding (counts toward your progress)

This should add all four rainfall readings and print 26, but it prints 20. Click the 1 broken line.

Correct! 🎉 Not quite.

Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.

What this task checks

Structure checked automatically. Whether your ideas are convincing isn't graded, so reread with the checklist.

The compiler says

A model answer

Why

The loop starts at i = 1, so rain[0], the 6, is never added: 9 + 0 + 11 = 20. Starting at i = 0 gives 26.

Correct answer

Also accepted:

Why

Which reading is missing from 20?

A Java programmer writes scores.length for a C++ array std::int32_t scores[8]. What should they write?

Correct! 🎉 Not quite.

Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.

A plain C++ array has nothing attached to it with a dot.

There's no .size on a plain array either.

len() is Python's way. C++ uses std::size.

Why

A plain C++ array doesn't know its own length. std::size(scores), from , gives 8.

The tool lives in the standard library, under std::.

This loop walks backwards. What does it print?

Correct! 🎉 Not quite.

Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.

What this task checks

Structure checked automatically. Whether your ideas are convincing isn't graded, so reread with the checklist.

The compiler says

A model answer

Why

i runs 3, 2, 1, 0, so the elements are visited 8, 6, 4, 2. Only 2 fails v[i] > 3, so 8, 6 and 4 print, in that order.

Correct answer

Also accepted:

Why

i goes 3, 2, 1, 0. Which of v[3], v[2], v[1], v[0] are greater than 3?

Two elements of an array. What does the program print?

Correct! 🎉 Not quite.

Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.

What this task checks

Structure checked automatically. Whether your ideas are convincing isn't graded, so reread with the checklist.

The compiler says

A model answer

Why

ages[1] is the second element, 8. ages[3] is 12 and ages[0] is 31, so the sum is 43.

Correct answer

Also accepted:

Why

Count positions from 0: 31 is at position 0.

Practice: Arrays (4 problems · doesn’t affect your progress)

Which names the last element of std::int32_t v[10]?

Correct! 🎉 Not quite.

Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.

Positions run 0 to 9, so v[10] is one past the end.

v[1] is the second element.

C++ has no counting from the end; v[-1] is outside the array.

Why

Ten elements have positions 0 to 9, so the last is v[9].

Ten elements, starting from 0.

v[9]

How many readings are over 50?

Correct! 🎉 Not quite.

Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.

What this task checks

Structure checked automatically. Whether your ideas are convincing isn't graded, so reread with the checklist.

The compiler says

A model answer

Why

52, 61 and 70 are over 50. 50 fails the > test, so the count is 3.

Correct answer

Also accepted:

Why

50 itself is not over 50.

3 ⏎

Which loop header visits every element of std::int32_t x[7] exactly once?

Correct! 🎉 Not quite.

Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.

That reaches x[7], one past the end.

That skips x[0] and reads x[7].

That skips x[0].

Why

Start at 0 and run while i < 7: positions 0 to 6, every element once.

Positions 0 to 6.

for (std::int32_t i = 0; i < 7; ++i)

In Java, reading past the end of an array stops the program with an error. Why doesn't C++ do the same?

Correct! 🎉 Not quite.

Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.

A C++ array's size never changes.

There's no wrapping; the position is simply outside the array.

There's no check at all while the program runs.

Why

C++ leaves positions unchecked, so out-of-range reads are undefined behaviour. Chapter 13 shows what the machine code actually does.

Checking takes time. Does C++ spend it?

C++ skips the check while the program runs, to save work

Structs

An array groups values of the same kind under positions. A struct groups values that belong together under names. Think of a form with labelled blanks: one blank for x, one for y. Here is how you describe that form to C++:

#include <cstdint>

struct Point {
    std::int32_t x;
    std::int32_t y;
};

This makes a new kind of value called Point. Every Point has two named parts, x and y, each a whole number 32 bits wide. Each named part is called a field. Notice the semicolon after the final curly brace; leaving it out is a classic error.

To make one, write Point p{3, 4};. That's a variable called p, whose x is 3 and whose y is 4, filled in the order the fields were listed. A dot reaches inside: p.x means "the x part of p". You can read it, or change it with p.x = 10;, and y is left alone.

You can also have a row of structs. Point corners[2] is an array holding two points. corners[1].y reads from left to right: go to position 1 in the row (the second point), then take its y.

If you know C#, a C++ struct is like a C# struct: the values live right inside the variable and get copied along with it. If you know Java, which has no struct, think of a class that only holds data, all of it public. The difference: a Java variable only points at its object, while a C++ struct variable is the values. If you know Python, it's like a @dataclass, except the fields can't change kind and can't be added later.

A struct is a type that groups several named values into one. Each named value is a field (the C++ standard says data member):

#include <cstdint>

struct Point {
    std::int32_t x;
    std::int32_t y;
};

The definition creates a new type, Point; note the semicolon after the closing brace. Point p{3, 4}; makes a variable of that type with p.x equal to 3 and p.y equal to 4, the values given in the order the fields are declared. A dot reaches a field: p.x = 10; changes one field and leaves the other alone. Structs and arrays combine: Point corners[2] is an array of two points, and corners[1].y is the y field of the second one.

In C#, the closest match is C#'s own struct: a value type, copied whole on assignment, whose array stores the points back to back. For a struct of plain numbers like this one, C# also keeps the fields in the order you declared them, so [StructLayout] is only needed to pin exact offsets or packing. Java has no struct; the nearest thing is a class (or record) with only public data, but every Java object is reached through a reference, so a Java Point[] holds references to points rather than the points themselves. A Python programmer can read it as a @dataclass, except that the fields and their types are fixed when the program is compiled. In Chapter 13 you will see how the fields sit inside a struct and how machine code reaches corners[1].y.

#include <cstdint>
#include <iostream>

struct Point {
    std::int32_t x;
    std::int32_t y;
};

int main() {
    Point p{3, 4};
    p.x = p.x + 10;
    Point corners[2] = {{0, 0}, {5, 7}};
    std::cout << p.x << '\n';
    std::cout << p.y << '\n';
    std::cout << corners[1].y << '\n';
}
13
4
7

Worked example

Reading corners[1].y from left to right

  1. 1

    Given Point corners[3] = {{0, 0}, {5, 7}, {2, 9}};, what is corners[2].x + corners[1].y?

  2. 2

    corners[2] is position 2, the third point, {2, 9}. Its .x is 2.

  3. 3

    corners[1] is the second point, {5, 7}. Its .y is 7.

  4. 4

    The sum is 2 + 7 = 9. Read these expressions left to right: first the position in the array, then the field. In Chapter 13 the machine code for this expression does the same two steps in the same order.

Check your understanding (counts toward your progress)

Java has no struct. For a Java programmer, which is the closest match to a C++ struct like Point?

Correct! 🎉 Not quite.

Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.

An array reaches its values by position and needs them all to be the same kind. A struct uses names.

A struct holds values. It doesn't run anything.

An interface describes methods with no data. A struct is data.

Why

A struct is a type that groups named fields, like a Java class with only public data. One difference: a Java variable refers to its object, while a C++ struct variable holds the values itself. (In C#, the closest match is C#'s own struct.)

Which Java thing groups named values?

An array of structs. What does this print?

Correct! 🎉 Not quite.

Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.

What this task checks

Structure checked automatically. Whether your ideas are convincing isn't graded, so reread with the checklist.

The compiler says

A model answer

Why

cart[1] is {10, 1}, so its price is 10. The total is 4×2 + 10×1 + 3×5 = 8 + 10 + 15 = 33.

Correct answer

Also accepted:

Why

cart[1] is the second item.

With struct Size { std::int32_t w; std::int32_t h; };, what is s.h after Size s{4, 9};?

Correct! 🎉 Not quite.

Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.

4 goes to the first field listed, w.

Nothing adds the values. Each goes into its own field.

Nothing multiplies them either.

Why

The values go in declaration order: w gets 4, h gets 9.

Values fill the fields in the order they're declared.

Fill in the blank so the program prints the box's height, 30.

Correct! 🎉 Not quite.

Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.

What this task checks

Structure checked automatically. Whether your ideas are convincing isn't graded, so reread with the checklist.

The compiler says

A model answer

Why

b is the value and height is the field, so b.height reaches 30. Box is the type, not a value.

Correct answer

Also accepted:

Why

Value, dot, field.

Practice: Structs (4 problems · doesn’t affect your progress)

What's wrong with this definition: struct Pair { std::int32_t a; std::int32_t b; } followed by int main() { }?

Correct! 🎉 Not quite.

Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.

Line breaks don't matter to C++.

Fields can share a type freely.

Names are case-sensitive, but any case is allowed.

Why

A struct definition ends with }; and leaving out that semicolon is a classic compile error.

Look at what follows the struct's final brace.

A semicolon is needed after the struct's closing brace

Changing the home score. What does the program print?

Correct! 🎉 Not quite.

Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.

What this task checks

Structure checked automatically. Whether your ideas are convincing isn't graded, so reread with the checklist.

The compiler says

A model answer

Why

home becomes 1 + 2 = 3. away isn't touched, so it stays 1.

Correct answer

Also accepted:

Why

Changing one field leaves the other alone.

3 ⏎ 1 ⏎

Three points sit in Point pts[3] = {{1, 2}, {3, 4}, {5, 6}};. Add the x of the last point to the y of the first. What do you get?

Correct! 🎉 Not quite.

Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.

Why

pts[2] is {5, 6}, so its x is 5. pts[0] is {1, 2}, so its y is 2. 5 + 2 = 7.

Correct answer

Also accepted:

Why

pts[2] is the third point.

7

Which C++ matches the Python @dataclass class Pixel: with fields r: int, g: int, b: int (each 0 to 255)?

Correct! 🎉 Not quite.

Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.

That's an array: values reached by position, not by the names r, g and b.

Every field needs a type in C++.

std::int8_t only reaches 127, and these go up to 255.

Why

A struct with three named fields, each std::uint8_t (0 to 255), matches the dataclass.

Named fields, each with a type that reaches 255.

struct Pixel { std::uint8_t r; std::uint8_t g; std::uint8_t b; };

Characters, text and printing

A char holds one character: a letter, a digit, a space, a symbol. You write a single character between single quotes, as in 'B'. So char grade = 'B'; makes a box called grade holding the letter B. Inside the computer, each character is stored as a small number; Chapter 2 shows which number goes with which character.

Text, like a name or a sentence, goes between double quotes: "cat". Here's the part that surprises everyone. In plain C-style text, the kind this course uses, the text is stored as a row of chars (an array, from earlier in this section). C++ quietly adds one extra char at the end. That extra char is written '\0' (a backslash then a zero). It's a special "the text stops here" marker, called the null terminator. So char name[] = "cat"; gives you four boxes, not three: 'c', 'a', 't', and the end marker. Any code that walks along the text, such as code that counts its letters, keeps going until it meets that marker.

Another backslash combination you've already met is '\n', the "start a new line" character.

There are two ways to print. The first is std::cout. You chain things to it with <<, and it prints each one in turn: std::cout << name << " has " << 9 << '\n'; prints cat has 9 and moves to a new line.

The second is std::printf. You give it a sentence with gaps, then the values to fill the gaps, in order. Each gap is a percent sign plus a letter saying what goes there. Use %d for a whole number, %u for a whole number that can't be negative, %c for one character, and %s for a piece of text. So std::printf("%s: %d\n", name, 9); prints cat: 9. If a gap's letter doesn't match the value you give it, the output is wrong, and the compiler can warn you. This course cares about printf because machine code can use it to print, which you'll do in Chapter 12.

char is the type for a single character. A character value is written in single quotes: char grade = 'B';. Underneath, a char holds a small number, one code per character; Chapter 2 §6 shows the table.

Text in double quotes, such as "cat", is a string literal. In the C-style text this course uses, a piece of text is an array of char followed by one extra character, '\0' (the null terminator, code 0), which marks the end. So char name[] = "cat"; makes an array of four chars: 'c', 'a', 't', '\0'. The empty brackets let the compiler count, and std::size(name) is 4. Code that walks text, such as finding its length, stops when it reaches '\0'. Other escapes start with a backslash too: '\n' is the newline character. (Everyday C++ uses std::string, which manages its own storage; the course uses C-style text because that's what machine code sees.)

Two ways to print appear in this course. std::cout << (from <iostream>) prints each value in turn, using its type to decide how: std::cout << name << " has " << 9 << '\n';. std::printf (from <cstdio>) takes a format string with placeholders and then the values to fill them, in order: %d for an int-sized whole number, %u for an unsigned one, %c for a char, %s for C-style text. A placeholder that doesn't match its value's type is a bug; compilers warn about it with -Wall. printf matters to us because it's an ordinary function that machine code can call, which Chapter 12 does.

Idea Java / C# Python C++
a row of numbers int[] a = {1, 2, 3}; a = [1, 2, 3] std::int32_t a[3] = {1, 2, 3};
its length a.length / a.Length len(a) std::size(a)
a group of named values record Point(int x, int y) / struct Point { public int X, Y; } @dataclass class Point: x: int; y: int struct Point { std::int32_t x; std::int32_t y; };
one character char c = 'B'; c = "B" (no separate kind) char c = 'B';
a piece of text String s = "cat"; / string s = "cat"; s = "cat" char s[] = "cat"; (4 chars with '\0')
print with gaps System.out.printf("%d%n", n); / Console.WriteLine($"{n}"); print(f"{n}") std::printf("%d\n", n);
#include <cstdint>
#include <cstdio>
#include <iostream>
#include <iterator>

int main() {
    char grade = 'B';
    char name[] = "cat";
    std::int32_t lives = 9;
    std::cout << grade << '\n';
    std::cout << name << " has " << lives << " lives\n";
    std::cout << std::size(name) << '\n';
    std::printf("%s: %d lives, grade %c\n", name, lives, grade);
}
B
cat has 9 lives
4
cat: 9 lives, grade B
Three pictures. Top: the array scores[4] as four boxes holding 90, 72, 85, 64, numbered scores[0] to scores[3], and a fifth dashed red box scores[4] marked not part of the array, C++ does not check. Bottom left: Point p{3, 4} as one rounded box containing two boxes, p.x holding 3 and p.y holding 4. Bottom right: the char array pet holding the text cat, as four boxes c, a, t and a dashed red backslash-zero box labelled the hidden end marker, numbered 0 to 3.
An array is numbered slots of one kind; a struct is named fields; text is chars with a hidden end marker.

One character, or a piece of text?

Sort each one: is it a single char, or C-style text that ends with a hidden end marker?

Loading interactive…

Correct! 🎉 Not quite.

Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.

What this task checks

Structure checked automatically. Whether your ideas are convincing isn't graded, so reread with the checklist.

The compiler says

A model answer

Correct answer

Also accepted:

Why

Why

Single quotes hold exactly one char, and a backslash pair (the newline, or the end marker written backslash-zero) counts as one char. Double quotes make text, which always gets the hidden end marker added. So the double-quoted Q is two chars, the letter and the marker, and even empty text is one char: just the marker.

Worked example

Counting the chars in a piece of text

  1. 1

    How many chars are in char city[] = "Oslo";, and what is city[4]?

  2. 2

    The visible letters are O, s, l, o: four of them, at positions 0 to 3.

  3. 3

    C++ adds the end marker '\0' after them, at position 4. So the array holds five chars, and std::size(city) is 5.

  4. 4

    city[4] is that end marker, '\0'. Code that measures the text's length counts letters until it meets it and reports 4. Chapter 13 writes that loop in assembly.

Fill the gaps

Type exactly what the two printf calls print. The answer came from compiling and running the program.

Loading interactive…

Correct! 🎉 Not quite.

Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.

What this task checks

Structure checked automatically. Whether your ideas are convincing isn't graded, so reread with the checklist.

The compiler says

A model answer

Correct answer

Also accepted:

Why

Why

The first format string has three gaps, filled in order: %d gets 3, %s gets the text tea, %c gets the char L. Everything else in the format string, the spaces, x and brackets, prints exactly as written. The second has two %s gaps with nothing between them, so the text prints twice with no space.

Worked example

Reading a printf call

  1. 1

    What does std::printf("%c%d: %s\n", 'R', 2, "done"); print?

  2. 2

    Match each gap to a value, left to right: %c gets 'R', %d gets 2, %s gets the text "done".

  3. 3

    Copy the format string, swapping each gap for its value: R, then 2, then : , then done. The \n ends the line.

  4. 4

    The output is R2: done. Nothing in the format string adds spaces you didn't write, which is why %c%d comes out as R2 with no gap.

A few more pieces of C++ turn up in later chapters' listings. Each one gets this one-line gloss here, so you can read it when you meet it:

C++ What it means Java / C# Python
bool done = false; a true-or-false value boolean / bool done = False
const std::int32_t limit = 10; const: this can't be changed after it's set final / const no direct match
unsigned n = 10u; unsigned is an unsigned int; a u on a number makes it unsigned none / uint, 10u no direct match
long long big = 5; a whole number of at least 64 bits long big = 5
0xFF a number written in hexadecimal (Chapter 2 teaches it) 0xFF 0xFF
static_cast<std::int64_t>(x) convert x to the type in the angle brackets (long) x int(x)
ok ? "yes" : "no" "yes" if ok is true, otherwise "no" same "yes" if ok else "no"
std::printf("%llx", v); %llx prints a long long in hex; %016llx pads it to 16 digits with zeros %x / {v:x} f"{v:016x}"
std::string s = "cat"; text that manages its own room String / string s = "cat"

Check your understanding (counts toward your progress)

Fill in the two placeholders so the program prints Mo scored 41.

Correct! 🎉 Not quite.

Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.

What this task checks

Structure checked automatically. Whether your ideas are convincing isn't graded, so reread with the checklist.

The compiler says

A model answer

Why

The values come in order: name (text, so %s) and then points (a whole number, so %d).

Correct answer

Also accepted:

Why

The first value after the format string is name, a piece of text.

How many chars does char greeting[] = "hello"; hold?

Correct! 🎉 Not quite.

Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.

Why

Five letters plus the end marker that C++ adds after them: 6 chars.

Correct answer

Also accepted:

Why

Count the letters, then add what C++ puts at the end.

No spaces are added for you. What does this print?

Correct! 🎉 Not quite.

Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.

What this task checks

Structure checked automatically. Whether your ideas are convincing isn't graded, so reread with the checklist.

The compiler says

A model answer

Why

std::cout adds nothing between values, so the first line is Load:12kg. The second prints 3 and then 4, which reads as 34.

Correct answer

Also accepted:

Why

std::cout prints exactly what it's given, one value after another.

Which printf placeholder fills a gap with one char?

Correct! 🎉 Not quite.

Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.

%s is for a whole piece of text, not a single char.

%d is for a signed whole number.

%u is for an unsigned whole number.

Why

%c prints one char. %s prints text, %d a whole number, %u an unsigned whole number.

c for char.

Practice: Characters, text and printing (5 problems · doesn’t affect your progress)

What's the difference between 'A' and "A" in C++?

Correct! 🎉 Not quite.

Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.

Double quotes always add the end marker, so they differ.

It's the other way round.

Quotes make literal values, not names.

Why

Single quotes: exactly one char. Double quotes: text, which always ends with the end marker, so "A" is two chars.

Which kind of quotes adds an end marker?

'A' is one char; "A" is the letter plus a hidden end marker

Two printf calls with %c. What do they print?

Correct! 🎉 Not quite.

Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.

What this task checks

Structure checked automatically. Whether your ideas are convincing isn't graded, so reread with the checklist.

The compiler says

A model answer

Why

The first format fills J and S around two dots: J.S. The second fills last, first, last: SJS.

Correct answer

Also accepted:

Why

Each %c is filled in order; everything else prints as written.

J.S. ⏎ SJS ⏎

char empty[] = ""; What does std::size(empty) give?

Correct! 🎉 Not quite.

Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.

Why

There are no letters, but the end marker is still added, so the array holds 1 char.

Correct answer

Also accepted:

Why

No letters, but something is still added.

1

Which printf placeholder fits an unsigned whole number?

Correct! 🎉 Not quite.

Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.

%d is for signed whole numbers; a mismatch is a bug the compiler can warn about.

%s is for text.

%c is for one char.

Why

%u prints an unsigned whole number such as a std::uint32_t.

u for unsigned.

%u

This loop walks the text until it finds the end marker. What does it print?

Correct! 🎉 Not quite.

Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.

What this task checks

Structure checked automatically. Whether your ideas are convincing isn't graded, so reread with the checklist.

The compiler says

A model answer

Why

The letters sit at positions 0 to 4 and the end marker at 5. The loop stops when n reaches 5, which is also the number of letters.

Correct answer

Also accepted:

Why

n stops at the position of the end marker.

5 ⏎

Where this goes next

Chapter 2 §6 shows the numbers behind each char. Chapter 4 finds where each element of an array sits and why scores[i] is cheap to reach. Chapter 12 calls std::printf from assembly. Chapter 13 is the machine level of this whole section: indexing arrays, reaching struct fields, and writing text routines that stop at '\0'.

Feeling good about this section?

Take the section quiz

Every answer gets a full explanation at the end.

Sign in to save highlights

Insert an equation

  • No matches.