Data Structures Notes
Data Structures Notes
Competency: Apply Data Structure and Algorithm Fundamentals Using Java Script
Competency: Apply Data Structure and Algorithm Fundamentals Using Java Script
1. Apply 1.1 Number systems are correctly converted according to the base conversion
Algorithm methods
Fundamental
s 1.2 Logic gates and expressions are well described based on boolean algebra
1.3 Data types are effectively used according to their intended use
2.1 Data structure concepts are clearly identified based on intended use.
2.2 Linear Data Structures are properly applied based on their operational
2. Apply Data
complexity
Structure
2.3 NonLinear Data Structures are properly applied based on their operational
complexity
3.1 JavaScript Source code is properly developed based on Algorithm
3. Implement 3.2 JavaScript source code is successfully run in accordance with expected
Algorithm using result
JavaScript
3.3 Time and space complexity are successfully tested based on data structure
standards
Learning outcomes: At the end of the module the learner will be able to:
Here's what the decimal and hexadecimal systems look like for digits 0 to 15.
Decimal 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Hexadecimal 0 1 2 3 4 5 6 7 8 9 A B C D E F
Octal base has a base of eight and uses the numbers from 0 to 7. The octal numbers, in
the number system, are usually represented by binary numbers when they are grouped in pairs of
three. For example, an octal number 128 is expressed as 0010102 in the binary system, where 1 is
equivalent to 001 and 2 is equivalent to 010.
Base – 8
13 ÷ 2 6 1 (LSB)
6÷2 3 0
3÷2 1 1
1÷2 0 1 (MSB)
After noting the remainders, we will write them in such a way that the Most Significant Bit (MSB) of the
binary number is written first, followed by the rest. Therefore, the binary equivalent for the given decimal
number 1310 is 11012. This means that 1310 = 11012.
Decimal to Binary Table
There are different methods of converting numbers from decimal to binary. When we convert numbers from
decimal to binary, the base of the number changes from 10 to 2. It should be noted that all decimal numbers
have their equivalent binary numbers. The following table shows the decimal to binary chart of the first
20 whole numbers.
0 0
1 1
2 10
3 11
4 100
5 101
6 110
7 111
8 1000
9 1001
10 1010
11 1011
12 1100
13 1101
14 1110
15 1111
16 10000
Decimal Numbers Binary Numbers
17 10001
18 10010
19 10011
20 10100
Examples
1: Convert 17410 to binary.
2: Convert the following decimal number into binary number: 156
3: State true or false with reference to decimal to binary conversion.
a.) The binary number system has a base of 2 since it uses only two digits to represent a number.
b.) When the decimal number 10 is converted to binary, it gives the value as 1010.
c.) When the decimal number 4 is converted to binary, it gives the value as 100.
Solution:
a.) True, the binary number system has a base of 2 since it uses only two digits to represent a number.
b.) True, when the decimal number 10 is converted to binary, it gives the value as 1010.
c.) True, when the decimal number 4 is converted to binary, it gives the value as 100.
There are two main methods for converting binary number systems into decimal number systems. These
methods are:
1. Positional Notation
2. Doubling
Conversion Using Positional Notation
Write the binary number and count the power of 2 from right to left, starting from 0 onwards.
Now each binary number has the corresponding power of 2 starting from right to left. So the
most significant bit will have the highest power of 2.
Add the product of the second step
The final answer will be converted into a decimal number that is base 10.
Example of Positional Notation
1 0 1
1 x 22 + 0 x 21 + 1 x 20
4+0+1
(5)10
1 0 1.1 0 1
(4 + 0 + 1) . (0.5 + 0 + 0.125)
(5.625)10
Conversion using doubling is one of the simplest ways for converting binary numbers into decimal numbers.
We need to take the most signification bit or leftmost digit of the number. Then multiply the digit by 2 and
add the second leftmost bit and store the result. Similarly, we need to take the result and multiply it by 2 and
take the third leftmost bit and update the result. This process will continue till we reach the least significant
bit which is the rightmost bit. Since we are multiplying by 2 so this process is known as Doubling.
Example of Doubling
=1x2+0=2
=2x2+1=5
The formula to convert binary number system into decimal can be represented by,
Where,
For Example :
(1000)2 = 1 x 23 + 0 x 22 + 0 x 21 + 0 x 20
0000 0 1000 8
0001 1 1001 9
0010 2 1010 10
Binary1 Decimal1 Binary2 Decimal2
0011 3 1011 11
0100 4 1100 12
0101 5 1101 13
0110 6 1110 14
0111 7 1111 15
To convert a decimal number to an octal number, there are several direct and indirect methods. They are as
given below:
o Decimal to Octal Conversion Using by Direct Method: As the name suggests decimal numbers are
directly converted to octal numbers.
o Decimal to Octal Conversion Using by Indirect Method: This method converts the decimal number
into a binary number or hexadecimal first and then converts that to an octal number.
To convert a Decimal number to an Octal number directly, you must start dividing the number by 8 until you
get 0 as the quotient. This is a straightforward method that involves dividing the number to be converted.
Step 1: If the decimal number is N, divide it by 8 because the octal number system’s base is 8.
Step 2: Note the value of the residual, which will be one of the following: 0, 1, 2, 3, 4, 5, 6, or 7. Divide the
remaining decimal number until it equals 0 and record the remainder of each step.
Step 3: Then, from bottom to top (or in reverse order), write the remainders, which will be the equivalent
octal number of the provided decimal number.
As mentioned above this method converts the decimal number into a binary number or hexadecimal first and
then converts that binary or hexadecimal number to an octal number.
Let’s see how to convert decimal numbers to binary to octal conversion. By repeatedly dividing a number by
two and recording the result, decimal values can be transformed into binary.
4310=1010112
A binary number can be converted to an octal number in a variety of ways. Direct and indirect approaches
can both be used to convert. To begin, you must convert a binary into a different base system (e.g., into
decimal, or into hexadecimal). After that, you must convert it to an octal number.
Because the octal number system has only eight digits (from 0 to 7), we may express each octal digit using
only three bits, as seen below.
0 000
1 001
2 010
3 011
4 100
5 101
6 110
7 111
Step 2: Each set of three binary digits should be converted to one octal digit.
= (1010111100)
= (1 2 7 4)
= (1274)
This is a simple procedure that involves dividing the number to be transformed by two.
Step 1: If the decimal number is N, divide it by 16 because the hexadecimal number system’s base is 16.
Make a note of the value of the remainder, which will range from 0 to 15 (replace 10, 11, 12, 13, 14, 15 with
A, B, C, D, E, and F respectively). Divide the remaining decimal number until it equals 0 and record the
remainder of each step. Then, from bottom to top (or in reverse order), write the remainders, which will be
the equivalent hexadecimal number of the supplied decimal number.
Example:
Converting with Division
This approach works by estimating a decimal number’s hexadecimal equivalent. Any decimal number can
be used as a starting point. Make a list of 16’s abilities. Multiply the decimal number by the 16th power.
Find the rest of the items. Multiply the residual by the 16th power. Repeat until you’ve figured out the whole
solution.
Example:
Now we will convert hexadecimal number to octal number. Here are the steps:
Step 2: If n is the digit’s position from the right end, multiply each digit by 16n−116�−1.
Step 3: After you’ve multiplied the terms, add them together. The comparable decimal form is the resultant.
Step 5: With the quotient, repeat the previous two steps until the quotient is zero. Reverse the order of the
remainder. The obtained number corresponds to the desired outcome.
Example:
Convert Decimal to Octal including Decimal Point
To convert Decimal to Octal including decimal points, we first convert it to hexadecimal and then convert it
to octal.
If the decimal fractional portion is M, multiply it by 16 because the hexadecimal number system’s base is
16. Take note of the integer part’s value, which will range from 0 to 15. (replace 10, 11, 12, 13, 14, and 15
by A, B, C, D, E, and F respectively). Multiply the remaining decimal fractional number until it equals 0 and
record each integer part of the result. Then write the integer part’s results, which will be a fraction
hexadecimal number comparable to the specified decimal value.
Once we get the hexadecimal number we convert it to octal using the steps we discussed above.
4330/8 541 2
541/8 67 5
67/8 8 3
8/8 1 0
1/8 0 1
Example 2: What is the number 4321.356104321.35610 in the octal number system? (till 6 significant
digits)
Solution: In order to convert 4321.356104321.35610 into octal, we divide it into two parts of whole number
and fraction. First, let’s convert the whole number part. We divide the number 4321 by 8 till we get the
quotient 0.
4321/8 540 1
540/8 67 4
67/8 8 3
8/8 1 0
1/8 0 1
We read the reminder in reverse order. So 44010=14352844010=143528. Next is the conversion of the
fraction part. If the decimal fractional component is M, multiply it by 8 because the octal number system’s
base is 8; till the significant digits are required.
— Octal
0.356 x 8 = 12.848 2
0.848 x 8 = 6.784 6
0.784 x 8 = 6.272 6
0.272 x 8 = 2.176 2
0.176 x 8 = 1.408 1
0.408 x 8 = 3.264 3
Go through the steps given below to learn how to convert the numbers from decimal to hex.
Step 1: First, divide the decimal number by 16, considering the number as an integer.
Step 3: Again divide the quotient by 16 and repeat till you get the quotient value equal to zero.
Step 4: Now take the values of the remainder’s left in the reverse order to get the hexadecimal numbers.
Note: Remember, from 0 to 9, the numbers will be counted as the same in the decimal system. But from 10 to
15, they are expressed in alphabetical order such as A, B, C, D, E, F and so on.
Let us take an example to understand the steps given above for decimal to hex conversion.
Solution:
To convert decimal to hex, i.e. 960 base 10 to a hexadecimal number, follow the steps given below:
Step 4: Now taking the remainder in reverse order and substituting the equivalent hexadecimal value for
them, we get,
3→3, 12→C and 0→0
Let’s discuss the octal to binary conversion steps for the indirect method.
To convert octal to decimal, we multiply each digit by the power of 8 based on the position starting from the
right. We will multiply the first digit from the right by 80. Next, we will multiply the second digit by 81 and
so on.
For converting decimal to binary, we will divide the given number by 2 and record
the quotient and reminder. We will repeat the process until we obtain 0 as the quotient.
548=4×80+5×81
548=4×1+5×8
548=4+40
548=4410
44÷2 22 0
22÷2 11 0
11÷2 5 1
5÷2 2 1
2÷2 1 0
1÷2 0 1
On arranging all the remainders in the reverse order, we will obtain the following binary number:
Thus, 4410=1011002
There is no specific octal to binary formula for conversion. However, if you are looking for an easier and
less complicated octal to binary conversion method, the direct method involves the following steps:
In octal to binary conversion, each digit in the octal number has a three-digit binary representation. Using it,
we can easily convert a number from octal to binary. We can convert octal to binary by choosing the binary
equivalent of every digit of the octal number from the below-mentioned chart.
The following table includes the octal numbers 0 to 7 and their equivalent three-digit binary representation
to aid octal to binary conversion.
Octal Number Equivalent Three-digit Binary Representation
0 000
1 001
2 010
3 011
4 100
5 101
6 110
7 111
From the above chart, we will note down their binary equivalents.
5→101
4→100
Now, combining the two, we get the following binary number: 1011002.
Let’s understand the steps with the help of an example. We will also understand how the three-digit binary
representation is obtained for each octal digit.
Example: Convert 7658 to binary.
7 6 5
Step 2: Each octal digit represents 3 binary bits. Starting from right to left, the value of these three digits
is 20=1,21=2, and 22=4 respectively. Thus, write (4, 2, 1) below each octal digit.
7 6 5
4 2 1 4 2 1 4 2 1
Step 3: Identify the numbers among 4, 2, and 1 (powers of 2), which add up to the octal number written on
the top. Write 1 below if the number is used. Write 0 below the number that is not used in the sum. For
example, 7=4+2+1, so we write 1 under all the three numbers.
7 6 5
4 2 1 4 2 1 4 2 1
1 1 1 1 1 0 1 0 1
Step 4: Write the 1s and 0s from left to write to find the binary equivalent of the given octal number.
Thus, 7658=1111101012
Octal to decimal:
348=(3×81)+(4×80)
348=24+4
348=2810
Problem : 1
Solution:
Octal is first converted to binary before being converted to hexadecimal. Looking at the table of the octal to
binary conversion,
5 = 101
1 =000
(50)8=(101000)2
0010 = 2
1000 = 8
Problem : 2
Solution:
(56)8
= (101)(110)
=(101110)2
(101110)2(101110)2
= (10)(1110)
= (2)(14)
= (2e)16
Problem: 3
= 3×81+6×80+1×8−1+2×8−2+5×8−3
= (30.16601563)10(30.16601563)10
It is safe and wise to agree that number system holds its importance for everything which includes
proportion and percentage. Number system plays a crucial role, both in our everyday lives and the
technological world. With its myriad qualities, it simplifies our lives a lot, which has been discussed as
follows:
It enables to keep count of all the things around people. Like how many apples are in the
basket, or the number of milk cartons to be purchased, etc.
It enables the unique and accurate representation of different types of numbers.
Making a phone call is possible only because we have a proper and efficient number system.
Elevators used in public places also depend upon number systems for their functioning.
Computation of any kind of interest on amounts deposited in banks.
Creation of passwords on computers, security purposes.
Encrypting important data, by converting figures into another number system to avoid hacking
and misuse of data.
It enables easy conversion of numbers for technical purposes.
The entirety of computer architecture depends upon number systems (octal, hexadecimal).
Every fiber of data gets stored in the computer as a number.
Description of logic gates
Logic gates are an important concept if you are studying electronics. These are important digital devices
that are mainly based on the Boolean function. Logic gates are used to carry out logical operations on single
or multiple binary inputs and give one binary output. In simple terms, logic gates are the electronic circuits
in a digital system.
AND gate
In the AND gate, the output of an AND gate attains state 1 if and only if all the inputs are in state 1.
The Boolean expression of AND gate is Y = A.B
A B Y
0 0 0
0 1 0
1 0 0
1 1 1
NAND gate
This basic logic gate is the combination of AND and NOT gates.
A Y
0 1
1 0
OR gate
In an OR gate, the output of an OR gate attains state 1 if one or more inputs attain state 1.
The Boolean expression of the OR gate is Y = A + B, read as Y equals A ‘OR’ B.
A B Y
0 0 0
0 1 1
1 0 1
1 1 1
NOR gate
The NOR gate is a combination OR gate followed by an inverter. Its output is "true" if both inputs are
"false." Otherwise, the output is "false."
A B Y
0 0 0
0 1 1
1 0 1
1 1 1
XOR gate
In an XOR gate, the output of a two-input XOR gate attains state 1 if one adds only input and attains state 1.
0 0 0
0 1 1
1 0 1
1 1 0
In the XNOR gate, the output is in state 1 when both inputs are the same, that is, both 0 or both 1.
A B Y
0 0 1
0 1 0
1 0 0
1 1 1
The easiest way to learn the function of basic logic gates is explained below.
For AND Gate – If both the inputs are high then the output is also high
For OR Gate – If a minimum of one input is high then the output is High
For XOR Gate – If the minimum one input is high then only the output is high
NAND Gate – If the minimum one input is low then the output is high
NOR Gate – If both the inputs are low then the output is high.
According to the first theorem, the complement result of the AND operation is equal to the OR operation of
the complement of that variable. Thus, it is equivalent to the NAND function and is a negative-OR function
proving that (A.B)' = A'+B' and we can show this using the following table.
0 0 0 1 1 1 1
0 1 0 1 1 0 1
1 0 0 1 0 1 1
1 1 1 0 0 0 0
0 0 0 1 1 1 1
0 1 1 0 1 0 0
1 0 1 0 0 1 0
1 1 1 0 0 0 0
Let's take some examples in which we take some expressions and apply DeMorgan's theorems.
Example 1: (A.B.C)'
(A.B.C)'=A'+B'+C'
Example 2: (A+B+C)'
(A+B+C)'=A'.B'.C
Example 3: ((A+BC')'+D(E+F')')'
For applying the DeMorgan's theorem on this expression, we have to follow the following expressions:
1) In complete expression, first, we find those terms on which we can apply the DeMorgan's theorem and
treat each term as a single variable.
So,
2) Next, we apply DeMorgan's first theorem. So,
3) Next, we use rule number 9, i.e., (A=(A')') for canceling the double bars.
Now, this expression has no term in which we can apply any rule or theorem. So, this is the final expression.
Every Variable has a data type that tells what kind of data is being stored in a variable. There are two types
of data types in JavaScript.
Primitive data types: The predefined data types provided by JavaScript language are known as primitive
data types. Primitive data types are also known as in-built data types.
Below is a list of Primitive Data Types with proper descriptions and examples:
1. Number: Number data type in javascript can be used to hold decimal values as well as values without
decimals.
2. String: The string data type in javascript represents a sequence of characters that are surrounded by single
or double quotes.
3. Undefined: The meaning of undefined is ‘value is not assigned’.
4. Boolean: The boolean data type can accept only two values i.e. true and false.
5. Null: This data type can hold only one possible value that is null.
6. BigInt: This data type can represent numbers greater than 253-1 which helps to perform operations on
large numbers. The number is specified by writing ‘n’ at the end of the value
7. Symbol: This data type is used to create objects which will always be unique. these objects can be created
using Symbol constructor.
Non-primitive data types: The data types that are derived from primitive data types of the JavaScript
language are known as non-primitive data types. It is also known as derived data types or reference data
types.
Below is a list of Non-primitive Data Types with proper descriptions and examples:
1. Object: An object in Javascript is an entity having properties and methods. Everything is an object in
javascript.
2. Array: With the help of an array, we can store more than one element under a single name.
Primitive Non-Primitive
Primitive Data types are predefined. Non-Primitive data types are created by the programmer
Primitive Data types will have certain values. Non-Primitive data types can be NULL.
Examples are numbers and strings. Examples are Array and Linked List.
Application of datatypes
JavaScript is a dynamically typed language. It means that a variable doesn’t associate with a type. In other
words, a variable can hold a value of different types. For example:
To get the current type of the value that the variable stores, you use the typeof operator:
Output:
"number"
"boolean"
"string"
The undefined type is a primitive type that has only one value undefined. By default, when a variable is
declared but not initialized, it is assigned the value of undefined.
let counter;
[Link](counter); // undefined
[Link](typeof counter); // undefinedCode language: JavaScript (javascript)
In this example, the counter is a variable. Since counter hasn’t been initialized, it is assigned the value
undefined. The type of counter is also undefined.
It’s important to note that the typeof operator also returns undefined when you call it on a variable that
hasn’t been declared:
The null type is the second primitive data type that also has only one value null. For example:
JavaScript uses the number type to represent both integer and floating-point numbers.
The following statement declares a variable and initializes its value with an integer:
To represent a floating-point number, you include a decimal point followed by at least one number. For
example:
Note that JavaScript automatically converts a floating-point number into an integer number if the number
appears to be a whole number.
The reason is that Javascript always wants to use less memory since a floating-point value uses twice as
much memory as an integer value. For example:
To get the range of the number type, you use Number.MIN_VALUE and Number.MAX_VALUE. For
example:
[Link](Number.MAX_VALUE); // 1.7976931348623157e+308
[Link](Number.MIN_VALUE); // 5e-324Code language: JavaScript (javascript)
Also, you can use Infinity and -Infinity to represent the infinite number. For example:
NaN stands for Not a Number. It is a special numeric value that indicates an invalid number. For example,
the division of a string by a number returns NaN:.
[Link](NaN/2); // NaN
[Link](NaN == NaN); // falseCode language: JavaScript (javascript)
In JavaScript, a string is a sequence of zero or more characters. A string literal begins and ends with either a
single quote(') or a double quote (").
A string that begins with a double quote must end with a double quote. Likewise, a string that begins with a
single quote must also end with a single quote:
If you want to single quote or double quotes in a literal string, you need to use the backslash to escape it. For
example:
let message = 'I\'m also a valid string'; // use \ to escape the single quote (')Code language: JavaScript
(javascript)
JavaScript strings are immutable. This means that it cannot be modified once created. However, you can
create a new string from an existing string. For example:
In this example:
First, declare the str variable and initialize it to a string of 'JavaScript'.
Second, use the + operator to combine 'JavaScript' with ' String' to make its value as 'Javascript
String'.
Behind the scene, the JavaScript engine creates a new string that holds the new string 'JavaScript String' and
destroys the original strings 'JavaScript' and ' String'.
The following example attempts to change the first character of the string JavaScript:
let s = 'JavaScript';
s[0] = 'j';
[Link](s)Code language: JavaScript (javascript)
But not:
The boolean type has two literal values: true and false in lowercase. The following example declares two
variables that hold the boolean values.
JavaScript allows values of other types to be converted into boolean values of true or false.
What is an Operator?
In JavaScript, an operator is a special symbol used to perform operations on operands (values and
variables). For example, 2 + 3; // 5. Here + is an operator that performs addition, and 2 and 3 are
operands.
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ‘+’ is called
the operator. JavaScript supports the following types of operators.
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
Arithmetic Operators
1
+ (Addition)
2
- (Subtraction)
3
* (Multiplication)
4
/ (Division)
6
++ (Increment)
7
-- (Decrement)
Note − Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give "a10".
Example
<html>
<body>
[Link]("a + b = ");
result = a + b;
[Link](result);
[Link](linebreak);
[Link]("a - b = ");
result = a - b;
[Link](result);
[Link](linebreak);
[Link]("a / b = ");
result = a / b;
[Link](result);
[Link](linebreak);
[Link]("a % b = ");
result = a % b;
[Link](result);
[Link](linebreak);
[Link]("a + b + c = ");
result = a + b + c;
[Link](result);
[Link](linebreak);
a = ++a;
[Link]("++a = ");
result = ++a;
[Link](result);
[Link](linebreak);
b = --b;
[Link]("--b = ");
result = --b;
[Link](result);
[Link](linebreak);
//-->
</script>
Comparison Operators
1
= = (Equal)
Checks if the value of two operands are equal or not, if yes, then the condition
becomes true.
2
!= (Not Equal)
Checks if the value of two operands are equal or not, if the values are not equal,
then the condition becomes true.
Ex: (A != B) is true.
3
> (Greater than)
Checks if the value of the left operand is greater than the value of the right operand,
if yes, then the condition becomes true.
4
< (Less than)
Checks if the value of the left operand is less than the value of the right operand,
if yes, then the condition becomes true.
Checks if the value of the left operand is greater than or equal to the value of the
right operand, if yes, then the condition becomes true.
6
<= (Less than or Equal to)
Checks if the value of the left operand is less than or equal to the value of the right
operand, if yes, then the condition becomes true.
Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
[Link]("(a == b) => ");
result = (a == b);
[Link](result);
[Link](linebreak);
Logical Operators
1
&& (Logical AND)
If both the operands are non-zero, then the condition becomes true.
2
|| (Logical OR)
If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.
3
! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the Logical
NOT operator will make it false.
Example
Try the following code to learn how to implement Logical Operators in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var a = true;
var b = false;
var linebreak = "<br />";
Bitwise Operators
1
& (Bitwise AND)
Ex: (A & B) is 2.
2
| (BitWise OR)
Ex: (A | B) is 3.
3
^ (Bitwise XOR)
Ex: (A ^ B) is 1.
4
~ (Bitwise Not)
It is a unary operator and operates by reversing all the bits in the operand.
5
<< (Left Shift)
It moves all the bits in its first operand to the left by the number of places specified
in the second operand. New bits are filled with zeros. Shifting a value left by one
position is equivalent to multiplying it by 2, shifting two positions is equivalent to
multiplying by 4, and so on.
Ex: (A << 1) is 4.
6
>> (Right Shift)
Binary Right Shift Operator. The left operand’s value is moved right by the
number of bits specified by the right operand.
Ex: (A >> 1) is 1.
7
>>> (Right shift with Zero)
This operator is just like the >> operator, except that the bits shifted in on the left
are always zero.
Ex: (A >>> 1) is 1.
Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
var linebreak = "<br />";
Assignment Operators
1
= (Simple Assignment )
Assigns values from the right side operand to the left side operand
2
+= (Add and Assignment)
It adds the right operand to the left operand and assigns the result to the left
operand.
Ex: C += A is equivalent to C = C + A
3
−= (Subtract and Assignment)
It subtracts the right operand from the left operand and assigns the result to the left
operand.
Ex: C -= A is equivalent to C = C - A
4
*= (Multiply and Assignment)
It multiplies the right operand with the left operand and assigns the result to the
left operand.
Ex: C *= A is equivalent to C = C * A
5
/= (Divide and Assignment)
It divides the left operand with the right operand and assigns the result to the left
operand.
Ex: C /= A is equivalent to C = C / A
6
%= (Modules and Assignment)
It takes modulus using two operands and assigns the result to the left operand.
Ex: C %= A is equivalent to C = C % A
Note − Same logic applies to Bitwise operators so they will become like <<=, >>=, >>=, &=, |= and ^=.
Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = 33;
var b = 10;
var linebreak = "<br />";
Miscellaneous Operator
We will discuss two operators here that are quite useful in JavaScript: the conditional operator (? :) and
the typeof operator.
Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or false value and then executes one of the
two given statements depending upon the result of the evaluation.
1
? : (Conditional )
If Condition is true? Then value X : Otherwise value Y
Example
Try the following code to understand how the Conditional Operator works in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
typeof Operator
The typeof operator is a unary operator that is placed before its single operand, which can be of any type. Its
value is a string indicating the data type of the operand.
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number, string, or boolean
value and returns true or false based on the evaluation.
Number "number"
String "string"
Boolean "boolean"
Object "object"
Function "function"
Undefined "undefined"
Null "object"
Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = "String";
var linebreak = "<br />";
Input
Tasks to be preformed
Output expected
1. Sorting algorithms
Javascript provides a rich set of data types and operators that can be used to implement various sorting
algorithms such as bubble sort, insertion sort and quick sort.
These algorithms are useful in many applications because they can be used to sort data of different sizes and
types.
they are:-
(i) Bubble sort: An uncomplicated sorting algorithm that compares nearby components repeatedly and
switches them out if they are out of order.
(ii) Insertion sort: a method of sorting that creates a sorted list one individual element at a time by placing
each one in the appropriate spot.
1. Initialize an empty sorted list and an unsorted list of the elements to be sorted.
2. The first member from the unsorted list should be taken and placed in the appropriate position in the
sorted list.
3. Repeat step 2 for each subsequent element in the unsorted list.
4. Compare the current element with the elements in the sorted list, starting with the element immediately
to the left.
5. Swap the two elements if the current element is smaller than the element to its left.
6. If the current element is larger than the element to its left, insert it at its correct position in the sorted
list.
7. Repeat steps 4-6 for each subsequent element in the unsorted list.
8. Once all elements have been processed, the sorted list will contain all elements in the correct order.
9. The sorting process is complete.
(iii) Selection sort: a method of sorting that consistently starts the sorted listing with the smallest detail from
the unordered listing.
(iv) Quick sort: A divide-and-conquer sorting algorithm that chooses a pivot element and splits the list into
sublists depending on whether the elements are fewer than or more than the pivot. After that, the sublists are
sorted repeatedly until the full list is sorted.
1. Choose a pivot element from the list. This is typically the first element, but it can also be a random
element or the median of the list.
2. Divide the list into two sublists: one containing elements less than the pivot and one containing
elements greater than the pivot.
3. Recursively sort the sublist containing elements less than the pivot using the same process.
4. Use the same procedure to recursively sort the sublist of entries larger than the pivot.
5. Concatenate the sorted sublists with the pivot element in between to form a fully sorted list.
6. Return the fully sorted list.
(v) Merge sort: The divide-and-conquer sort algorithm divides the list into two halves, sorts each half, and
then merges the two halves in sorted order.
Merge-sort Algorithm:
1. Make two sublists out of the list: one with elements below the pivot and one with elements above the
pivot.
2. Produces a new sorted sublist by iteratively merging sublists until only one sublist exists. This will be
your sorted list.
3. Steps to merge two sub-directories:-
4. Create an empty list to hold the sorted elements.
5. Compares the first element of each sublist.
6. Adds the smaller element to the new list and removes it from the parent sublist.
7. Repeat the steps 2 and 3 until a list is completly empty.
8. Adds the remaining elements from other sublists to a new list.
9. Replaces the merged sublist with the new sorted list.
10. Repeat this process until all sublists are merged into one sorted list.
(vi) Heapsort: A sorting algorithm that sorts elements using a data structure called heap.
1. Build max heap: Starting with the first non-leaf node, compare each node with its child nodes and
replace the nodes with the largest of its children to satisfy the max heap property.
2. Swap root with last element: Swap the root (largest element) with the last element in the stack.
3. Stack the rest of the elements. Starting from the root, each node is compared with its children, swapping
nodes with their older children until the max heap property is satisfied.
4. Repeat steps 2 and 3 with the newly stacked elements, except for the last element in the correct
position.
5. Repeat this process until only one element remains in the stack. This is now sorted.
6. Heapify Down: Starting from the root node, it compares elements with its children and swaps with
the larger of the two until the max heap property is satisfied.
7. Heapify Up: Start with the last element in the heap, compare it to its parent, and swap it with the parent
to satisfy the max heap property.
(vii) Radix sort: A sorting algorithm that sorts elements based on the digits or digits of their binary
representation.
1. determine how many digits are contained in the input listing's largest element.
2. Initialize a variable, say digit place, to 1, which represents the current digit place.
3. Create an empty list for each possible digit value from 0 to 9.
4. Iterate through the input list and add each element to the appropriate list based on the value of the
current digit place.
5. Concatenate all the lists together to form the new list in the order of the digit lists.
6. Multiply digitPlace by 10 to move to the next digit place.
7. Repeat steps 4-6 for each digit place until all digits in the largest element have been considered.
8. The final list will be sorted in ascending order by the digits of the elements.
9. Return the final sorted list.
2. Searching algorithms
C also provides the tools necessary to implement a variety of searching algorithms, such as linear search and
binary search. These algorithms can quickly find specific items in a data set, making them useful for a wide
range of applications.
They are:-
(i) Linear search: A basic search algorithm that examines each item in the listing one by one until it finds the
desired item.
1. Define the input for the algorithm: The input for a linear search algorithm is a list of elements (or an
array) and a target element we are searching for.
2. Initialize a variable called "index" to -1: This variable will be used to store the index of the target
element if it is found.
3. Loop through the list of elements: Starting from the first element, check each element in the list one
by one.
4. Compare the present element to the desired element for evaluation: Keep the index of the current
element in the index variable and exit the loop if the modern element and the goal element are identical.
5. Return the index of the target element: After the loop completes, return the value stored in the index
variable. If the target element is not found, the value of the index will be -1
(ii) Binary search: A search algorithm that operates by splitting the listing into halves and searches within of
those halves is more likely to include the element.
(iii) Depth-first search: A search algorithm that examines each branch as far as is feasible before turning
around.
(iv) Breadth-first search: A search algorithm that explores all the neighbors of a node before moving to the
next level.
(v) Interpolation Search: A search algorithm that uses the values of the searched elements to estimate the
position in the index.
It works as expected.
The algorithm can be summarized as follows.
(vi) Jump search: A search method that iterates over the list in constant-length steps until it finds the relevant
element or determines that it is no longer present.
1. First, set the jump size to the square root of the number of array elements.
2. Sets a variable named "current" to the first element of the array.
3. Iterates over the array by jumping by jump size while incrementing a variable called "jump".
4. Move on to the following leap if the existing element is smaller than the desired element.
5. If the current element is larger than the target element, perform a linear search between the current
element and the previous jump element to find the target element.
6. If the target element is not found in the array, it returns -1 to indicate that it is not in the array.
7. If the element is found, it returns the element's index in the array.
3. Graph algorithms
C's support for pointers and data structures such as arrays and linked lists makes it suitable for implementing
algorithms that manipulate graphs, such as finding the shortest path between two nodes in a graph.
they are:-
1. Dijkstra's Algorithm: An algorithm that finds the shortest path between two nodes in a graph by
continuously updating the shortest distance from each node.
2. Algorithm A*: A method that continually updates the shortest course to each node in a graph to
determine the shortest route between them.
3. Prim's Algorithm: An approach for figuring out the weighted connected graph's smallest spanning
tree.
4. Kruskal's algorithm: An approach to identify the linked weighted graph's lowest spanning tree.
5. Bellman-Ford Algorithm: An algorithm that, even when the graph has negative edge weights,
displays the shortest path between a particular supply node and every other node in the network.
4. Cryptographic Algorithms
C supports low-level operations and efficient data manipulation, making it ideal for implementing algorithms
used in cryptography, such as data encryption and decryption algorithms.
They are:-
1. Hash Algorithms: These algorithms produce fixed-size outputs (hash) from arbitrary-sized inputs.
Examples include MD5, SHA-1 and SHA-2.
2. Symmetric key algorithms: The encryption and decryption steps in such algorithms employ the same
private key. AES, DES, and Blowfish are a few examples.
3. Asymmetric key algorithms: A public key and a non-public key are used by those methods as separate
keys for encryption and decryption. Some examples include RSA, ECC, and DSA.
4. Key exchange algorithms: These algorithms allow two parties to exchange keys over an insecure
channel securely. For example, we can mention Diffie-Hellman and Elliptic Curve Diffie-Hellman.
Efficiency: A good algorithm should perform its task quickly and use minimal resources.
Correctness: It must produce the correct and accurate output for all valid inputs.
Clarity: The algorithm should be easy to understand and comprehend, making it maintainable and
modifiable.
Scalability: It should handle larger data sets and problem sizes without a significant decrease in
performance.
Reliability: The algorithm should consistently deliver correct results under different conditions and
environments.
Optimality: Striving for the most efficient solution within the given problem constraints.
Robustness: Capable of handling unexpected inputs or errors gracefully without crashing.
Adaptability: Ideally, it can be applied to a range of related problems with minimal adjustments.
Simplicity: Keeping the algorithm as simple as possible while meeting its requirements, avoiding
unnecessary complexity.
Structured English is the use of the English language with the syntax of structured programming to
communicate the design of a computer program to non-technical users by breaking it down into logical steps
using straightforward English words. Structured English gives aims to get the benefits of both the
programming logic and natural language: program logic helps to attain precision, whilst natural language
helps with the familiarity of the spoken word.
Structured English
Structure English is derived from structured programming language which gives more understandable and
precise description of process. It is based on procedural logic that uses construction and imperative
sentences designed to perform operation for action.
It is best used when sequences and loops in a program must be considered and the problem needs
sequences of actions with decisions.
It does not have strict syntax rule. It expresses all logic in terms of sequential decision structures and
iterations.
Following are the algorithm of the sum and the average of three numbers is given below.
Explanation:
Step 1: Start
Step 2: Read the three number suppose "a","b","c" form the user.
Step 4 : sum=a+b+c;
Step 5: Avg=sum/3
Step 7: End.
The idea is to use the compound expression where each number is compared with the other two to find out
which one is the maximum of them.
Algorithm
a. IF-THEN-ELSE CONDITIONALS
One of the first things that programmers learn is how to use IF-THEN-ELSE statements. Every
programming language has some version of these. The syntax and exact usage may be different but
they all accomplish the same thing, which is to allow for program execution based on conditionals.
The basic flow is: If some condition is true then do this, otherwise do that.
Complex conditional statements can have more than just two choices. As humans, the way we make
decisions when we have several options to choose from is very different than computers. We are able
to select one item out of a group of choices, however a computer program must proceed by making
binary decisions, meaning that it can only select between two things at a time. Even the most complex
conditional statements boil down to a series of binary choices.
The switch statement is used to allow you to perform different actions based
on different conditions. In some languages this was a common structure for
conditional execution that makes it easier for a program to execute one of
several cases depending on the value of the expression at the switch.
Pseudocode is an informal way of programming description that does not require any strict programming
language syntax or underlying technology considerations. It is used for creating an outline or a rough draft
of a program. Pseudocode summarizes a program’s flow, but excludes underlying details.
• Variables:
• Assignment:
• Input/output:
• Selection:
• Repetition:
Advantages of pseudocode –
Examples
1: Write pseudo code that reads two numbers and multiplies them together and print out their product.
2: Write pseudo code that tells a user that the number they entered is not a 5 or a 6.
3: Write pseudo code that performs the following: Ask a user to enter a number. If the number is between 0
and 10, write the word blue. If the number is between 10 and 20, write the word red. if the number is
between 20 and 30, write the word green. If it is any other number, write that it is not a correct color option.
4: Write pseudo code to print all multiples of 5 between 1 and 100 (including both 1 and 100).
5: Write pseudo code that will count all the even numbers up to a user defined stopping point.
c) Find the smallest (minimum) and largest (maximum) of the five entered numbers.
d) Write out the results found from steps b and c with a message describing what they are.
Homework
1: Write pseudo code that reads in three numbers and writes them all in sorted order.
2: Write pseudo code that will calculate a running sum. A user will enter numbers that will be added to the
sum and when a negative number is encountered, stop adding numbers and write out the final result.
Design of Flowchart
It is a graphical representation of a computer program in relation to its sequence of functions (as distinct
from the data it processes).
When to Use a Flowchart
Materials needed: Sticky notes or cards, a large piece of flipchart paper or newsprint, and marking pens.
1. Define the process to be diagrammed. Write its title at the top of the work surface.
2. Discuss and decide on the boundaries of your process: Where or when does the process start? Where
or when does it end? Discuss and decide on the level of detail to be included in the diagram.
3. Brainstorm the activities that take place. Write each on a card or sticky note.
4. Arrange the activities in proper sequence.
5. When all activities are included and everyone agrees that the sequence is correct, draw arrows to
show the flow of the process.
6. Review the flowchart with others involved in the process (workers, supervisors, suppliers,
customers) to see if they agree that the process is drawn accurately.
Flowchart Symbols
Here is a chart for some of the common symbols used in drawing flowcharts.
Flowchart can have only one start and one stop symbol
On-page connectors are referenced using numbers
Off-page connectors are referenced using alphabets
General flow of processes is top to bottom or left to right
Arrows should not cross each other
Example Flowcharts
[Link]
[Link]
Learning outcome 2: Apply Data Structure
Identification of data structure concepts