Chapter 7 – Basics of Arrays & Structures (Full Study Notes)
Arrays
Definition & Rationale
- An array is a collection of elements of the same data-type stored contiguously in memory and referenced by a single identifier.
- C++ allows arrays of both primitive (e.g., int, float, char) and user-defined types (e.g., structs).
- Primary goal: group logically related, homogeneous data items so they can be processed with the same algorithmic steps (loops, functions, etc.).
Indexing, Subscripts & Zero-Based Convention
- Elements are numbered ; the numeric label is called an index / subscript.
- → first element, → second, … , → element at position .
- Zero-based indexing ⇒ the subscript equals the number of “steps” from the first element .
- C++ always starts at index ; negative or out-of-range subscripts cause undefined behaviour (often a runtime crash or memory corruption).
General Declaration & Access Syntax
- Declaration template:
data_type array_name[size];- must be an integer constant or constant expression.
- Access / assignment:
array_name[index] = value;value = array_name[index]; - Address formula (not explicitly in the transcript but fundamental):
\text{Address}(a[i]) = \text{Base}(a) + i \times \text{sizeof}(\text{element"]) (for 1-D arrays).
Types of Arrays
One-Dimensional (1-D) Arrays
- Declaration example:
int RegNo[50];→ stores integers. - Initialization during declaration:
- Complete list → compiler counts elements automatically:
int a[] = {9, -5, 6, 2, 8};(size deduced as ). - Partial list → remaining cells auto-filled with :
float w[5] = {1.5, 2.8, 2.5};⇒ .
- Complete list → compiler counts elements automatically:
- No initialization ⇒ cells hold garbage values (indeterminate).
- I/O Pattern (typical loop):
for(i = 0; i < size; ++i) cin >> a[i]; // read
for(i = 0; i < size; ++i) cout << a[i] << "\t"; // write
- Example Program – Read & Print: reads ints into
a[50], then prints them (see transcript Example Program 1). - Memory Representation: contiguous bytes. For
char A[5], each element uses 1 byte back-to-back. - Computation Example – Sum & Average:
sum = Σ a[i]avg = (float) sum / n;- Program in transcript shows explicit cast to float to avoid integer division.
Two-Dimensional (2-D) Arrays
- Viewed as an matrix (rows × columns).
- Declaration syntax:
data_type array_name[rows][cols]; - Initialization:
- Flat list:
int a[2][3] = {1,2,3,4,5,6};⇒
. - Nested braces with missing values auto-zeroed:
cpp int b[2][3] = { {1, 2}, // row 0: 1,2,0 {3} // row 1: 3,0,0 };
- Flat list:
- Access & Nested Loops:
for(i = 0; i < rows; ++i)
for(j = 0; j < cols; ++j)
cin >> a[i][j];
Outer loop → rows; inner loop → columns.
- Example Program 2: reads
m × nints (max ) and prints the table formatted with tabs.
Multi-Dimensional (n-D) Arrays (>2-D)
- Concept: “array of arrays of …”.
- General form:
data_type Array_name[s1][s2][s3]... [sn];where each is the size of the dimension. - Memory is still contiguous; compiler performs row-major flattening.
Common Pitfalls & Practical Notes
- Out-of-Bounds Access: C++ does not perform bounds checking → may read/write arbitrary memory.
- Constant Size: In classic C++ arrays must have a compile-time constant size; for variable sizes use std::vector.
- Zero Initialization Rules: only when (a) explicit initializer list shorter than size or (b) global/static arrays (implicitly zeroed).
- Passing to Functions: an array decays to a pointer to its first element; size information must be passed separately.
Structures
Concept & Motivation
- A structure (struct) is a composite / compound data type aggregating variables (of possibly different types) under a single identifier.
- Useful for grouping logically related, heterogeneous attributes (e.g., a student’s name, ID, GPA).
Declaration Syntax & Vocabulary
- General template:
struct StructName {
type1 member1;
type2 member2;
...
} optional_variables;
- Terms: member / element / field.
structdeclaration ends with a semicolon.- After definition,
StructNamebehaves as a new data type.
Examples
- Address record:
struct AA_Address {
char firstName[80];
char lastName[80];
char street[40];
int houseNumber;
char city[40];
} addressEntry; // addressEntry declared here
- Employee record:
struct employee {
char name[80];
char phone[20];
float hours;
float wage;
};
employee databaseEntry; // variable of type employee
Accessing Members – Dot Operator
- General form:
structure_variable.member_name - Example:
Recording song;
song.title = "Hello";
song.cost = 3.50;
cout << song.title;
Aggregate Operations
- Assignment makes a member-wise copy:
Recording song1, song2;
song2 = song1; // copies title, artist, cost, quantity
- Structures can be function parameters (by value or reference) and return types.
Full Program Illustration – Books
#include <iostream.h>
#include <conio.h>
#include <iomanip.h>
using namespace std;
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main() {
Books Book1; // first variable
strcpy(Book1.title, "Learn C++ Programming");
strcpy(Book1.author, "Mr X");
strcpy(Book1.subject, "C++ Programming");
Book1.book_id = 6495407;
Books Book2; // second variable
strcpy(Book2.title, "Telecom Billing");
strcpy(Book2.author, "Mr Y");
strcpy(Book2.subject, "Telecom");
Book2.book_id = 6495700;
cout << "Book 1 title : " << Book1.title <<
"\nBook 1 author : " << Book1.author <<
"\nBook 1 subject : " << Book1.subject <<
"\nBook 1 id : " << Book1.book_id << endl;
cout << "Book 2 title : " << Book2.title <<
"\nBook 2 author : " << Book2.author <<
"\nBook 2 subject : " << Book2.subject <<
"\nBook 2 id : " << Book2.book_id << endl;
return 0;
}
- Output (simplified):
Book 1 → Learn C++ Programming | Mr X | C++ Programming | 6495407
Book 2 → Telecom Billing | Mr Y | Telecom | 6495700
Practical & Philosophical Notes
- Encapsulation precursor: although
structhas public members by default, grouping data anticipates classes (which add methods & access control). - Ethical / maintenance angle: using structs promotes clearer, self-documenting code and reduces the likelihood of mismatching related variables.
- Real-world relevance: database rows, network packets, file headers, GUI widgets—often modelled with structs.
Quick Reference Cheat-Sheet
- 1-D array declaration:
type var[N]; - 2-D array declaration:
type var[rows][cols]; - Partial initializer → zeros for remainder.
- Uninitialized local array → garbage.
- Structure declaration ends with
;. - Member access:
var.member(dot) | Pointer to struct:ptr->member(arrow, not covered but common). - Struct assignment copies all members.
- Arrays ≠ assignable directly (must loop or
std::copy), but structs are assignable.