Arrays are data structures that store collections of elements of the same data type. They are useful for organizing and accessing data in a structured manner.
Declaring an Array:
array_name[array_size] data_type;
array_name
: The name of the array.array_size
: The number of elements the array can hold.data_type
: The data type of the elements in the array.Example:
numbers[5] integer;
This declares an array named numbers
that can hold 5 integer values.
Accessing Array Elements:
array_name[index];
index
: The position of the element in the array, starting from 0.Example:
numbers[2] = 10;
This assigns the value 10 to the third element of the numbers
array.
Iterating Through an Array:
for (i = 0; i < array_size; i++) {
// Access and process array elements using array_name[i]
}
Example:
for (i = 0; i < 5; i++) {
print(numbers[i]);
}
This code iterates through the numbers
array and prints each element.
Records are data structures that store a collection of data items of different data types. Each data item is associated with a unique identifier called a field.
Declaring a Record:
record record_name {
data_type field_name1;
data_type field_name2;
...
};
record_name
: The name of the record.field_name
: The name of a field in the record.data_type
: The data type of the field.Example:
record student {
string name;
integer roll_number;
float marks;
};
This declares a record named student
with fields name
, roll_number
, and marks
.
Creating a Record Instance:
record_name variable_name;
Example:
student s1;
This creates a record instance of student
named s1
.
Accessing Record Fields:
variable_name.field_name;
Example:
s1.name = "John Doe";
This assigns the value "John Doe" to the name
field of the s1
record instance.
Arrays and records can be combined to create complex data structures. For example, we can create an array of records to store information about multiple students.
Example:
student students[100];
This declares an array named students
that can hold 100 student
records.
Accessing Records in an Array:
students[i].name;
This accesses the name
field of the student
record at index i
in the students
array.
Arrays and records are fundamental data structures that are essential for organizing and managing data in programs. Understanding how to use these structures effectively is crucial for writing efficient and maintainable code.