8. Functions
To write a function with parameters and a return type, and to call it after defining it.
Explanation
Section titled “Explanation”- A function is a named group of instructions. It starts with a line such as
داله مساحة(ط كسر64, ع كسر64) كسر64:, followed by its body indented underneath. - Between the parentheses are the parameters: the name and type of each value the function takes. After the parentheses comes the return type: the type of what it returns. A function that returns no value has the return type
فراغ(void). ارجع(return) ends the function and returns the value written after it.- A function is called after its definition in the file.
Example
Section titled “Example”داله مساحة(ط كسر64, ع كسر64) كسر64: ارجع ط * عاطبع(مساحة(2.5, 4.0))Common mistakes
Section titled “Common mistakes”Calling a function before defining it:
اطبع(ضعف(2))داله ضعف(س عدد64) عدد64: ارجع س * 2Exit code: 2
In the error catalog: E0125
داله ضعف(س عدد64) عدد64: ارجع س * 2اطبع(ضعف(2))And a function with a path that ends without ارجع:
داله اشارة(س عدد64) نص: اذا س > 0: ارجع "موجب"اطبع(اشارة(-1))Exit code: 2
In the error catalog: E0266
داله اشارة(س عدد64) نص: اذا س > 0: ارجع "موجب" ارجع "غير موجب"اطبع(اشارة(-1))Exercise
Section titled “Exercise”Write a function اولي(ن عدد64) منطقي that returns صواب (true) if ن is prime, and use it to print the primes up to 30.
Show the solution
داله اولي(ن عدد64) منطقي: اذا ن < 2: ارجع خطاء ق = 2 طالما ق * ق <= ن: اذا ن % ق == 0: ارجع خطاء ق += 1 ارجع صواب
لكل ع في مدى(1, 31): اذا اولي(ع): اطبع(ع)