Chapter 2 • Language basics
Variables and constants in SomonScript
A variable is like a box that holds data. In this topic we will see how to declare values, change them and print them on the screen.
1. What is a variable?
A variable is a name we give to a value so that we can use it later. For example, an age, a name or the result of a calculation.
- тағ or тағйирёбанда - a value that can be changed later.
- собит - a value that no longer changes after it is declared (for example, ПИ, the number pi).
2. A simple example
In the example below we declare several variables and print them on the screen. Try changing the values yourself.
Personal details
String and number variables, with the result printed on the screen. This example is easy to explain to a class.
example.som
// Declaring variables
тағ ном: сатр = "Аҳмад";
тағ синну_сол: рақам = 15;
// A constant for the city
собит ШАҲР: сатр = "Душанбе";
// Printing the data on the screen
чоп.сабт("Ном: " + ном);
чоп.сабт("Синну сол: " + синну_сол);
чоп.сабт("Шаҳр: " + ШАҲР);terminal
somon run variables.som
Ном: Аҳмад
Синну сол: 15
Шаҳр: Душанбе3. A harder example (with a calculation)
In this example we store three grades, calculate their sum and print the average grade on the screen.
Average grade
Variables for three subjects and calculating the average grade.
example.som
// The student's grades
тағ бахо_математика: рақам = 5;
тағ бахо_физика: рақам = 4;
тағ бахо_забон: рақам = 3;
// Sum of the grades
тағ ҷамъ: рақам = бахо_математика + бахо_физика + бахо_забон;
// The average
тағ миёна: рақам = ҷамъ / 3;
// Final result
чоп.сабт("Миёнаи бахоҳо: " + миёна);terminal
somon run grades.som
Миёнаи бахоҳо: 44. Exercises for the class
You can give these exercises as homework or for group work.
- Declare the variables ном, синну_сол and шӯъба and print them on the screen.
- Declare the constant ПИ with the value 3.14 and calculate the area of a circle with a radius of 5.
- Try to change the value of the constant and see what error the compiler gives.