module 1: basic digital skills unit 3: · pdf filelogical schemes are graphical notations made...

21
This project has been funded with support from the European Commission. This publication reflects the views only of the author, and the Commission cannot be held responsible for any use which may be made of the information contained therein. PROJECT TITLE PROJECT ACRONYM DATE OF DELIVERY AUTHORS ALEXANDRU STRUNGĂ EDITORS INTELECTUAL OUTPUT AVAILABILITY OF DELIVERABLE MODULE 1: BASIC DIGITAL SKILLS UNIT 3: ALGORITHMS, LOGICAL BLOCK SCHEMAS, CONTROL STRUCTURES

Upload: vunga

Post on 15-Mar-2018

218 views

Category:

Documents


3 download

TRANSCRIPT

This project has been funded with support from the European Commission. This publication reflects the

views only of the author, and the Commission cannot be held responsible for any use which may be made of

the information contained therein.

PROJECT TITLE

PROJECT ACRONYM

DATE OF DELIVERY

AUTHORS ALEXANDRU STRUNGĂ

EDITORS

INTELECTUAL OUTPUT

AVAILABILITY OF DELIVERABLE

MODULE 1: BASIC DIGITAL

SKILLS

UNIT 3: ALGORITHMS, LOGICAL

BLOCK SCHEMAS, CONTROL

STRUCTURES

Module/Unit: 1.3

https://www.silvercodeproject.eu/

Table of Contents

Entrance 2

Keywords 2

I. Module/unit overview 2

II. Learning content 2

Introduction (short description) 2

Learning Objective 3

1. Introduction to basic programming concepts 3

Variables 3

Constants 4

Keywords 4

Data Types 4

Operators 5

2. Introduction to algorithms 8

3. Logical block schemas 9

4. Testing a very simple algorithm in JavaScript 10

5. Control structures 11

Summary of Key Points (what did the participant learn) 17

III Conclusion 17

IV Further resources / Additional reading 17

Further resources 17

Additional reading 17

V Self-test questions 17

VI Glossary 18

VII References 19

Module/Unit: 1.3

https://www.silvercodeproject.eu/

Module/unit 1.3: ALGORITHMS, LOGICAL BLOCK SCHEMAS, CONTROL STRUCTURES _____________________________________________________________________

Entrance Keywords

Variables, constants, keywords, operators, algorithm, logical block schema, control

structures, sequence, selection, looping

I. Module/unit overview

Learning outcomes1 As a result of engaging with the materials in this module, learners are intended to

achieve the following learning outcomes:

Competences:

Defining basic programming concepts (variables, constants, keywords,

operators)

Defining the main notions presented in the unit (algorithms, logical block schema,

control structures)

Reading a logical block schema

Appreciating the importance of algorithms and control structures in coding

Using algorithms, logical block schemas and control structures in approaching a

coding problem

Time schedule

Structure

II. Learning content

Introduction (short description) The proper understanding of algorithms, logical block schemas and control structures

is critical in coding. Every application has a logical framework that can be expressed in very simple and finite steps and basic operations.

1 https://europass.cedefop.europa.eu/education-and-training-glossary/l

Module/Unit: 1.3

https://www.silvercodeproject.eu/

Learning Objective: What you will learn in this module/unit? - To define variables, constants, keywords, operators; - To define an algorithm; - To give real-life examples of algorithms; - To understand what is a logical block schema; - To use a logical block schema with a mathematical expression; - To construct a logical block schema for a simple application; - To appreciate the importance of algorithms and control structures in coding.

1. Introduction to basic programming concepts

Variables Like many other programming languages, JavaScript has variables. Variables can be

thought of as named container or storage for data. We can put data into these containers and then refer to the data simply by naming the container. The name of a variable, that will always start with a letter, can contain: upper-case letters, lower case letters, numbers and “..” character (underscore).

The statement below creates (in other words: declares or defines) a variable with the name “message”:

var message;

The semicolon “;” is used in JavaScript and other programming languages for a statement or a command given to computer. The comma operator “,” evaluates each of its operands (from left to right) and returns the value of the last operand.

Now we can put some data into it by using the assignment operator =, which we will

discuss in more detail further in the unit:

var message;

message = 'Hello'; // stores the string

The string is now saved into the memory area associated with the variable. We can access it using the variable name:

var message;

message = 'Hello!';

alert(message); // shows the variable content

To be concise we can merge the variable declaration and assignment into a single line:

var message = 'Hello!'; // define the variable and assign the

value

alert(message); // Hello!

Now, let’s try to create a HTML document and check if the code is executed properly.

First, we need to write the following code in Notepad++. We will save this as an HTML file

and proceed to run it in Chrome.

<script>

var message = 'Hello!'; // define the variable and assign the

value

Module/Unit: 1.3

https://www.silvercodeproject.eu/

alert(message); // Hello!

</script>

Constants

A constant is another important concept. It holds a value that is assigned when the

program is compiled, and never changes after that. Explicit constants are zones in memory

with fixed values, but without name. In the following code, 1 is an explicit constant:

var message = 1;

Symbolic constants are zones in memory with fixed values and without name, as it is

the case of PI in the following code:

var PI = 3.14;

var message = PI/2;

Keywords

By rule, keywords are reserved and cannot be used as variable or function names.

Here is the complete list of JavaScript keywords: break, case, catch, continue, default, delete,

do, else, finally, for, function, if, in, instanceof, new, return, switch, this, throw, try, typeof,

var, void, while, with.

If you use a keyword as a variable or function name, we will meet an error message

like this: “Identifier expected.” The same is true for reserved words, which, broadly speaking,

words that are reserved for future use as keywords. The complete list of reserved words is as

follows: abstract, Boolean, byte, char, class, const, debugger, double, enum, export, extends,

final, float, goto, int, interface, implements, import, long, native, package, private, protected,

public, short, static, super, synchronized, throws, transient, volatile. It is recommendable to

avoid the use of reserved words in coding.

Data Types

A variable can contain any data. However, we can use 7 basic data types in

JavaScript. The first category are primitive data types (numbers, string, Booleans, null and

undefined. The second category are objects and symbols.

number for numbers of any kind: integer or floating-point;

string for strings. A string may have one or more characters, there’s no separate single-character type;

boolean for true/false;

Module/Unit: 1.3

https://www.silvercodeproject.eu/

null for unknown values – a standalone type that has a single value null;

undefined for unassigned values – a standalone type that has a single value undefined;

object for more complex data structures;

symbol for unique identifiers.

Let’s try to test in JavaScript these data types using the information we learned about

variables and constants. Create a HTML document using the following code, in Notepad++

and save it in a HTML file. Next, proceed to run it in Chrome.

<script>

var message1 = 1; // define the variable to a number data type

var message2 = 'Hello!'; // define the variable to a string data

type

var message3 = true; // define the variable to a boolean data

type

var message4 = null; // define the variable as null data type

var message5 = []; // define the variable to an object data type

(array)

var showme = typeof message1; // we declare a variable and

assign it to the result of typeof operator for message1

console.log(showme); // we ask the console to show the result

</script>

What is the result? In the end of the code section we added a typeof operator that

can return information about the data type, which in our case is number. We can try using

the same code for the rest of variables (message 2 to 5).

Operators

JavaScript operators are used to assign values, compare values, perform arithmetic

operations, and much more.

Let’s take a simple expression 8 + 2 is equal to 10. Here 4 and 5 are named

operands and ‘+’ is called the operator.

JavaScript supports the following main types of operators:

Arithmetic Operators

Comparison Operators

Logical (or Relational) Operators

Assignment Operators

Conditional (or ternary) Operators

Module/Unit: 1.3

https://www.silvercodeproject.eu/

In this unit we will approach

only several type of operators: arithmetic, comparison, logical and assignment. More

details about using operators will be provided in the following modules.

a) Arithmetic operators (given that y = 5):

Operator

Description Example Result in y Result in x

+ Addition x = y + 2 y = 5 x = 7

- Subtraction x = y - 2 y = 5 x = 3

* Multiplication x = y * 2 y = 5 x = 10

/ Division x = y / 2 y = 5 x = 2.5

% Modulus x = y % 2 y = 5 x = 1

++ Increment x = ++y y = 6 x = 6

x = y++ y = 6 x = 5

-- Decrement x = --y y = 4 x = 4

x = y-- y = 4 x = 5

Let’s try to use these operators with the variables we’ve learned earlier:

<script>

var message = 2; // define the variable and assign the value

var myoperator = message + 2; // adding 2 to var message

console.log(myoperator)// 4

</script>

Module/Unit: 1.3

https://www.silvercodeproject.eu/

a) Comparison operators (given that x = 5):

Operator Description Comparing Returns

== equal to x == 8 false

x == 5 true

=== equal value and equal type x === "5" false

x === 5 true

!= not equal x != 8 true

!== not equal value or not equal type x !== "5" true

x !== 5 false

> greater than x > 8 false

< less than x < 8 true

>= greater than or equal to x >= 8 false

<= less than or equal to x <= 8 true

b) Assignment operators (given that x = 10 and y = 5):

Operator Example Same As Result in x

= x = y x = y x = 5

+= x += y x = x + y x = 15

-= x -= y x = x - y x = 5

*= x *= y x = x * y x = 50

/= x /= y x = x / y x = 2

%= x %= y x = x % y x = 0

Module/Unit: 1.3

https://www.silvercodeproject.eu/

c) Logical operators (given that x = 6 and y = 3)

Operator Description Example

&& and (x < 10 && y > 1) is true

|| or (x === 5 || y === 5) is false

! not !(x === y) is true

2. Introduction to algorithms

The notion of algorithm originates from the name of Arab mathematician and astrologist Al-Khwarizmi who lived in the 9th century A.D.

There are several modalities of understanding the notion of algorithm: (1) A thinking pattern used for resolving a problem in a finite number of steps; (2) A way of thinking – algorithmic thinking;

We can think of several ways of expressing algorithms: (a) Natural language

The algorithms for how to calculate arithmetic mean of two numbers is: 1) Start; 2) Read the first number; 3) Read the second number; 4) Calculate their sum; 5) Divide the result to 2; 6) Display the calculated result; 7) Stop.

(b) Pseudocode

Pseudocode is an informal high-level description of the operating principle of a computer program. The algorithm for how to calculate the largest number in a list of numbers of random order is:

read i=0 for i<n read a[i] i=i+1 end for

(c) Logical block schemas – block diagrams

Module/Unit: 1.3

https://www.silvercodeproject.eu/

Logical schemes are graphical notations made up of blocks linked to each other by arrows.

A fragment of the logical block schema for the module function is the following figure:

3. Logical block schemas A logical block schema graphically describes the steps of an algorithm and processing

executed on the data. There are several categories of data included in the logical block schemas:

(1) variables: memory zones that are changing values and are characterized by a name; The name can be a combination of lower case letters, upper case letters, numbers and “_” sign (underscore). Examples: aria, Aria, perimeter, volume, length etc.

(2) constants: memory zones with fixed value, without name (explicit constants) or memory zones with fixed value and name (symbolic constants). Examples: π (PI)

The basic operations of logical block schemas are the following:

start block

stop block

reading block

writing block

attribution block

decision block

Module/Unit: 1.3

https://www.silvercodeproject.eu/

In logical block schemas, we will meet many of the elements described above.

Flowcharting (or elaborating logical block schemas) has many advantages: (a) communication: flowcharts are better way of communicating the logic of a system to all concerned; (b) effective analysis: with the help of flowchart, problem can be analyzed in more effective way; (c) proper documentation: program flowcharts serve as a good program documentation, which is needed for various purposes; (d) efficient coding: the flowcharts act as a guide or blueprint during the systems analysis and program development phase; (e) proper debugging: the flowchart helps in debugging process; (f) efficient program maintenance: the maintenance of operating program becomes easy with the help of flowchart; it helps the programmer to put efforts more efficiently on that part.

4. Testing a very simple algorithm in JavaScript

An example of using a very simple algorithm (using logical block schema, pseudocode and JavaScript code), is to find out the sum of two numbers.

Module/Unit: 1.3

https://www.silvercodeproject.eu/

Here are the lines of code that we can test ourselves by running Chrome: <script>

var n1 = Number(prompt("Enter first number"));

var n2 = Number(prompt("Enter second number"));

var sum = n1+n2;

console.log(sum);

</script>

Let’s try to explain what’s happening step-by-step: 1. we declared two variables (n1 and n2) and we asked the user for a value for each one

of them; 2. we declared that the variable sum is the sum of n1 and n2; 3. the output is displayed (the sum of n1 and n2).

5. Control structures A control structure is a block of programming that analyzes variables and chooses a

direction in which to go based on given parameters. The term flow control details the direction the program takes (which way program control "flows"). Hence it is the basic decision-making process in computing; flow control determines how a computer will respond when given certain conditions and parameters.

Pseudocode read a and b sum=a+b write sum

Module/Unit: 1.3

https://www.silvercodeproject.eu/

The flow of control through any given function is implemented with three basic types of control structures:

1. Sequence: sequential execution of code statements (one line after another) -- like following a recipe

2. Selection: used for decisions, branching -- choosing between 2 or more alternative paths. In Javascript, for exemple, we can use different types of selection statements:

if else if switch

3. Looping (or repetition): used for looping, i.e. repeating a piece of code multiple times in a row. In Javascript, we can use loop statements such as:

while do/while for

The sequence is the simplest control structure, an abstract notation used to define other control structures (represented in the above figure). While not directly used in logical schemas, it usually include basic operations such as: one reading, two attributions, one decision.

Here is an example of JavaScript sequence! In first line of code we declare a new variable (averageGrade) that the user must input its value in the JavaScript prompt; in the third line of code, we add 1 to the value of averageGrade so the current value is 2; in the fourth line of

code we display the value of the variable. <script>

var averageGrade = Number(prompt("Guess the number from

1 to 10! You can only try once!"))

var averageGrade = averageGrade + 1;

console.log(averageGrade);

Module/Unit: 1.3

https://www.silvercodeproject.eu/

</script>

The selection is a control structure that has the role of selecting a sequence of two for

execution depending on the condition value. It is represented by the graphical elements of the appropriate decision block.

<script>

var averageGrade = Number(prompt("Guess the number from

1 to 10! You can only try once!"));

if (averageGrade == 8) {

console.log ("You won!");

}

else {

console.log ("You lost!");

}

</script>

Pseudocode read a a=1+1 write a

Module/Unit: 1.3

https://www.silvercodeproject.eu/

Here is a JavaScript example for selection! In first line of code, we declare a new variable

(averageGrade) that the user must input in the JavaScript prompt; in the next lines of code we have two possible situations: if the averageGrade is equal to 8, the message “You won!” will

Pseudocode read a if a==8 write “You won!” end if else write “You lost!” end else

Module/Unit: 1.3

https://www.silvercodeproject.eu/

be displayed; (2) if the averageGrade is less or more than 8, the message “You lost” will be displayed.

A loop in coding is an instruction that repeats until a specified condition is reached. In a loop control structure, the loop asks a question. If the answer requires an action, it is executed. The same question is asked again and again until no further action is required. Each time the question is asked is called an iteration. According to the position of the sequence included in the loop, we can identify: (a) loops with initial test and (b) loops with final test. A third type of loop is the loop with counter. It has a more complex structure, and it is based on a counter that (1) has an initial value; (2) go through all the values of a continuous range (3) until a final value is reached and (4) every step is executed in the same sequence.

<script>

var averageGrade = 8;

for(var i=0; i<averageGrade; i++)

{

console.log(i);

}

</script>

Here is a JavaScript example for a loop or repetition! In first line of code, we declare a

new variable (averageGrade) that is equal to 8; in the next lines of code we have a loop that repeats if the condition are satisfied. The condition is that i must be less than the value of averageGrade which is 8. If so, the number will be displayed on the screen. In the end, 8 numbers will be displayed (0,1,2,3,4,5,6,7), after each loop.

Module/Unit: 1.3

https://www.silvercodeproject.eu/

Pseudocode read and b sum=a+b write sum

Module/Unit: 1.3

https://www.silvercodeproject.eu/

Summary of Key Points (what did the participant learn)

The participant learned the definitions of basic programming concepts, algorithms, logical block schemas and control structures and how can be used in coding. The participant has also started to use logical block schemas in describing simple real-life tasks or basic applications.

III Conclusion

Defining, understanding and using algorithms is a key basic digital skill in coding. Only if the control structures are clearly defined and coherently expressed, a coding activity can be carried out successfully.

IV Further resources / Additional reading

Further resources To directly try the applications from chapter 3 we can test the code in a virtual

JavaScript compiler, which is available online here. What result do you get when

inserting the code individually, for each algorithm?

Additional reading

McPeak, J. & Wilton, P. (2015). Beginning Javascript. Indianapolis: John Wiley &

Sons.

Groner, L. (2016). Learning JavaScript Data Structures and Algorithms. Birmingham:

Packt Publishing Ltd.

Larsen, J.R. (2016). Get Programming with JavaScript. Shelter Island: Manning

https://en.wikiversity.org/wiki/Category:Introduction_to_Computer_Science

V Self-test questions 1. The “>” operator is a:

a. logical operator

b. comparison operator

c. arithmetical operator

d. assignment operator

2. An algorithm is a:

a. piece of code with infinite number of steps;

b. a thinking pattern used for resolving a problem in a finite number of

steps;

c. a mathematical theory.

Module/Unit: 1.3

https://www.silvercodeproject.eu/

3. A logical block schema includes:

a. start block;

b. stop block;

c. reading block;

d. writing block;

e. attribution block;

f. decision block;

g. all the above;

h. neither option is correct.

3. Which one of the above is a control structure?

a. Sentence;

b. Selection;

c. Concatenation.

4. What is the number of iteration for the following pseudocode:

X is 0

WHILE X is less than 10

add 1 to X

a. 1

b. 5

c. 8

d. 9

e. 10

5. Give an example from day by day life which can be explained as an algorithm.

VI Glossary Variable*

Constant*

Operator*

Keyword*

Algorithm*

logical block schema*

start block*

stop block*

reading block*

writing block*

attribution block*

decision block*

control structure*

sequence*

selection*

loop*

Module/Unit: 1.3

https://www.silvercodeproject.eu/

VII References McPeak, J. & Wilton, P. (2015). Beginning Javascript. Indianapolis: John Wiley &

Sons.

Groner, L. (2016). Learning JavaScript Data Structures and Algorithms. Birmingham:

Packt Publishing Ltd.

Larsen, J.R. (2016). Get Programming with JavaScript. Shelter Island: Manning

https://en.wikiversity.org/wiki/Category:Introduction_to_Computer_Science

http://users.evtek.fi/~jaanah/IntroC/DBeech/3gl_flow.htm

https://www.w3schools.com/js/js_if_else.asp

https://www.edx.org/course/introduction-computer-science-harvardx-cs50x

http://www.cs.unm.edu/~joel/cs105/cs105.html

https://javascript.info/operators

http://speakingjs.com/es5/ch01.html#_variables_and_assignment

Learning Objective (at the beginning: What you will learn in this module/unit?)

Summary of key points (at the end: What did you learn?)

Important

Problem/Question (for discussion/reflection)

Background Information

to keep in mind

Advise/Hint/Tip

Definition

Task/To-do

Download

Module/Unit: 1.3

https://www.silvercodeproject.eu/