Lesson 8

Conditions: агар and вагарна

Conditions: агар and вагарна

In this lesson: the program makes a decision that depends on a condition.

The whole lesson on one page

Conditions: агар and вагарна

In this lesson: the program makes a decision that depends on a condition.

агар

агар means "if":

1тағ ҳарорат = хонданиРақам();
2агар (ҳарорат > 30) {
3 чоп("Имрӯз гарм аст!");
4}
5чоп("Рӯзи хуш!");
Input
35
  • The condition is written in brackets ( ).
  • The commands inside { } 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}
Input
7

Only one of the two parts runs, never both.

вагарна

What does this program print?

1тағ х = 3;
2агар (х > 5) {
3 чоп("калон");
4} вагарна {
5 чоп("хурд");
6}
  • калон
  • хурд
  • калон and хурд
  • nothing

The greater of two numbers

1тағ а = хонданиРақам();
2тағ б = хонданиРақам();
3агар (а > б) {
4 чоп(а);
5} вагарна {
6 чоп(б);
7}
Input
4
9

Formatting

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.

Common mistakes

  • агар (х = 5): = instead of ===.
  • ; after the condition: агар (х > 5); { … }. Then the { } part always runs.
  • Forgetting the }. The playground tells you on which line the bracket was opened.

Task: Even or odd

Read a number and print Ҷуфт or Тоқ.

Input: One whole number.

Output: Ҷуфт or Тоқ

Task: The greatest

Read two numbers and print the greater one.

Input: Two numbers.

Output: The greater one.

Task: The exam

Read an exam score. If the score is 50 or more, print Гузашт, otherwise Нагузашт.

Input: One number: the score.

Output: Гузашт or Нагузашт

Task: Absolute value

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.