Lesson 13

Functions

Functions

In this lesson: you will give a name to a part of a program and use it several times.

The whole lesson on one page

Functions

In this lesson: you will give a name to a part of a program and use it several times.

What is a function?

A function (функсия) is a part of a program with a name. You write it once and call it as many times as you like:

1функсия салом() {
2 чоп("Салом!");
3 чоп("Хуш омадед!");
4}
5
6салом();
7салом();
  • функсия салом() { … } declares a function. Nothing is printed yet.
  • салом(); calls the function: the commands inside it run.

Parameters

You can give values to a function. They are called parameters:

1функсия саломДиҳ(ном: сатр) {
2 чоп("Салом, " + ном + "!");
3}
4
5саломДиҳ("Зарина");
6саломДиҳ("Фарҳод");

ном: сатр is the parameter ном of type сатр (string). The type says what value is expected: сатр (string), рақам (number) or мантиқӣ (logical). If you pass a number instead of a string, the playground warns you.

Several parameters

1функсия хат(аломат: сатр, шумора: рақам) {
2 тағ натиҷа = "";
3 барои (тағ и = 0; и < шумора; и++) {
4 натиҷа += аломат;
5 }
6 чоп(натиҷа);
7}
8
9хат("*", 5);
10хат("-", 10);

Common mistakes

  • Declaring a function and not calling it: then nothing runs.
  • Forgetting the brackets when you call it: салом; instead of салом();.
  • A mistake in the name of the function: the playground suggests a similar name.

Task: Greeting

Write a function саломДиҳ(ном) ("greet(name)") that prints Салом, ном! ("Hello, name!"). Read two names and call the function for each of them.

Input: Two lines: two names.

Output: Two greetings.

Task: A line

Write a function хат(н) ("line") that prints н equals signs = on one line. Read a number and call the function.

Input: One number.

Output: One line of =.

Task: A table

Write a function ҷадвал(н) ("table") that prints the lines from н × 1 = … to н × 5 = …. Read a number and call the function.

Input: One number.

Output: Five lines.