Skip to main content
Skip to content

Lesson 4 of 12

Operators: maths, comparison and logic

Do arithmetic, compare values and combine conditions — the building blocks of every decision your program makes.

8 min

Arithmetic

+ - * / work as you expect, and / gives decimals when needed: 7 / 2 is 3.5. % gives the remainder after division, which is the classic way to test whether a number is even (n % 2 == 0). Multiplication and division happen before addition and subtraction; use brackets to change the order.

Dividing by zero is not allowed — AltFLang stops with a clear runtime error instead of printing Infinity.

Expected output

Press Run to try it

10 4 213.511420

The ganit toolbox

ganit ("mathematics") groups common maths helpers: ganit.floor rounds down, ganit.ceil rounds up, ganit.round rounds to the nearest whole number, plus ganit.pow, ganit.sqrt, ganit.abs, ganit.min, ganit.max, ganit.random and the constants ganit.PI and ganit.E.

Expected output

Press Run to try it

4 5 51024 99 3

Comparisons give sahi or galat

== asks "are these equal?" and != asks "are these different?". AltFLang's == is strict: a number is never equal to text, so 5 == "5" is galat. Convert with sankhya() first when you compare user input with a number. <, >, <= and >= compare sizes.

Expected output

Press Run to try it

sahi galatgalatsahi galat

Combining conditions

&& (and) is true only when both sides are true. || (or) is true when at least one side is. ! flips a value. Like JavaScript, && and || stop early: if the left side already decides the answer, the right side is never run.

Shortcuts such as x += 5 (meaning x = x + 5) also work for -=, *= and /=.

Expected output

Press Run to try it

sahigalatgalat15

Practice exercise

For n = 17, print three lines: the remainder of n divided by 5, whether n is greater than 10 AND odd, and n squared using ganit.pow. Expected: 2, sahi, 289.

Expected output

2
sahi
289
Open in playground
Show solution
solution.altf
rakho n = 17;
bol(n % 5);
bol(n > 10 && n % 2 != 0);
bol(ganit.pow(n, 2));