UNIVERSITY OF AGRICULTURE, FAISALABAD
Department of Computer Science
LECTURE 17 · STUDENT NOTES
Lists (Arrays) I: Declaration & Memory Organisation
CS-307 Programming Fundamentals · BSCS Semester 1
Week | Slides | Linked practical | Reference ID |
7 | Lecture17_Arrays_Declaration_Memory.pptx | Practical 12 | N17 |
Learning Outcomes
SLO | By the end of this lecture you can… | Builds CLO | Bloom level |
|---|---|---|---|
SLO 17.1 | Explain why a list (array) is needed to keep many values of the same type under one name | CLO4: Describe the syntax and semantics of the C++ programming language. | C2 |
SLO 17.2 | Declare and initialise a one-dimensional array and use its elements by index (0 to size − 1) | CLO4: Describe the syntax and semantics of the C++ programming language. | C3 |
SLO 17.3 | Describe how an array is stored in memory (side-by-side boxes, addresses, sizeof) and the danger of an index out of bounds | CLO4: Describe the syntax and semantics of the C++ programming language. | C2 |
How to use these notes Read these notes after the lecture and before the practical. Section numbers (for example §3.2) are used in the question bank, so you can always find where an answer comes from. Type every code example yourself — do not copy-paste. |
1. Why Do We Need Lists?
Until now one variable held one value. Many real problems need many values of the same kind that we must use more than once. (Slide L17-S05)
Example: print the marks of 40 students and then list the students who are above the class average. The average is known only after all marks are read, so every mark must still be there for the second step. With one variable each mark is lost when the next is read; with 40 separate variables (m1 … m40) we would need 40 cin and 40 if statements.
A list — called an array in C++ — solves this: it is a group of values of the same type, kept under one name, where each value is found by its position number (index).
Real-world list | Same type | Position number |
|---|---|---|
Seats in a Daewoo bus | seats | seat 1, 2, 3 … |
An egg tray | eggs | place 1 … 12 |
A cricket team sheet | players | batting order 1 … 11 |
2. What an Array Looks Like
int marks[5] = {72, 85, 64, 90, 58}; makes five int boxes under the name marks. Each box is an element; the number under it is its index (also called a subscript). (Slide L17-S06)
Figure 17.1 – The array marks: five elements with indexes 0 to 4 (Slide L17-S06)
Word | Meaning for marks |
|---|---|
Array name | marks |
Size | 5 elements |
Index range | 0 to 4 (size − 1) |
marks[3] | the 4th element, value 90 |
Remember The first index is 0, not 1. The last index is size − 1. |
3. Declaring and Initialising an Array
3.1 Declaring
Syntax: type name[SIZE]; — the element type, the array name and the size in square brackets. (Slide L17-S07)
Declarations int marks[40]; // 40 ints double price[6]; // 6 doubles char grade[40]; // 40 chars
const int SIZE = 30; // good habit int roll[SIZE]; |
- The size must be a whole-number constant (a number or a const int).
- All elements have the same type.
- A local array declared without values holds garbage (unknown leftover values), just like a local variable.
- Using const int SIZE means that if the class grows, you change one line, not every loop.
3.2 Initialising
Values can be given in braces { } when the array is declared. (Slide L17-S08)
declare.cpp #include <iostream> using namespace std;
int main() { const int SIZE = 5; int a[SIZE] = {10, 20, 30, 40, 50}; // full list int b[SIZE] = {7, 9}; // rest become 0 int c[SIZE] = {}; // all 0 double price[] = {120.5, 80, 45.25}; // size taken from the list (3)
for (int i = 0; i < SIZE; i++) cout << a[i] << " "; cout << endl; for (int i = 0; i < SIZE; i++) cout << b[i] << " "; cout << endl; for (int i = 0; i < SIZE; i++) cout << c[i] << " "; cout << endl; for (int i = 0; i < 3; i++) cout << price[i] << " "; cout << endl;
a[2] = 99; // change one element cout << "a[2] is now " << a[2] << endl; return 0; } |
Output 10 20 30 40 50 7 9 0 0 0 0 0 0 0 0 120.5 80 45.25 a[2] is now 99 |
Form | Result |
|---|---|
Full list {10, 20, 30, 40, 50} | every box filled |
Short list {7, 9} | first boxes filled, the rest become 0 |
Empty braces {} | all 0 — quick way to make counters |
Size left out: price[] = {…} | C++ counts the values (3) |
Too many values: int m[3] = {72, 85, 64, 90}; | compile error: too many initializers for 'int [3]' |
4. Using Elements With an Index
An element such as marks[i] works exactly like an ordinary int variable: it can be printed, read with cin, changed and used in expressions. Because the index can be a variable, a for loop from 0 to size − 1 can visit every element. Visiting every element is called traversing the array. (Slide L17-S09)
marks.cpp #include <iostream> using namespace std;
int main() { int marks[5] = {72, 85, 64, 90, 58}; // one name, five boxes
for (int i = 0; i < 5; i++) { cout << "marks[" << i << "] = " << marks[i] << endl; } return 0; } |
Output marks[0] = 72 marks[1] = 85 marks[2] = 64 marks[3] = 90 marks[4] = 58 |
Statement | Effect |
|---|---|
marks[0] = 75; | changes the first element |
cin >> marks[i]; | reads a value into box i |
marks[4] + 2 | uses an element in a sum (60) |
4.1 Reading values and using them again
This program does what one variable could not: it keeps a week of temperatures and then prints them last day first. (Slide L17-S10)
reverse_input.cpp #include <iostream> using namespace std;
int main() { const int DAYS = 7; int temp[DAYS];
cout << "Enter " << DAYS << " temperatures: "; for (int i = 0; i < DAYS; i++) { cin >> temp[i]; // store each value in its own box }
cout << "Last day first: "; for (int i = DAYS - 1; i >= 0; i--) { cout << temp[i] << " "; } cout << endl; return 0; } |
Session Enter 7 temperatures: 31 33 35 29 28 34 36 Last day first: 36 34 28 29 35 33 31 |
The first loop stores the values; the second loop goes backwards from DAYS - 1 (6) down to 0.
5. Memory Organisation
Recall from Lecture 5 that memory is a long row of byte-sized boxes, each with an address. An array is stored as side-by-side (contiguous) elements of the same size with no gaps. (Slide L17-S11)
Figure 17.2 – marks in memory: 5 ints × 4 bytes = 20 bytes in a row (Slide L17-S11)
memory.cpp #include <iostream> using namespace std;
int main() { int marks[5] = {72, 85, 64, 90, 58};
cout << "sizeof(marks[0]) = " << sizeof(marks[0]) << " bytes" << endl; cout << "sizeof(marks) = " << sizeof(marks) << " bytes" << endl; cout << "elements = " << sizeof(marks) / sizeof(marks[0]) << endl;
for (int i = 0; i < 5; i++) { long gap = (char*)&marks[i] - (char*)&marks[0]; // distance from the start cout << "marks[" << i << "] starts " << gap << " bytes after marks[0]" << endl; } return 0; } |
Output (lab PC, g++) sizeof(marks[0]) = 4 bytes sizeof(marks) = 20 bytes elements = 5 marks[0] starts 0 bytes after marks[0] marks[1] starts 4 bytes after marks[0] marks[2] starts 8 bytes after marks[0] marks[3] starts 12 bytes after marks[0] marks[4] starts 16 bytes after marks[0] |
5.1 The address formula
address of a[i] = start address + i × (size of one element). (Slide L17-S12) This is how the computer jumps straight to any element, like finding a plot in a street where every plot has the same width. It also explains why the index starts at 0: element 0 is 0 steps from the start. The real addresses change every time the program runs; the gap does not.
Array | Bytes each | Total bytes | Where does [5] start? |
|---|---|---|---|
int marks[40] | 4 | 160 | start + 20 |
double rain[12] | 8 | 96 | start + 40 |
char grade[30] | 1 | 30 | start + 5 |
- sizeof(array) / sizeof(array[0]) gives the number of elements.
- cout << marks; prints an address (e.g. 0x7ffe…), not the values — print elements in a loop.
- Arrays cannot be copied with =: b = a; gives error: invalid array assignment. Copy element by element: for (int i = 0; i < 3; i++) b[i] = a[i];
6. Common Mistakes
Index out of bounds is the most dangerous mistake because C++ does not check the index. (Slide L17-S14)
bounds_bug.cpp #include <iostream> using namespace std;
int main() { int marks[5] = {72, 85, 64, 90, 58}; int total = 0;
for (int i = 0; i <= 5; i++) { // BUG: <= reads marks[5] total += marks[i]; } cout << "Total: " << total << endl; return 0; } |
The loop runs to i = 5 and reads marks[5], which belongs to something else in memory. The result is undefined behaviour (the language makes no promise): a wrong total, a crash, or it may even seem to work on one PC and fail on another. With g++ -Wall -O2 the compiler warns: warning: iteration 5 invokes undefined behavior. Fix: i < 5.
Mistake | What happens | Fix |
|---|---|---|
Loop runs to SIZE (i <= SIZE) | reads outside the array | i < SIZE |
Index starts at 1 | skips the first element | start at 0 |
Too many values in { } | error: too many initializers | match the size |
b = a; to copy | error: invalid array assignment | copy in a loop |
7. Word Bank (Key Terms)
Word | Simple meaning |
|---|---|
List / array | A group of values of the same type under one name |
Element | One value inside an array |
Index (subscript) | The position number of an element; starts at 0 |
Contiguous | Side by side in memory, with no gaps |
Traverse | Visit every element, usually with a for loop |
Out of bounds | An index below 0 or ≥ size |
Undefined behaviour | C++ makes no promise about what happens |
8. Self-Check Questions
1. What are the first and last indexes of int a[10]?
2. What does int c[6] = {5}; store in c[0] … c[5]?
3. How many bytes does double rain[12] use, and where does rain[5] start?
4. int b[6] = {2, 4, 6}; — what are b[3] and b[5], and what is the sum of all six?
5. Why is for (int i = 0; i <= SIZE; i++) wrong for an array of SIZE elements?
6. Why can't we copy an array with b = a;? What do we do instead?
Answers: 0 and 9; 5 0 0 0 0 0; 96 bytes, 40 bytes after rain[0]; 0, 0 and 12; it reads a[SIZE], one past the end (§6); invalid array assignment — copy in a loop (§5.1). Homework is on Slide L17-S16.