These are the notes for C++ episode 8. In episode 7, functions let us write a job once. This time the problem is not too much code but too much data: a teacher with 5 marks, then 60. You will invent the array: one name, many values, picked by an index counting from 0. Then the silent out of bounds bug, starting values and zeros, why backup = marks fails and how to copy, what happens when you pass an array to a function, 2D arrays for tables, C-style char arrays and the hidden '\0', and finally std::string with +, size(), [i], find and substr, plus getline and the famous empty name bug fixed by cin.ignore(). Every example below was compiled with g++ -O2 -std=c++17 main.cpp -o main (g++ 13.3, the same command as the SyntaxPilot compiler) and run; the outputs and error messages are copied from those runs.
The problem: Rao ma'am's marks register
Rao ma'am teaches class 8 and has just checked a class test. Five students for now, sixty later. She wants two things:
- The class average. Easy with a loop from episode 6: read each mark, add it to a total.
- Who scored above the average? For that she has to look at every mark again, after the average is known.
First attempt: one variable in a loop
The input is the five marks 78 92 65 88 71:
#include <iostream>
#include <string>
using namespace std;
int main() {
int mark, total = 0;
for (int i = 1; i <= 5; i++) {
cin >> mark;
total = total + mark;
}
cout << "Average: " << total / 5.0 << endl;
cout << "mark now holds: " << mark << endl;
return 0;
}
Input: 78 92 65 88 71. Output:
Average: 78.8
mark now holds: 71
The average is right. But mark holds only 71: every new mark overwrote the one before. So who scored above 78.8? We can't say, because the other four marks are gone. One box holds one value.
Second attempt: one variable per student
The obvious fix is m1 to m5, and a loop where i goes from 1 to 5, printing "m i":
#include <iostream>
#include <string>
using namespace std;
int main() {
int m1 = 78, m2 = 92, m3 = 65, m4 = 88, m5 = 71;
for (int i = 1; i <= 5; i++) {
cout << mi << endl;
}
return 0;
}
main.cpp: In function 'int main()':
main.cpp:8:17: error: 'mi' was not declared in this scope; did you mean 'i'?
8 | cout << mi << endl;
| ^~
| i
Why it fails: the compiler does not glue m and i together to make m1, m2 ... To it, mi is just one more unknown name. Variable names are fixed when you write the code; a loop can't build them. With sixty students you'd need sixty variables and sixty separate lines, and no loop can help. We need one name for all the marks, plus a number to pick each one.
The fix: an array (a train with numbered coaches)
| At the railway station | In C++ | Name |
|---|---|---|
| Rajdhani Express: one name for the whole train | int marks[5] |
an array: one name, 5 slots |
| "Coach number 2": pick one coach by its number | marks[2] |
the index picks a slot |
| Counted from the engine: the first coach is 0 steps away | marks[0] ... marks[4] |
indexes start at 0 |
An array is one name for many values of the same type, stored side by side. Each slot is called an element, and you pick an element with its index in square brackets.
#include <iostream>
#include <string>
using namespace std;
int main() {
int marks[5] = {78, 92, 65, 88, 71};
cout << marks[0] << endl;
cout << marks[4] << endl;
return 0;
}
Output:
78
71
marks[0] is the first mark and marks[4] the last. Five slots means indexes 0 to 4, because the index counts how many steps a slot is from the start.
An array, in one page
int marks[5] = {78, 92, 65, 88, 71};
│ │ │ │
type name [size] {starting values}
index: [0] [1] [2] [3] [4]
value: 78 92 65 88 71
- Every slot has the same type: an
intarray holds onlyints. - The index goes from 0 to size - 1.
- The size is fixed when the array is made. It can't grow later.
The real power: the index can be a variable
Now Rao ma'am's two jobs are easy. One loop adds everything up; a second loop goes over the same marks and prints the ones above the average.
#include <iostream>
#include <string>
using namespace std;
int main() {
int marks[5] = {78, 92, 65, 88, 71};
int total = 0;
for (int i = 0; i < 5; i++) {
total = total + marks[i];
}
double avg = total / 5.0;
cout << "Average: " << avg << endl;
for (int i = 0; i < 5; i++) {
if (marks[i] > avg) {
cout << "Roll " << i + 1 << ": " << marks[i] << endl;
}
}
return 0;
}
Output:
Average: 78.8
Roll 2: 92
Roll 4: 88
The marks were still there for the second loop, because the array kept all of them. We print i + 1 as the roll number because people count from 1 and arrays count from 0. You just invented the array.
Out of bounds: coach number 5 doesn't exist
| At the station | In C++ |
|---|---|
| A 5-coach train has coaches 0 to 4 | int marks[5] has marks[0] to marks[4] |
| Someone walks one step past the last coach | the loop says i <= 5, so it asks for marks[5] |
| There's only a stranger's luggage there | C++ reads whatever memory lies just after the array |
| No guard checks your ticket | C++ does not check the index for you |
The habit from "count 1 to 5" sneaks in as i <= 5:
#include <iostream>
#include <string>
using namespace std;
int main() {
int marks[5] = {78, 92, 65, 88, 71};
int total = 0;
for (int i = 0; i <= 5; i++) {
total = total + marks[i];
}
cout << "Total: " << total << endl;
return 0;
}
g++ prints a warning (not an error, so the program is still built):
main.cpp: In function 'int main()':
main.cpp:9:32: warning: iteration 5 invokes undefined behavior [-Waggressive-loop-optimizations]
9 | total = total + marks[i];
| ~~~~~~~^
main.cpp:8:23: note: within this loop
8 | for (int i = 0; i <= 5; i++) {
| ~~^~~~
Example output (this number changes from run to run; five runs on our machine gave 33158, 33159, 33159, 33158 and 33160):
Total: 33159
Five marks out of 100 can never add up to 33159. marks[5] was some random value from memory, and it went straight into the total. This is undefined behaviour: C++ makes no promise at all. A wrong number today, a crash tomorrow, and maybe a "correct-looking" answer on your friend's laptop. That's why it is the most dangerous array bug: no error, just a wrong answer.
The fix: a constant size and i < N
Keep the size in one place with const int N, and make every loop say i < N. This time the marks also come from the keyboard with cin, straight into marks[i]:
#include <iostream>
#include <string>
using namespace std;
int main() {
const int N = 5;
int marks[N];
for (int i = 0; i < N; i++) {
cin >> marks[i];
}
int total = 0;
for (int i = 0; i < N; i++) {
total = total + marks[i];
}
cout << "Average: " << total / double(N) << endl;
return 0;
}
Input: 78 92 65 88 71. Output:
Average: 78.8
For sixty students, change N to 60 and type sixty marks. Not one other line changes. double(N) turns N into a decimal so the division keeps its decimal part (episode 4). Rule: loop with i < N, never i <= N.
Starting values: missing values become 0
What if you give fewer values than the size?
#include <iostream>
#include <string>
using namespace std;
int main() {
int b[5] = {78, 92};
int c[5] = {};
for (int i = 0; i < 5; i++) {
cout << b[i] << " ";
}
cout << endl;
for (int i = 0; i < 5; i++) {
cout << c[i] << " ";
}
cout << endl;
return 0;
}
Output:
78 92 0 0 0
0 0 0 0 0
| You write | The array starts as |
|---|---|
int b[5] = {78, 92}; |
78 92 0 0 0: the rest are filled with zero |
int c[5] = {}; |
all zeros |
int d[5]; (no =, no braces, inside a function) |
garbage: leftover values from memory |
int e[3] = {1, 2, 3, 4}; |
compile error: too many initializers for 'int [3]' |
That's why, in the const int N program, we filled marks with cin before adding them up. Adding up an array that was never filled gives nonsense. Example output from our runs (it changes every run, and is undefined behaviour): Total: 365149608, then Total: -2039846280, Total: -1716009656.
Copying an array: the photocopier
| In the staff room | In C++ |
|---|---|
| "Copy the whole register in one go!" | backup = marks; gives invalid array assignment |
| The machine copies one page at a time, in order | backup[i] = marks[i]; inside a loop |
Before changing any marks, Rao ma'am wants a backup. You might expect backup = marks; to work:
#include <iostream>
#include <string>
using namespace std;
int main() {
int marks[5] = {78, 92, 65, 88, 71};
int backup[5];
backup = marks;
return 0;
}
main.cpp: In function 'int main()':
main.cpp:8:12: error: invalid array assignment
8 | backup = marks;
| ~~~~~~~^~~~~~~
Why it fails: C++ arrays can't be assigned as a whole with =. Copy them slot by slot with a loop. To prove it's a real copy, change marks[0] afterwards:
#include <iostream>
#include <string>
using namespace std;
int main() {
int marks[5] = {78, 92, 65, 88, 71};
int backup[5];
for (int i = 0; i < 5; i++) {
backup[i] = marks[i];
}
marks[0] = 0;
cout << "marks[0]: " << marks[0] << endl;
cout << "backup[0]: " << backup[0] << endl;
return 0;
}
Output:
marks[0]: 0
backup[0]: 78
Two separate arrays: changing one doesn't touch the other.
Arrays and functions: "the train is on platform 3"
| At the station | In C++ |
|---|---|
| Episode 7: you hand over a photocopy | void addBonus(int marks): a single int is copied |
| "The train is on platform 3": your friend boards the real train | void addGrace(int m[], int n): the array is not copied |
| The platform number doesn't say how many coaches there are | so you also pass the size: addGrace(marks, 5) |
Rao ma'am gives 5 grace marks to everyone. In episode 7, a function that received a single int got a copy and couldn't change main's variable. Arrays behave differently:
#include <iostream>
#include <string>
using namespace std;
void addGrace(int m[], int n) {
for (int i = 0; i < n; i++) {
m[i] = m[i] + 5;
}
}
int main() {
int marks[5] = {78, 92, 65, 88, 71};
addGrace(marks, 5);
for (int i = 0; i < 5; i++) {
cout << marks[i] << " ";
}
cout << endl;
return 0;
}
Output:
83 97 70 93 76
main's array changed. int m[] with empty square brackets means "an int array of any size", and int n carries the size. The function worked on the original slots, not a copy. Why does this happen, and why must we send the size separately? Because what really gets passed is the array's address (where it lives in memory). That is exactly the topic of the next episode: pointers.
2D arrays: cinema seats
| At the cinema | In C++ |
|---|---|
| 3 students x 4 subjects: a marks table | int marks[3][4]: 3 rows, 4 columns |
| Ticket "row B, seat 4": row first, then seat | marks[1][3]: row 1, column 3 (both from 0) |
| The usher walks row by row, every seat | a loop inside a loop: outer = rows, inner = columns |
The report card is not a line of values, it's a table. A 2D array has two sizes: [rows][columns]. Each inner pair of curly braces is one student's row.
#include <iostream>
#include <string>
using namespace std;
int main() {
int marks[3][4] = {
{78, 85, 90, 72},
{92, 88, 79, 95},
{65, 70, 58, 81}
};
for (int s = 0; s < 3; s++) {
int total = 0;
for (int j = 0; j < 4; j++) {
cout << marks[s][j] << " ";
total = total + marks[s][j];
}
cout << "| total " << total << endl;
}
return 0;
}
Output:
78 85 90 72 | total 325
92 88 79 95 | total 354
65 70 58 81 | total 274
The outer loop s picks a student (row), the inner loop j walks that student's subjects (columns). One loop per dimension. Here marks[1][3] is the second student's fourth subject: 95.
Text: char arrays and the hidden '\0'
| A name bracelet | In C++ |
|---|---|
| One bead per letter: M-e-e-n-a | a char array: one character per slot |
| A hidden knot at the end | '\0', the null character, marks where the text stops |
| "Meenakshi" won't fit on a 5-bead bracelet | a char array's size is fixed |
A report card needs names, not roll numbers. The old C way to store text is an array of char. But C++ secretly adds an end marker, '\0', after the letters, so five letters need six slots.
#include <iostream>
#include <string>
using namespace std;
int main() {
char name[5] = "Meena";
cout << name << endl;
return 0;
}
main.cpp: In function 'int main()':
main.cpp:6:20: error: initializer-string for 'char [5]' is too long [-fpermissive]
6 | char name[5] = "Meena";
| ^~~~~~~
With size 6 it works:
#include <iostream>
#include <string>
using namespace std;
int main() {
char name[6] = "Meena";
cout << name << endl;
return 0;
}
Output:
Meena
But picture a student called Meenakshi, or a full name. You'd have to guess the biggest size in advance, and the array can never grow.
The better tool: std::string
C++ has a type made exactly for text: string (from the <string> header; its full name is std::string). A string grows and shrinks by itself.
#include <iostream>
#include <string>
using namespace std;
int main() {
string first = "Meena";
string last = "Sharma";
string full = first + " " + last;
cout << full << endl;
cout << "Length: " << full.size() << endl;
cout << "First letter: " << full[0] << endl;
cout << "Sharma starts at: " << full.find("Sharma") << endl;
cout << full.substr(0, 5) << endl;
return 0;
}
Output:
Meena Sharma
Length: 12
First letter: M
Sharma starts at: 6
Meena
| Operation | What it does | Here |
|---|---|---|
a + b |
joins two strings (concatenation) | "Meena" + " " + "Sharma" → Meena Sharma |
s.size() |
number of characters (the space counts) | 12 |
s[i] |
the character at index i, counting from 0 |
full[0] → M |
s.find("x") |
the index where "x" first starts |
6 |
s.substr(start, count) |
cuts out count characters starting at start |
substr(0, 5) → Meena |
Careful with find: if the text is not there, find returns a special value, string::npos. Printed, it looks like a huge number:
#include <iostream>
#include <string>
using namespace std;
int main() {
string full = "Meena Sharma";
cout << full.find("Verma") << endl;
if (full.find("Verma") == string::npos) {
cout << "Not found" << endl;
}
return 0;
}
Output:
18446744073709551615
Not found
Always compare with string::npos to check "not found".
The trap: adding two quoted texts
#include <iostream>
#include <string>
using namespace std;
int main() {
string greet = "Hello, " + "Meena";
cout << greet << endl;
return 0;
}
main.cpp: In function 'int main()':
main.cpp:6:30: error: invalid operands of types 'const char [8]' and 'const char [6]' to binary 'operator+'
6 | string greet = "Hello, " + "Meena";
| ~~~~~~~~~ ^ ~~~~~~~
| | |
| | const char [6]
| const char [8]
Why it fails: text in double quotes (a string literal) is an old-style char array, not a string. "Hello, " is 7 letters plus the hidden '\0', so const char [8]. Two char arrays can't be added. Make one side a string, and + works:
#include <iostream>
#include <string>
using namespace std;
int main() {
string greet = string("Hello, ") + "Meena";
cout << greet << endl;
return 0;
}
Output:
Hello, Meena
As long as at least one side of + is a string, you can join. (That's why first + " " + last worked above.)
Reading a full name: cin vs getline
| At the reception | In C++ |
|---|---|
| Form box "First name": the clerk copies one word | cin >> name; reads one word, stops at the first space |
| "Write the full line": everything until you press Enter | getline(cin, name); reads the whole line |
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
cin >> name;
cout << "Hello, " << name << "!" << endl;
return 0;
}
Input: Meena Sharma. Output:
Hello, Meena!
Sharma was left behind, because cin >> stops at a space. Use getline:
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
getline(cin, name);
cout << "Hello, " << name << "!" << endl;
return 0;
}
Input: Meena Sharma. Output:
Hello, Meena Sharma!
The bug almost everyone hits: the leftover Enter
Read the roll number with cin >>, then the name with getline. Input: 12, Enter, Meena Sharma.
#include <iostream>
#include <string>
using namespace std;
int main() {
int roll;
string name;
cin >> roll;
getline(cin, name);
cout << roll << ": [" << name << "]" << endl;
return 0;
}
Output:
12: []
The name is empty: the square brackets show nothing. Why: cin >> roll read 12 but left the Enter (the newline character '\n') waiting in the input. getline saw that Enter first, thought "empty line, done", and returned. The fix: cin.ignore() before getline, which throws away that one leftover character.
#include <iostream>
#include <string>
using namespace std;
int main() {
int roll;
string name;
cin >> roll;
cin.ignore();
getline(cin, name);
cout << roll << ": [" << name << "]" << endl;
return 0;
}
Input: 12, Enter, Meena Sharma. Output:
12: [Meena Sharma]
Rule: cin >> followed by getline? Add cin.ignore() in between.
Common mistakes (and the real g++ messages)
| Mistake | Code | What g++ says / what happens | Fix |
|---|---|---|---|
| Looping one past the end | for (int i = 0; i <= 5; i++) with int marks[5] |
no error; warning: iteration 5 invokes undefined behavior; a wrong total (e.g. Total: 33159, changes per run) |
const int N = 5; and i < N |
| Building a variable name in a loop | cout << mi; |
error: 'mi' was not declared in this scope; did you mean 'i'? |
use an array: marks[i] |
| Assigning a whole array | backup = marks; |
error: invalid array assignment |
copy with a loop: backup[i] = marks[i]; |
No room for the hidden '\0' |
char name[5] = "Meena"; |
error: initializer-string for 'char [5]' is too long [-fpermissive] |
char name[6], or better, string name = "Meena"; |
| Adding two quoted texts | string g = "Hello, " + "Meena"; |
error: invalid operands of types 'const char [8]' and 'const char [6]' to binary 'operator+' |
string("Hello, ") + "Meena" |
getline right after cin >> |
cin >> roll; getline(cin, name); |
no error; name is empty: 12: [] |
cin.ignore(); before getline |
| More values than the size | int marks[3] = {78, 92, 65, 88}; |
error: too many initializers for 'int [3]' |
make the size big enough |
| Using an array before filling it | int marks[5]; then adding them up |
no error; garbage total (e.g. Total: 365149608, changes per run) |
fill it first, or start with = {} |
Calling .size() on an array |
marks.size() with int marks[5] |
error: request for member 'size' in 'marks', which is of non-class type 'int [5]' |
keep the size in const int N (.size() is for string) |
Double quotes for one char |
char letter = "M"; |
error: invalid conversion from 'const char*' to 'char' [-fpermissive] |
single quotes: char letter = 'M'; |
| Single quotes for a string | string name = 'Meena'; |
warning: character constant too long for its type then error: conversion from 'int' to non-scalar type 'std::string' {aka 'std::__cxx11::basic_string<char>'} requested |
double quotes: "Meena" |
Printing find when the text is missing |
cout << full.find("Verma"); |
no error; prints 18446744073709551615 |
check == string::npos first |
Mini project: the class report card
Two parallel arrays: slot i of names belongs to slot i of marks. One loop does two jobs: it adds up the total, and remembers top, the index of the highest mark so far.
#include <iostream>
#include <string>
using namespace std;
int main() {
const int N = 5;
string names[N] = {"Aman", "Bela", "Chirag", "Divya", "Esha"};
int marks[N] = {78, 92, 65, 88, 71};
int total = 0, top = 0;
for (int i = 0; i < N; i++) {
total = total + marks[i];
if (marks[i] > marks[top]) top = i;
}
double avg = total / double(N);
cout << "Class average: " << avg << endl;
cout << "Topper: " << names[top] << " (" << marks[top] << ")" << endl;
cout << "Above average:";
for (int i = 0; i < N; i++) {
if (marks[i] > avg) cout << " " << names[i];
}
cout << endl;
return 0;
}
Output:
Class average: 78.8
Topper: Bela (92)
Above average: Bela Divya
topstarts at 0 (Aman). Whenever a later mark beatsmarks[top],topmoves there: Bela at index 1 with 92 stays on top.- An array can hold
strings too:string names[N]. - For sixty students, change
Nand add the names and marks. Try it: add a sixth student.
Practice
- Read 6 temperatures and print the highest and the lowest.
- Reverse an array of 5 numbers in place (inside the same array, without a second array).
- Count the vowels in a full line read with
getline. - Print a 3 x 3 marks table with each column's total.
Solution
1. Start high and low at the first temperature, then compare the rest. Input: 31 34 29 36 33 27. Output:
Highest: 36
Lowest: 27
#include <iostream>
using namespace std;
int main() {
const int N = 6;
int temp[N];
for (int i = 0; i < N; i++) {
cin >> temp[i];
}
int high = temp[0], low = temp[0];
for (int i = 1; i < N; i++) {
if (temp[i] > high) high = temp[i];
if (temp[i] < low) low = temp[i];
}
cout << "Highest: " << high << endl;
cout << "Lowest: " << low << endl;
return 0;
}
2. Swap the first with the last, the second with the second-last, and stop at the middle (N / 2 swaps; going further would swap them back). Output: 50 40 30 20 10.
#include <iostream>
using namespace std;
int main() {
const int N = 5;
int a[N] = {10, 20, 30, 40, 50};
for (int i = 0; i < N / 2; i++) {
int temp = a[i];
a[i] = a[N - 1 - i];
a[N - 1 - i] = temp;
}
for (int i = 0; i < N; i++) {
cout << a[i] << " ";
}
cout << endl;
return 0;
}
3. A string is indexed like an array, so loop over line[i] up to line.size(). Input: Rao ma'am loves chai at the station. Output: Vowels: 13.
#include <iostream>
#include <string>
using namespace std;
int main() {
string line;
getline(cin, line);
int vowels = 0;
for (int i = 0; i < line.size(); i++) {
char c = line[i];
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ||
c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') {
vowels++;
}
}
cout << "Vowels: " << vowels << endl;
return 0;
}
4. For a column total, the outer loop picks the column j and the inner loop walks down the rows s. Output:
78 85 90
92 88 79
65 70 58
Totals:
235 243 227
#include <iostream>
using namespace std;
int main() {
int marks[3][3] = {
{78, 85, 90},
{92, 88, 79},
{65, 70, 58}
};
for (int s = 0; s < 3; s++) {
for (int j = 0; j < 3; j++) {
cout << marks[s][j] << " ";
}
cout << endl;
}
cout << "Totals:" << endl;
for (int j = 0; j < 3; j++) {
int total = 0;
for (int s = 0; s < 3; s++) {
total = total + marks[s][j];
}
cout << total << " ";
}
cout << endl;
return 0;
}
Quick quiz
What does this print?
string s = "chai";
cout << s.size() << s[1] << endl;
- A.
4h - B.
4c - C.
5h - D. Compile error
Answer
A: 4h (verified). s.size() is 4: c, h, a, i (a string's size does not count any hidden '\0'). Indexes start at 0, so s[1] is the second letter, h. Nothing is printed between them, so you see 4h.
Interview questions
- What is an array? A fixed-size collection of elements of the same type, stored one after another in memory, accessed by an index starting at 0.
- Why do array indexes start at 0? The index is the distance (offset) from the start of the array: the first element is 0 steps away. For an array of size N, valid indexes are 0 to N - 1.
- What happens if you access an array out of bounds in C++? Undefined behaviour. C++ does no bounds check: you may read garbage, corrupt other data, or crash. There is usually no error message.
- What values does
int a[5] = {1, 2};hold? Andint a[5];inside a function?1 2 0 0 0: missing values become zero. Without any initializer, a local array holds indeterminate (garbage) values. - Can you assign one array to another with
=? No, it givesinvalid array assignment. Copy element by element (or usestd::copy, orstd::array/std::vector, which support=). - Why can a function change an array passed to it, and why pass the size? The array is not copied; the function receives the address of its first element. That address carries no length information, so the size must be passed separately.
- How is a 2D array stored and accessed? As rows one after another in memory (row-major order).
a[r][c]picks rowr, columnc; nested loops visit every cell. - What is the difference between a C-style string and
std::string? A C-style string is achararray ending in'\0', with a fixed size.std::stringmanages its own memory, grows as needed, knows its length (size()), and supports+,find,substrand more. - Why does
"Hello" + "World"not compile? Both are string literals (const chararrays), notstd::string, and+is not defined for two of them. Make at least one side astd::string. - Why does
getlinereturn an empty string aftercin >>, and how do you fix it?cin >>leaves the newline in the input buffer;getlinereads up to that newline and stops immediately. Callcin.ignore()(orcin >> ws) beforegetline.
Glossary
| Term | Plain meaning | Example |
|---|---|---|
| Array | One name for many values of the same type, stored side by side | int marks[5] |
| Element | One slot (value) inside an array | marks[2] is 65 |
| Index | The number in square brackets that picks a slot, counted from 0 | the 2 in marks[2] |
| Size (of an array) | How many slots an array has; fixed when it is created | 5 in int marks[5] |
| Initializer list | Starting values in curly braces | {78, 92, 65, 88, 71} |
| Initialise | Give a variable or array its first value when you create it | int c[5] = {}; |
| Partial initialisation | Giving fewer values than the size; the rest become 0 | int b[5] = {78, 92}; → 78 92 0 0 0 |
| Garbage value | A leftover, unpredictable value in memory you never set | int d[5]; then reading d[0] |
| Out of bounds | Using an index outside 0 to size - 1 | marks[5] in a size-5 array |
| Undefined behaviour | Code C++ makes no promise about: wrong answer, crash, or seeming to work | reading marks[5] |
| Warning | A message from g++ about likely trouble; the program is still built | iteration 5 invokes undefined behavior |
| Compile error | A mistake g++ finds before running; no program is produced | invalid array assignment |
const |
Makes a variable a constant that can't be changed | const int N = 5; |
| Constant | A named value fixed for the whole program | N |
double(N) |
Converts N to a decimal number so division keeps decimals |
total / double(N) → 78.8 |
| Copy slot by slot | Copying an array with a loop, one element at a time | backup[i] = marks[i]; |
| Array parameter | A function parameter that receives an array (the original, not a copy) | int m[] in addGrace(int m[], int n) |
| Address | Where something lives in memory; arrays are passed by their address (next episode) | what addGrace really receives |
| Pass by value | Passing a copy of a value; the original is unchanged (episode 7) | addBonus(int marks) |
| 2D array | An array of rows and columns, like a table | int marks[3][4] |
| Row / column | The first index picks the row, the second the column | marks[1][3] → row 1, column 3 |
| Nested loop | A loop inside another loop, used to visit every cell of a table | for (s...) { for (j...) } |
char |
A type that holds one character, written in single quotes | 'M' |
| C-style string (char array) | Text stored as a char array ending in '\0' |
char name[6] = "Meena"; |
'\0' (null character) |
The invisible end marker after the letters in a C-style string | the 6th slot of "Meena" |
| String literal | Text written in double quotes in the code; it is a const char array |
"Meena" is const char [6] |
string (std::string) |
C++'s text type that grows and shrinks by itself | string full = "Meena Sharma"; |
#include <string> |
The header that brings in string |
top of the file |
| Concatenation | Joining texts end to end with + |
first + " " + last |
size() |
Number of characters in a string | full.size() → 12 |
| Member function | A function that belongs to a type, called with a dot | full.size(), full.find(...) |
find |
Returns the index where some text first starts in a string | full.find("Sharma") → 6 |
string::npos |
The special value find returns when the text is not found |
18446744073709551615 when printed |
substr(start, count) |
Cuts out count characters starting at index start |
full.substr(0, 5) → Meena |
| Operand | A value on either side of an operator | "Hello, " and "Meena" in + |
cin >> |
Reads one word (or number) from input; stops at a space or Enter | cin >> name; → Meena |
getline(cin, s) |
Reads a whole line, spaces included, until Enter | getline(cin, name); → Meena Sharma |
| Input buffer | The waiting area where typed characters sit until the program reads them | the leftover Enter after cin >> roll |
Newline ('\n') |
The character produced by pressing Enter | left behind by cin >> roll |
cin.ignore() |
Throws away one waiting character from the input (the leftover Enter) | cin.ignore(); before getline |
| stdin (input box) | The text fed to a program's cin; in the SyntaxPilot compiler, the input box |
78 92 65 88 71 |
| Parallel arrays | Two arrays where the same index belongs to the same person | names[i] and marks[i] |
| In place | Changing an array inside itself, without making a second array | reversing a by swapping |
| Swap | Exchanging two values using a temporary variable | temp = a[i]; a[i] = a[j]; a[j] = temp; |
Summary
- One variable keeps only the last value, and a loop can't build names like
m1...m60. An array gives one name plus an index. int marks[5] = {...};: same type in every slot, indexes 0 to size - 1, size fixed.- Going past the end (
i <= 5) is out of bounds: no error, a wrong answer, undefined behaviour. Useconst int Nandi < N. - Missing starting values become 0;
{}means all zeros; no initializer means garbage. - Arrays can't be copied with
=(invalid array assignment): copy slot by slot. - An array passed to a function is the original, not a copy, so pass the size too (the real reason is the address: pointers, next episode).
- 2D arrays are tables:
[row][column], visited with nested loops. - A
chararray needs one extra slot for the hidden'\0'and can't grow. Usestring:+,size(),[i],find,substr. At least one side of+must be astring. cin >>stops at a space;getlinereads the whole line. Aftercin >>, callcin.ignore()beforegetline.
Next episode: pointers. Today a function changed main's array, and it needed the size passed separately. Why? Because it received an address. Next time you'll invent pointers, and see the real reason arrays behave this way.