Presentation is loading. Please wait.

Presentation is loading. Please wait.

Programming Techniques :: Data Types and Variables

Similar presentations


Presentation on theme: "Programming Techniques :: Data Types and Variables"— Presentation transcript:

1 Programming Techniques :: Data Types and Variables
Last modified: 29th May 2019

2 www.drfrostmaths.com ? Everything is completely free.
Why not register? Registering on the DrFrostMaths platform allows you to save all the code and progress in the various Computer Science mini-tasks. It also gives you access to the maths platform allowing you to practise GCSE and A Level questions from Edexcel, OCR and AQA. With Computer Science questions by: Your code on any mini-tasks will be preserved. Note: The Tiffin/DFM Computer Science course uses JavaScript as its core language. Most code examples are therefore in JavaScript. Using these slides: Green question boxes can be clicked while in Presentation mode to reveal. Slides are intentionally designed to double up as revision notes for students, while being optimised for classroom usage. The Mini-Tasks on the DFM platform are purposely ordered to correspond to these slides, giving your flexibility over your lesson structure. ?

3 𝑥=4 𝑃={1,4,5} 𝒂= 3 −2 RECAP :: Value Types in Maths
In maths, variables are used to represent values. 𝑥=4 𝑃={1,4,5} 𝒂= 3 −2 Values need not be numbers. At GCSE you have seen variables representing different types of values, e.g. sets and vectors.

4 Value Types in Programming
We can similar assign values to variables in most programming languages. And as with mathematics, variables can have different types. Can you name some of the main data types? Name Typically written in code as Description Examples Integer int Whole numbers only 4, 0, -1 Real/Float real/float Any decimal number. 3, -2.4, 4.796 Double double A decimal with extra accuracy – when we need to store more digits. Boolean bool True/false values true, false Character char A single symbol. 'a', '0’, '?' String string Text, i.e. a collection of characters. "Ashwin", "B", "Cat123" ? ? ? ? ? ? ? ? Typically strings are in double quotes, e.g. "Ashwin", but characters are in single quotes, e.g. 'a'. However, many languages allow single quotes for strings: ‘Ashwin’ will be interpreted as a string as there are multiple characters. ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? These are known as primitive data types; they are the most simple data types upon which more complex ones (e.g. objects, arrays) are formed from. Technical Note: Strings are not primitive in languages such as Java, because they are considered as collections of characters (i.e. an array). We’ll see the practical implication of primitive types later…

5 Name That Type! true 7 -3.00 'c' "B" "Dog" false 3.95 Boolean Real
? true Boolean ? -3.00 'c' Character* Real ? ? "B" String ? "Dog" String ? false Boolean ? ? 3.95 Real *However, JavaScript does not explicitly have a character type: all characters are just strings of length 1.

6 Declaring Variables ? ? ? We create new variables by declaring them.
Coding Note: A statement in programming is a single instruction. Statements are separated by semicolons. Usually (but not necessarily) we try to have one statement per line. Declaring a variable is an example of a statement. JavaScript: ? var x = 5; var y = "Hello"; var declares a variable. JavaScript is known as a weakly-typed language, because variables are not constrained to a particular type; we can reassign x with a value of a different type. PHP: ? $x = 5; $y = "Hello"; C++ is an example of a strongly-typed language, so the type of variables (here int and char) must be stated when they are declared. When x and y are subsequently used in code, the code will know the types of these variables and therefore can check they are used in a way which respects their type. C++: ? int x = 5; char y = ‘b’;

7 10 Updating the Values of Variables ? Output var x = 5; x = 7;
JavaScript: ? Output var x = 5; x = 7; var y = x + 3; console.log(y); 10 The = symbol assigns a variable a value. Variables should only be declared once, do you should not use var on the second line. Line 1 is a declaration while line 2 updates the value of x. The process of declaring a variable and assigning it a value are separate. When we write var x = 5 , this is a short for: var x; x = 5; If we removed the above second line, it’s possible to declare a variable without assigning it a value. Its value until then will be undefined until we assign it with the 5. These output to the console, a command line interface where programs are often run from and outputted text can be seen. If you are coding JavaScript, you can view the console in Google Chrome by pressing Ctrl + Shift + I. C++: int x = 5; x = 7; int y = x + 3; cout << y Very important: = is for assignment, and does not mean equality (i.e. determining if two values are equal), which we will encounter in further lessons. We can write x = 7 (meaning “let x be the value 7”), but not 7 = x.

8 More on Weakly vs Strongly Typed Languages
JavaScript: var x = 5; console.log(x); x = "hello"; ? Does it work Because x isn’t restricted to a particular type, its type can change from int to String when x is reassigned on line 3. The code runs without error and outputs 5 and hello. When x is declared, it is constrained to integer values only in subsequent usage. C++ ? Does it work This will raise an error when the code is compiled. As x is declared as an integer variable, the compiler checks that any subsequent lines of code respects this. But in line 3 we’re trying to reassign this integer variable a string value. int x = 5; cout << x; x = "hello"; cout << x;

9 More on Weakly vs Strongly Typed Languages
JavaScript: Advantages of weakly typed languages: More flexibility: a function for example could return one type in one circumstance and another type in another. Values can readily change from one type to another. For example if x = 3, then "Bob" + x would convert the 3 to a string before appending them to get "Bob3", whereas in strongly typed languages we’d get an error as “Bob” and x are of inconsistent types. Disadvantage of weakly typed languages: More prone to errors when running the program (i.e. at “runtime”), as we can’t be sure our variables are of the type we think they are. e.g. If we had x.toUpperCase() in our code and x happened to be an integer (instead of a string), a strongly-typed language would warn us when trying to compile the code. A weakly-typed language would not, and only at runtime would the problem emerge. ? var x = 5; console.log(x); x = "hello"; C++ ? int x = 5; cout << x; x = "hello"; cout << x;

10 Determining the type of a variable
With weakly-typed language, we saw that we can’t guarantee the current type of the variable. Suppose we wanted some code that checked the answer, stored in the variable ans, to a question. The answer could be a word (a string) or a number… typeof is a special operator which gives the type (as a string) of value or variable that follows it. if(typeof ans == "string") { // Deal with textual answer. } else if(typeof ans == "number") { // Deal with numeric answer. } This kind of type checking is useful for writing utility functions, as we can accommodate different inputs without restricting to a particular type. What is the surprising thing here? JavaScript has a type ‘number’, and does not distinguish between integers and reals. This is akin to mathematics, where numbers may or may not have a decimal part, but are ultimately just ‘numbers’. ?

11 Constants vs Variables
In mathematics, constants are values which are fixed and cannot change. Can you think of symbols in maths presenting fixed values? 𝜋= … 𝑒= … Pi Euler’s Number (which you will encounter at A Level) var PI = ; PI = 42; const PI = ; ? How could we fix it ? What could go wrong Attempting to overwrite its value now gives the following error: TypeError: Assignment to constant variable. By declaring PI as a ‘variable’, there’s nothing preventing us assigning it a different value. To improve the ‘maintainability’ of our code we should prevent ourselves/other coders accidentally overwriting it. Note: Various mathematical constants are already available in JavaScript via libraries. For pi, use Math.PI

12 Variable Naming Conventions
In mathematics there are a variety of variable naming conventions: Single letter (English alphabet, e.g. 𝑥 or Greek, e.g. 𝜃) Typically lower case for numeric values (𝑥=4), capital letters for sets (𝑋={1,2,3}), bold lower case for vectors (𝒂= ) In programming we also have variable naming conventions. Lower case words (or single letter) for normal variables. var total = 0; var twoWords = 'c'; const LIMIT = 10; Capitalise each subsequent word. Upper case for constants.

13 Casting ? ? ? ? 4 var x = 3.45; var a = String(x); var b = Boolean(x);
Just like in mathematics where we may want to convert between fractions, decimal and percentages, there are many circumstances where might want to convert a value from one type to another. This is known as casting. ? 4 String(x) converts x to a string, allowing us to access various string functions, in this case the length (number of characters) in “3.45”. var x = 3.45; var a = String(x); var b = Boolean(x); var y = "103.2"; var z = "Hamster"; var c = Number(y) – 100; var d = Number(z); console.log(a.length); console.log(b); console.log(c); console.log(d); true 0 is converted to false and anything else to true. In the opposite direction: Number(false) = 0; Number(true) = 1; ? ? 3.2 Converting the string to a number allows us to do arithmetic operations on it. ? NaN NaN = “Not a Number” is a special numeric value to indicate the number is… not a number.

14 Casting in other languages
The syntax: (type) x casts x to the type type. C++ double x = 10.3; int y; char a = 'M'; int b; y = (int) x; cout << y; b = (int) a; cout << b; ? Outputs 10. Reals/floats/doubles are truncated (i.e. rounded down) when cast to integers. ? Outputs 77. Converting a character to an integer gives us the underlying number used to represent it. We will look at this further when we study ASCII. In JavaScript there is no character type, but we could use “M”.charCodeAt(0)

15 How variables are stored in memory
Most variables are stored in the memory stack. C++: Memory Address: int x = 5; if(x < 10) { char c = 'A'; } string y = “Hello”; int x 5 1 Each type requires some amount of memory in the stack. An int requires 4 bytes. 2 3 char c char requires 1 byte. 4 'A' string y An variables declared within a statement block, { … }, are no longer available when we reach the end of this block of code. The reference to this part of this stack is removed, so ‘A’ is now in limbo! In languages like C++, we sometimes need to manually ‘free up’ this memory. Languages like JavaScript have garbage collection, which automatically frees up values in the memory which are no longer used. 5 6 7 strings take up 1 byte per character. However, these aren’t stored in the stack, because were we to increase the length of the string later, we would end up overlapping with what’s stored for any variables further down the stack. Instead, we store an address, or ‘pointer’ of somewhere in a more flexible memory store called the heap. We only therefore store values directly in the stack when we know exactly how much memory will be required to store that value. Heap "Hello"

16 How variables are stored in memory
Data Type Amount of memory Integer 2 bytes (if limited to to 32767) or 4 bytes (anything between ±2 billion) Real float: 4 bytes double: 8 bytes Boolean 1 bit (i.e. a 0 or 1) but 1 byte used. Character 1 byte String 1 byte per character ? ? ? ? ?

17 Review ? ? ? ? Name the ‘primitive’ types.
Integer, String, Character, Real, Boolean. What is the difference between declaring and assigning? Declaring a variable ‘creates’ it and allocates it memory. Assigning gives the variable a value. What is casting and why might we use it? Casting is converting a value to another type. Used for example if we wanted to use an integer within a string, e.g. "Your age is "+age; What is the difference between weakly-typed and strongly-typed languages? Strongly-typed languages enforce a particular type on a variable once it is declared. We can’t then for example assign this variable a value of the wrong type, and we guarantee for later code what type this variable is. Weakly-typed languages allow the type of a variable to change. ? ? ? ?

18 Coding Mini-Tasks Return to the DrFrostMaths site to complete the various mini-coding tasks on functions.


Download ppt "Programming Techniques :: Data Types and Variables"

Similar presentations


Ads by Google