Chapter 6 • Functions
Functions in SomonScript
A function is a named block of code that performs a specific task. With functions you can write code once and use it many times.
1. A simple example: a greeting function
In the example below we create a function that builds a greeting and prints it on the screen. The teacher can first show only the салом() part and then call the function several times.
Greeting function
The function takes a name and an age as parameters and builds a personal message.
example.som
// Declaring a function that builds a greeting
функсия салом(ном: сатр, синну_сол: рақам) {
// Printing a message with the name and age
чоп.сабт("Салом, " + ном + "! Ту " + синну_сол + " сола ҳастӣ.");
}
// Calling the function with two arguments
салом("Аҳмад", 15);
салом("Фотима", 14);terminal
somon run functions.som
Салом, Аҳмад! Ту 15 сола ҳастӣ.
Салом, Фотима! Ту 14 сола ҳастӣ.2. A harder example: a function that returns a value
So far our functions have only printed text. Now let's see how a function can return a result so that we can use it somewhere else.
Calculating the area of a rectangle
A function with two parameters (length and width) that returns the area.
example.som
// A function that calculates the area of a rectangle
функсия масоҳати_росткунҷа(дарозӣ: рақам, паҳнӣ: рақам): рақам {
// Calculating the area
тағ натиҷа: рақам = дарозӣ * паҳнӣ;
// Returning the result to where the function was called
бозгашт натиҷа;
}
// Using the function and printing the result
тағ а: рақам = масоҳати_росткунҷа(5, 3);
чоп.сабт("Масоҳат: " + а);terminal
somon run area.som
Масоҳат: 153. Exercises
Exercises to reinforce the topic. They can be done in groups or as homework.
- Create a function that takes the name of a student and their average grade and prints the message "You passed" or "You did not pass".
- Write a function called секарата that takes a number and returns its cube.
- Create a function that takes an age and returns "adult" or "minor".