Operators, strings and subroutines
Operators, strings and subroutines
- Programs combine values with operators and work with strings.
- To avoid repeating code, we use procedures and functions.
- Good naming and comments make a program maintainable.
Operators
- Arithmetic:
+ - * /,^(power),MOD(remainder),DIV(whole-number part). e.g.17 MOD 5 = 2,17 DIV 5 = 3. - Relational (give a Boolean):
= < <= > >= <>(not equal). - Logical:
AND(both true),OR(at least one),NOT(reverses).
Practice
What is 17 MOD 5?
MOD gives the remainder: 17 ÷ 5 = 3 remainder 2.
Practice
What is 17 DIV 5?
DIV gives the whole-number part: 17 ÷ 5 = 3 (remainder discarded).
String handling
- A string is made of characters. Useful operations:
- LENGTH (number of characters), SUBSTRING (a part), UCASE (capitals), LCASE (small).
name ← "Computer"
OUTPUT LENGTH(name) // 8
OUTPUT SUBSTRING(name, 1, 4) // "Comp"
Practice
What does LENGTH("Computer") return?
"Computer" has 8 characters.
Procedures, functions and good style
- A procedure does a task (run with
CALL); a function returns a value. - A parameter is a value passed in (up to three).
- A local variable exists only inside its subroutine (safer); a global is visible everywhere.
- Library routines:
MOD,DIV,ROUND,RANDOM. - A maintainable program uses meaningful names, comments, and subroutines.
Practice
How does a function differ from a procedure?
A function returns a value (used in an expression); a procedure just performs a task.
Practice
A local variable:
Locals are safer because other parts of the program cannot change them by mistake.
You've got it
Key idea
MOD= remainder,DIV= whole-number part; logicalAND/OR/NOT- strings: LENGTH, SUBSTRING, UCASE, LCASE
- a procedure does a task; a function returns a value; parameters pass values in
- local variables are safer than global; maintainable = meaningful names + comments + subroutines
Practice
Which makes a program more maintainable?
Clear names, comments and small subroutines make code easy to read and change later.