Variables, Constants, and Operators
Variables
Variable
A named storage location in memory that can hold a value, which can be changed during the execution of a program.
Variables are used to store data that may vary, such as user input or intermediate results.
Example- Consider a variable score in a game algorithm.
- As the player earns points, the value of the score increases.
When it comes to declaring data types of variables, there are two types of programming languages:
- Strongly Typed Languages
- A variable’s data type is strictly enforced.
- You cannot use a value of one type as if it were another without explicit conversion.
- Weakly Typed Languages
- The language allows more flexibility in how types are used.
- Implicit conversions between types are often performed automatically.
- In Python, a variable can be defined as x = 10, where x is the variable name and 10 is its value without specifying its data type.
- But in Java, you need to say that x is an integer explicitly:
int x = 10;In the official IB pseudocode that you will use in the examination, variable names ought to be in all capitals and a value is assigned via the = sign.
X = 10
output X- Use meaningful variable names to improve readability, for example, use totalPrice instead of tp.
- Avoid using the same variable for multiple purposes, as it can lead to confusion and errors.
Constants
Constant
A named storage location in memory that holds a value, which cannot be changed during the execution of a program.
Variables and constants are both used to store data, but constants cannot be changed after they are defined, for instance, mathematical constants or configuration settings.
Example- In a physics simulation, the constant GRAVITY might be set to 9.8 m/s².
- This value remains unchanged throughout the simulation.
- In a weather forecasting algorithm, variables store real-time data such as temperature and humidity.
- Constants represent fixed values like the freezing point of water.
- Usually, for clarity, constants are given names in all capitals.
- Use constants to avoid hardcoding values.
- Using constants makes your algorithm easier to maintain and reduces the risk of errors, as otherwise, this can lead to unintended changes and bugs.
In Java, a constant can be defined by adding the keyword final to the declaration of a variable.
final int MAX_SCORE = 100;Operators
Operator
A function that performs an operation on one or more operands.
- Operators are used to perform operations on variables and values.