Chapter 4 • Operators and expressions
Operators and expressions in SomonScript
Operators let us do calculations, compare values and build conditions. Here we get to know them through a few simple examples.
1. Arithmetic operators
The operators +, -, *, / and % are used for addition, subtraction, multiplication, division and finding the remainder.
Calculations with operators
A simple example of using arithmetic operators.
example.som
тағ а: рақам = 10;
тағ б: рақам = 3;
тағ ҷамъ: рақам = а + б;
тағ тарҳ: рақам = а - б;
тағ зарб: рақам = а * б;
тағ тақсим: рақам = а / б;
тағ бақия: рақам = а % б;
чоп.сабт("Ҷамъ: " + ҷамъ);
чоп.сабт("Тарҳ: " + тарҳ);
чоп.сабт("Зарб: " + зарб);
чоп.сабт("Тақсим: " + тақсим);
чоп.сабт("Бақия: " + бақия);terminal
somon run operators-basic.som
Ҷамъ: 13
Тарҳ: 7
Зарб: 30
Тақсим: 3.3333333333333335
Бақия: 12. Comparison and logical operators
To build conditions we use the comparison operators >, <, >=, <=, === and !== and the logical operators && (and), || (or) and ! (not).
A condition with comparison operators
A short example with the >= operator and the logical operator &&.
example.som
тағ синну_сол: рақам = 18;
тағ дорои_шиноснома: мантиқӣ = дуруст;
агар (синну_сол >= 18 && дорои_шиноснома) {
чоп.сабт("Шумо метавонед овоз диҳед");
} вагарна {
чоп.сабт("Шумо ҳоло наметавонед овоз диҳед");
}terminal
somon run operators-compare.som
Шумо метавонед овоз диҳед3. Exercises
These exercises will help students understand the basic operators better.
- Write a program that takes two numbers and calculates their sum, difference, product and quotient.
- Create a program that takes an age and uses comparison operators to decide whether the person is a school pupil or a university student.
- Write an expression that prints "access" only when the user is "admin" and the password is correct.