Published by Patrick Mutisya · 14 days ago
Define and use composite data types.
A composite (or user‑defined) data type is built from two or more primitive types, allowing a programmer to model real‑world entities more naturally.
In many languages a record is declared with the record or struct keyword.
struct Point {int x;
int y;
};
Usage example:
struct Point p1 = {3, 4};printf("(%d, %d)\n", p1.x, p1.y);
An array groups a fixed number of elements of the same type.
| Language | Declaration Syntax |
|---|---|
| C / C++ | int scores[10]; |
| Java | int[] scores = new int[10]; |
| Python | scores = [0] * 10 |
Tuples are immutable ordered collections.
person = ("Alice", 23, True) # name, age, isStudentA class encapsulates data and related operations.
class Circle {private double radius;
public Circle(double r) { radius = r; }
public double area() { return Math.PI * radius * radius; }
}
Many languages allow you to create a new name for an existing type, improving readability.
| Language | Alias Syntax |
|---|---|
| C | typedef struct Point Point2D; |
| C++ | using Point2D = struct Point; |
| Java | Not applicable – use class names directly. |
| Python | from typing import NamedTuple |
.) or arrow operator (->) for pointers.The following pseudo‑code demonstrates defining a record, creating an array of records, and processing them.
// Define a composite typerecord Student {
string id;
string name;
int age;
float GPA;
}
// Declare an array of 5 students
Student class[5];
// Initialise the first student
class[0] = {"S001", "Emma", 19, 3.7};
// Function to compute average GPA
float averageGPA(Student s[], int n) {
float total = 0;
for (int i = 0; i < n; i++) {
total = total + s[i].GPA;
}
return total / n;
}
Student record with fields id, name, age, GPA and a method averageGPA() operating on an array of Student objects.