Chapter 7 • Objects and arrays
Objects and arrays in SomonScript
Arrays are used to store lists of values, and objects to store complex data. Here we will see how to create a simple list and an array of objects.
1. A simple array of names
First, we create a simple list of names and print them to the screen one by one. This example shows students that indexes start at 0.
List of students
A simple array and a барои loop to print all the names.
example.som
// List of student names
тағ номҳо: сатр[] = ["Аҳмад", "Фотима", "Ҳасан"];
// Printing the list to the screen
чоп.сабт("=== Рӯйхати донишҷӯён ===");
барои (тағйирёбанда и: рақам = 0; и < номҳо.дарозӣ; и++) {
чоп.сабт(номҳо[и]);
}terminal
somon run objects-basic.som
=== Рӯйхати донишҷӯён ===
Аҳмад
Фотима
Ҳасан2. An array of objects and the average grade
Now let's create a list of objects, each describing one student: their name, age and grade. Then we will calculate the average grade.
Array of student objects
Using an array of objects to store a class's data and calculate the average grade.
example.som
// List of student objects
тағ донишҷӯён: объект[] = [
{ ном: "Аҳмад", синну_сол: 20, бахо: 4.5 },
{ ном: "Фотима", синну_сол: 19, бахо: 4.8 },
{ ном: "Ҳасан", синну_сол: 21, бахо: 4.2 }
];
// Printing the list and calculating the average grade
чоп.сабт("=== Рӯйхати донишҷӯён ===");
тағ ҷамъи_бахоҳо: рақам = 0;
барои (тағ и: рақам = 0; и < донишҷӯён.дарозӣ; и++) {
тағ д: объект = донишҷӯён[и];
чоп.сабт(д.ном + " (" + д.синну_сол + " сол) - Бахо: " + д.бахо);
ҷамъи_бахоҳо = ҷамъи_бахоҳо + д.бахо;
}
тағ миёна: рақам = ҷамъи_бахоҳо / донишҷӯён.дарозӣ;
чоп.сабт("Миёнаи бахо: " + миёна);terminal
somon run objects-students.som
=== Рӯйхати донишҷӯён ===
Аҳмад (20 сол) - Бахо: 4.5
Фотима (19 сол) - Бахо: 4.8
Ҳасан (21 сол) - Бахо: 4.2
Миёнаи бахо: 4.53. Exercises
These exercises reinforce the topic of objects and arrays.
- Create an array of 10 random numbers and find the largest and the smallest of them.
- Create an object for a car with properties and methods (start, stop, accelerate) and use it several times.
- Create a list of students with names and grades and print the students with a grade above 4.5.