SomonScriptDocsControl structures
Chapter 5 • Control structures

Control structures in SomonScript

Control structures let us make decisions (if, switch) and repeat actions (for, while). This is one of the most important topics for understanding how a program behaves.

1. Why do we need control structures?

Without conditions and loops, a program simply runs from top to bottom. With them we can:

  • run a part of the code only when a condition is met;
  • choose one option out of several;
  • repeat one action many times.

2. A simple example: "Pass / fail"

In this example a student gets a score. If the score is 60 or more, the program prints "Шумо гузаштед" ("You passed"), otherwise "Шумо нагузаштед" ("You failed").

A simple condition with АГАР-ВАГАРНА

An example of a condition that decides whether a student passed the exam or not.

example.som
// One student's score
тағ холҳо: рақам = 72;

// A simple condition with АГАР-ВАГАРНА
агар (холҳо >= 60) {
  чоп.сабт("Шумо гузаштед");
} вагарна {
  чоп.сабт("Шумо нагузаштед");
}
terminal
somon run exam.som
Шумо гузаштед

3. A harder example: a loop with counting

Now we have the scores of several students, and we want to count how many of them passed. For this we use the барои loop and a condition.

Counting the students who passed

A барои loop (for loop) with a condition, to count how many students scored enough points.

example.som
// The class's list of scores
тағ холҳо: рақам[] = [45, 80, 92, 58, 73];

// Number of students who passed
тағ шумораи_гузаштанд: рақам = 0;

// A loop that goes through the list of scores
барои (тағ и: рақам = 0; и < холҳо.дарозӣ; и++) {
  // If the score is greater than or equal to 60, this student passed
  агар (холҳо[и] >= 60) {
    шумораи_гузаштанд = шумораи_гузаштанд + 1;
  }
}

// Print the result on the screen
чоп.сабт("Донишҷӯёни гузашташуда: " + шумораи_гузаштанд);
terminal
somon run control-flow.som
Донишҷӯёни гузашташуда: 3

4. Exercises

You can do these exercises in class or give them as homework.

  1. Write a program that takes the number of a day (1-7) and, using интихоб, prints the name of the day.
  2. Create a program that prints the numbers from 1 to 20 but shows only the odd ones (using барои and давом).
  3. Create an array of numbers and use a loop to count how many of them are greater than 0.