Chapter 3 • Data types
Data types in SomonScript
A type shows what kind of value a variable can hold: a string, a number, a boolean value and so on. Understanding types is very important for avoiding errors and writing clear code.
1. Primitive types (сатр, рақам, мантиқӣ)
The most common types in SomonScript are сатр (text), рақам (number) and мантиқӣ (true/false).
Basic variable types
A simple example with the types сатр, рақам and мантиқӣ for a short student profile.
example.som
// Primitive types: сатр, рақам, мантиқӣ
тағ ном: сатр = "Аҳмад";
тағ синну_сол: рақам = 16;
тағ донишҷӯ_аст: мантиқӣ = дуруст;
// Printing the values on the screen
чоп.сабт("Ном: " + ном);
чоп.сабт("Синну сол: " + синну_сол);
чоп.сабт("Донишҷӯ аст:", донишҷӯ_аст);terminal
somon run types-basic.som
Ном: Аҳмад
Синну сол: 16
Донишҷӯ аст: дуруст2. A harder example: an array and an object
Composite types, such as an array (for example, рақам[]) and объект (object), let us store several values together. In the example below we describe a student's data with these types.
An array and an object for a student
For example, storing a student's data with different types: сатр, рақам, мантиқӣ and an array.
example.som
// Student data of different types
собит НОМИ_ДОНИШГОҲ: сатр = "Донишгоҳи миллии Тоҷикистон";
// An object with the student's data
тағ донишҷӯ: объект = {
ном: "Аҳмад",
синну_сол: 20,
фаъол_аст: дуруст,
бахоҳо: [5, 4, 5, 5, 4] // an array of numbers
};
// Printing the data on the screen
чоп.сабт("=== " + НОМИ_ДОНИШГОҲ + " ===");
чоп.сабт("Донишҷӯ: " + донишҷӯ.ном);
чоп.сабт("Синну сол: " + донишҷӯ.синну_сол);
// Calculating the average grade
тағ ҷамъи_бахоҳо: рақам = 0;
барои (тағ и: рақам = 0; и < донишҷӯ.бахоҳо.дарозӣ; и++) {
ҷамъи_бахоҳо = ҷамъи_бахоҳо + донишҷӯ.бахоҳо[и];
}
тағ миёнаи_бахо: рақам = ҷамъи_бахоҳо / донишҷӯ.бахоҳо.дарозӣ;
чоп.сабт("Миёнаи бахоҳо: " + миёнаи_бахо);terminal
somon run types-student.som
=== Донишгоҳи миллии Тоҷикистон ===
Донишҷӯ: Аҳмад
Синну сол: 20
Миёнаи бахоҳо: 4.63. Exercises
These exercises help you reinforce the topic of types.
- Create an array of your 5 favorite numbers and print them on the screen one by one.
- Create an object for a book with the properties ном, муаллиф, соли_нашр and саҳифаҳо and print it on the screen.
- Create two arrays of numbers, calculate the sum of all their elements and print the result on the screen.