Conditions: агар and вагарна
In this lesson: the program makes a decision that depends on a condition.
Lesson 8
агар and вагарнаагар and вагарнаIn this lesson: the program makes a decision that depends on a condition.
агар and вагарнаIn this lesson: the program makes a decision that depends on a condition.
агарагар means "if":
1тағ ҳарорат = хонданиРақам();2агар (ҳарорат > 30) {3чоп("Имрӯз гарм аст!");4}5чоп("Рӯзи хуш!");
35
( ).{ } run only if the condition is дуруст.чоп("Рӯзи хуш!") is outside the { }, so it always runs.Change the input to 20 and run the program again.
вагарнавагарна means "else" (otherwise). It says what to do if the condition is false:
1тағ рақам = хонданиРақам();2агар (рақам % 2 === 0) {3чоп(рақам, "ҷуфт аст");4} вагарна {5чоп(рақам, "тоқ аст");6}
7
Only one of the two parts runs, never both.
вагарнаWhat does this program print?
1тағ х = 3;2агар (х > 5) {3чоп("калон");4} вагарна {5чоп("хурд");6}
1тағ а = хонданиРақам();2тағ б = хонданиРақам();3агар (а > б) {4чоп(а);5} вагарна {6чоп(б);7}
4 9
The commands inside { } are written two spaces further to the right. The computer does not care, but people can read the program more easily. In the playground, when you type { and press Enter, the spaces are added for you.
агар (х = 5): = instead of ===.; after the condition: агар (х > 5); { … }. Then the { } part always runs.}. The playground tells you on which line the bracket was opened.Read a number and print Ҷуфт or Тоқ.
Input: One whole number.
Output: Ҷуфт or Тоқ
Read two numbers and print the greater one.
Input: Two numbers.
Output: The greater one.
Read an exam score. If the score is 50 or more, print Гузашт, otherwise Нагузашт.
Input: One number: the score.
Output: Гузашт or Нагузашт
Read a number and print its absolute value without using Риёзӣ.мутлақ: if the number is negative, change its sign.
Input: One number.
Output: The absolute value.