Expressions
We need values to work within the instructions in our code. In programming terminology the code for a value is known as an expression. So far we can have values (expressions) in our method calls and assignment statements. Each assignment statement has an expression that is the value to be assigned to the variable. In each method call, you have expressions for each argument.
Expressions allow you to calculate the value to be used. This can include standard mathematical operator (addition, subtraction, multiplication, and division), and work with values typed into the code (called literals), values read from variables and constants, and values returned from method calls.
Example
The expressions are highlighted in the following code that calculates a person’s body mass index.
using static SplashKitSDK.SplashKit;using static System.Convert;
string name, userInput;double weightInKg, heightInM;double bmi;
// The argument is a value (expression) - a string literalWriteLine("Welcome to the BMI calculator");
// As above - a string expression with the value hard codedWrite("Please enter your name: ");
// The expression's value is the result from the call to ReadLinename = ReadLine();
// The argument is a string expression - using + to concatenate valuesWriteLine("Hi " + name);
// As above - this takes one string value the text to writeWrite("Please enter your weight in kilograms: ");// The value in the assignment is the result of calling ReadLineuserInput = ReadLine();// There are two expressions here - userInput is used as the value// in the call to ToDouble. The result of ToDouble is the 2nd// expression as this is the value stored in weightInKgweightInKg = ToDouble(userInput);
// Same as above - for all three linesWrite("Please enter your height in meters: ");userInput = ReadLine();heightInM = ToDouble(userInput);
// There is one expression here - the result stored in bmi// it is calculated using division, multiplication etc.bmi = weightInKg / (heightInM * heightInM);
// You can use string interpolation with $"" this has// 2 expressions. The value bmi is injected into the string// and then the string value is used as the argument in WriteLineWriteLine($"The BMI of the data entered is: {bmi}");
Activities
What expressions are there in the following lines of code?
age = 21;
interestPayment = balance * rate;
WriteLine($"Hello {name}");
value = ToInt32(line);
OpenWindow("Hello", 1920, 1080);
Answers
- 1: There is one expression - the value 21
- 2: There is one expression - balance * rate
- 3: There are two expressions - name and "Hello {name}"
- 4: There are two expressions - line, and the result of calling ToInt32.
- 5: There are three expressions - "Hello", 1920, and 1080. Each of these is an argument in the OpenWindow method call.