0% found this document useful (0 votes)
3 views

4 Computational Thinking Latest

The document outlines the principles of computational thinking, emphasizing problem identification, development, selection, and implementation, while highlighting the importance of algorithms and flowcharts in problem-solving. It discusses the need for preconditions and postconditions, exception handling, and the benefits of concurrent processing in software development. Additionally, it covers abstraction in programming, particularly in object-oriented programming, to enhance efficiency and reduce complexity.

Uploaded by

manitkhurana1105
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

4 Computational Thinking Latest

The document outlines the principles of computational thinking, emphasizing problem identification, development, selection, and implementation, while highlighting the importance of algorithms and flowcharts in problem-solving. It discusses the need for preconditions and postconditions, exception handling, and the benefits of concurrent processing in software development. Additionally, it covers abstraction in programming, particularly in object-oriented programming, to enhance efficiency and reduce complexity.

Uploaded by

manitkhurana1105
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 131

Computational

Thinking
The concept of a Problem
• Identification
• Identify the problem
• Understand the problem
• Formulate the problem
• Development
• Explore various alternatives
• Selection
• Choose the best alternative
• Implementation
• Implement the selected solution
• Problem solving is not linear. Sometimes it is necessary to return to a previous stage.
• Computers can only solve problems that are solvable by humans, but also that computers can’t solve
some problems that are solvable by humans. (CAPTCHA – program used to prevent bots or automated
software from distorting online polls, registering etc)
• Some problems need human intelligence, human logic, human perception and human intuition.
• Only Advanced Artificial Intelligence programs can come close to imitating human performance in
these areas.
Algorithm
• A series of unambiguous instructions designed in order to solve a problem and achieve
a goal in a finite number of steps.
• Properties of Algorithm
• Finiteness – Finite number of steps, it should end
• Definiteness – Each step precisely defined
• Input -
• Output -
• Effectiveness –
• Simpler problem  Simpler Algorithm
• Complex problem  bigger & more complicated algorithm
• Writing an algorithm is in essence just problem solving
• Representations
• Simple English
• Flow chart
• Pseudocode
• Programming language
Flowcharts
• Diagrammatically describes an algorithm
Pseudocode
• Steps of an algorithm written in a particular notation
• Does not have a strict syntax
• Should be converted to equivalent High level language statements
Thinking Procedurally
Procedure appropriate to solving a
problem
• When a particular problem has to be solved, an effective method or
procedure should be identified.
• This procedure reduces the solution to a series of simple steps.
• These steps have to be followed in the correct order to obtain the
desired output.
Order of activities and required
outcome
• A company wishes to develop a new information system.
• The analysis phase will be the one that the company should complete
before proceeding to the next stages of the project.
• If the company tries to implement the new system without first
analyzing the problem domain, then a total waste of money, effort
and resources will almost certainly occur.
The role of sub-procedures in
solving a problem
• Breaking up the problem into smaller sub-problems.
• This method is very effective and efficient because it is much easier to attack a number of sub-problems instead of a
big complex problem.
• The resulting sub-problems can be further divided to smaller and smaller sub-problems until finally they can be dealt
individually.
• This strategy is often called top—down design or stepwise refinement.
• The very same approach could be used when developing complex computer programs.
• Using top-down program design, the complex problem is decomposed and for each sub-problem, an appropriate sub-
procedure is developed.
• A sub—procedure contains a series of commands that perform a task.
• When a sub procedure is called, all statements included in the particular sub-procedure are executed.
• All the sub-procedures that represent different parts of the problem solution can be used at the right time using their
identifiers.
• So the procedure is divided into a series of sub—procedures; this process is referred as a modular programming
approach.
• An identifier is the name that is used by the programmer to uniquely identify a variable, an object a sub-procedure etc.
Sub-Procedures
Thinking Logically
Decision-making in a specified
situation
• The addition process does not require any decision to be taken.
• The following algorithm is straight forward:
Input A
Input B
C=A+B
Output C
• Some problems require the use of decisions.
Decisions required for the solution
to a specified problem
Input A Input B Output Input A
Input B
Off Off Off
If A = 1 or B = 1 then
Off On On
Output 1
On Off On Else
On On On Output 0
End if

Input A Input B Output Input A


Off Off Off Input B
Off On Off If A = 1 and B = 1 then
Output 1
On Off Off
Else
On On On
Output 0
End if
multiple ifs and if-else if-else
A = input("Type a number")
A = input("Type a number") if A=0 then
if A=0 then output "1"
output "1" End if
else if A+2 > 6 then if A+2 > 6 then
output "2" output "2“
else end if
if NOT (A+2>6) AND NOT (A=0) then
output "3"
output "3"
end if
end if
Iteration associated with a given
decision in a specified problem
• Iteration is the process of repeating a series of instructions depending
upon a condition.
Loops
LOOP WHILE LOOP FROM TO
//use of while loop //use of from to loop
//to print a message //to print a message
//user selects the number of times //user selects the number of times
I=0 I =0
X = input("How many times do you want to see the X = input ("How many times do you want to see the
message") message")
loop while I < X loop I from 1 to X
I=I+1 output (“Hello")
output (“Hello") end loop
end while
X = input ("Please enter a number") x = input ("Please enter a number“)
if x > 0 then if X > 0 then
output "Positive" output "Positive"
end if
else if x = 0 then
if X = 0 then
output "0"
output "0"
end if else
if x < 0 then output "Negative"
output "Negative" end if
end if
x = input ("Please enter a number“)
X = input ("Please enter a number")
if x > 40 then if x > 40 then
output x + 40 output x + 40
end if Else if X > 30 then
if X > 30 then
output x + 30
output x + 30
end if
Else if x > 20 then
if x > 20 then output x + 20
output x + 20 end if
end if

Assume X = 45, 35, 25, 15


Assume X = 45, 35, 25, 15
What will be the output?
Thinking ahead
Inputs and outputs required in a
solution
• Calculate the wages earned by a daily worker at the end of the day
• Inputs
• Hours Worked
• Wages per Hour
• Output
• Total wages
• Calculate the wages earned by a daily worker at the end of the week
• Inputs
• Hours worked for each day
• Wages per Hour
• Output
• Total wages
Pre-planning in a suggested problem
and solution
• Example
• Prefetching in broad terms means getting data or instructions from memory into
the cache before they are actually needed.
• When a program requests data that was previously prefetched, it can use the
prefetched data and continue with execution, instead of waiting for the data
from RAM.
• preplanning an action so as to save time and improve efficiency.
• Another example of effective preplanning is the use of software libraries.
• These consist of pre— formed elements and are ready for future use.
• A software library consists of pre-written code, classes, procedures, methods
etc. that a programmer can use to add more functionality to his/her programs,
Pre-planning in a suggested problem
and solution
• A Gantt chart is a type of bar chart, named after Henry Gantt.
• It is widely used for project schedule and project management, as a way of
showing activities, tasks and events against time.
• On the left of the chart is a list of the tasks, activities and events.
• Along the top is an appropriate time scale. All tasks, activities and events are
represented by bars.
• Each bar represents the duration, start day and end day of the task, activity or
event.
• A Gantt chart allows easy inspection of the project’s activities, overlapping
activities, the total duration of the project etc.
• This chart provides details such as:
• the project includes 8 activities
• Site work should take place before plumbing and electrical tasks.
• Plumbing and electrical are carried out concurrently (that means to do both
tasks at the same time).
• Site work and plumbing are carried out sequentially.
• This chart provides details such as:
• the project consists of four activities.
• Task 1 and Task 2 are carried out sequentially (the second task cannot begin
before the other is completed).
• The total duration of the project is 21 days.
• Task 2 is the longest task.
Need for pre-conditions & post-
conditions
• Precondition
• what must be true before the program or sub-procedure is called
• Starting state before execution
• Postcondition
• what will be true after the program or sub-procedure is executed
• Final state after execution
• Example
• Files / Database / Libraries to be present in the required path
• Database updated with the correct values
• Files updated if required
• Preconditions and Postconditions are different from input and output
• Input to be in the given format – is a precondition
• Output to be in the required format – is a post condition
Exceptions that need to be
considered
• Exception is an act or event that disrupts the anticipated flow of the program’s execution.
• The exceptions take place during the execution of the program and can be effectively handled by specific
mechanisms that most modern programming languages provide.

• Error is an expected situation in your program.


• For example, Consider a situation where you specified a divided by zero in your program logic, and the
program throws an error.

• Where as exception is a runtime error that might occur during the execution of your program.

• For example you are trying to login into your application and application throws an error for database
connectivity lost or something like Connection closed or license expired.
• These are exceptions which are unpredictable errors during runtime.

• Error handling is to put your logic to handle an expected error in your program, and Exception handling is to
handle an unexpected error thrown by application /program at runtime.
• A company has the following policy to calculate the end—of—year
bonus for its employees:
• If the employee has worked for the company for 9 months or more,
then the bonus equals to 30% of his/her monthly salary.
• If the employee has worked for the company for less than 9 months
and his/her salary is less than €2000 then the bonus equals to 20% of
his/her monthly salary.
• If the employee has worked for the company for less than 9 months
and his/her salary is equal or more than €2000 then the bonus equals
10% of his/her monthly salary.
MONTHS =0
SALARY =0
BONUS = 0
TOTAL = 0
SALARY = input("what is the salary of the employee?")
MONTHS = input(“How many months did he/she work?")
if MONTHS >= 9 then
BONUS = (30/100)*(SALARY)
TOTAL = BONUS +(SALARY * MONTHS)
else if MONTHS < 9 AND SALARY < 2000 then
BONUS = (20/100)*(SALARY)
TOTAL = BONUS+(SALARY * MONTHS)
else if MONTHS < 9 AND SALARY >= 2000 then
BONUS = (10/100)*(SALARY)
TOTAL = BONUS+(SALARY * MONTHS)
end if
output "TOTAL IS:" , TOTAL ,"Euros"
output "BONUS IS:" , BONUS ,"Euros"
Thinking concurrently
Parts of a solution that could be implemented
concurrently
• Concurrent means something that happens at the same time as something
else.
• In computer science, concurrent processing means the execution of different
instructions simultaneously by multiple processors so as to achieve the best
performance.
• A simplified explanation of this process is that programs are broken down
into procedures and procedures are broken down to sub-procedures.
• These are then assigned to separate processing units to perform
simultaneously.
• Sequential processing is the execution of all sub—procedures one after the
other by a single processor.
Decision to use concurrent
processing in solving a problem
• Concurrent processing requires better planning and coordination of resources.
• Without this, concurrent processing may cause serious problems and the decision to use serial or
concurrent processing in solving a problem should be carefully examined.
• For example, an accountant is making changes to an electronic financial database.
• As he is doing so, a second accountant opens the same database which includes all the
modifications made so far by the first accountant, and uses it to retrieve information.
• The first accountant then decides the changes made so far are invalid and brings the database
records to the previous condition.
• The first accountant saves the database.
• The information retrieved by the second accountant no longer exists, but the second accountant is
not aware of this crucial information.
• This problem could have been avoided if no one could read the altered database until the first
accountant decided that the edits and amendments were final
Evaluate the use of designing and developing
different parts of software products concurrently.
• different stages of programming run simultaneously (rather than
consecutively)
• decreases product development time
• improves productivity
• reduces costs
• requires more resources & more software developers
Thinking abstractly
Examples of abstraction
• Abstract thinking means reflecting on events, ideas, attributes and relationships in a general
manner that hides all unnecessary details of specific objects.
• All information, that is not necessary to accomplish a goal, is removed and ignored and a
generalization technique is implemented.
• The explanation of the various components of the motherboard requires the use of abstraction.
• Although the RAM and the CPU are considered as fundamental physical parts, it is known that
they are abstractions of gates and integrated circuits which contain millions of transistors.
• Decades ago, a programmer had to work with the low-level circuitry instructions of the CPU and
the computer used.
• Nowadays, high-level programming languages allow the user to use English like commands and
syntax in which one command statement corresponds to many machine instructions.
• In Java computer language, System.out.println displays a message on the screen.
• The user is not required to understand the function of the monitor and the various procedures,
interfaces, graphic card drivers and libraries used to create the corresponding pixels on the screen.
Why abstraction is necessary?
• Abstraction allows us to create a general idea of what the problem is and how to
solve it
• Abstraction removes all specific detail, and any patterns that will not help in solving
a problem.
• This helps in forming a “model” (If designers don’t abstract they may end upwith
the wrong solution to the problem they are trying to solve)
• Abstraction is widely used because there exist a number of “patterns” in
programming that keeps repeating in every application/program
• The pattern corresponding to an issue can be found, then the abstract solution to it
can be found and implemented, and the problem is solved
• Most programming languages provide some built-in abstract patterns, which are
easy to use (some API provides more advanced patterns)
Virtual machine and abstraction
• Virtual machines provide a software emulation/virtualization of other
operating systems;
• While hiding/abstracting the physical environment/OS/execution
environment of the host machine;
• Virtual machines do not directly correspond to any real platform so
software may be tested/executed on any platform (portability);
• This is more practical/economical than having to test software on
several computers with different OS;
• The software to be tested is compiled into the language of the virtual
machine, and this is interpreted into the language of the host machine;
Abstraction and computational
solutions for a specified situation
Object-oriented Programming
• Abstraction is the process of taking away or removing characteristics from something in order to reduce it
to a set of essential characteristics
• In object-oriented programming, abstraction is one of three central principles (along with encapsulation
and inheritance);
• Through the process of abstraction, a programmer hides all but the relevant data about an object in order
to reduce complexity and increase efficiency;
• The resulting object itself can be referred to as an abstraction, meaning a named entity made up of
selected attributes and behavior specific to a particular usage of the originating entity.
• Abstraction is related to both encapsulation and data hiding;
• Object-oriented programming uses programming objects that describe data (properties) and behavior
(methods) of real objects, and facilitates code reusability and abstraction.
• It makes complex software faster and easier to develop, and facilitates maintenance.
• It is an evolution of procedural (structural) programming, which uses procedures that are able to interact
and exchange data as building blocks of programs.
Object car1 Object car2
Data: Data:
integer speed = 0; String Colour = Black
String Equipment = Silver
integer gear = 1;
String Availability = True
Methods :
Integer Manufacturerstock = 0
changeGear Methods:
Accelerate changeColour
Brake changeEquipment
• The role of abstraction is profound; Availability
• the first object (car1) could be used in a program that simulates the driving experience of such a car,
• while the second (car2) could be used in a program suitable for sales purposes.
• In each case, the programmer hides the unnecessary details and concentrates only on properties and
behaviors that are important to the particular implementation.
• An object hides the details; Yet preserves the functionality;
• Objects combine abstractions of data and code; While hiding away implementation of details;
• Suppose a salesman uses a program that facilitates his/her job.
• When a customer chooses a car and finalizes the deal, a new object is
created.
• Each deal has some unique attributes.
• The salesman deals with a collection of items (cars).
• This collection is organized in a particular way to represent the sale of
cars.
• Some common operators could be applied to all items in the
collection (add a car, read details of a car etc.).
• So a collection is a data structure that consists of the data and the
predefined methods which operate on the data.
• A collection is an abstract data type like queues and stacks.
• An Abstract Data Type, or ADT, is a group of operations and data.
• In object oriented languages, a collection is an object that assembles
and contains a lot of elements in a single structure.
• A collection is used to add, store, manage, retrieve, manipulate and
communicate the data using predefined methods.
Modelling and simulation
• Mathematical modelling refers to a process where a system is understood well
enough and scientists describe it using mathematical language.
• A set of mathematical rules is used to describe the function of the particular system.
• It is clear that the mathematical model is an abstraction of the real system.
• A mathematical model contains only the necessary details, rules and objects for
studying the real system or an aspect of it.
• A mathematical model could be transformed into an algorithm and then to a
program that replicates the behavior of a real system.
• A computer simulation runs on a computer and reproduces the behavior of a real
system.
• The simulation uses an abstract mathematical model that is expressed as a computer
model (computer program) to simulate the system.
• A computer simulation is always based on a computer model.
Abstraction from a specified
situation
• A modular program is easier to understand and facilitate the use of abstraction.
• The programmer is able to focus on the important things and ignore all
unnecessary details.
• Procedures and sub-procedures facilitate abstraction.
• For example, the following program can call a sub—procedure named
computeSomething().
• When this sub-procedure is called from the main program, it executes a
sequence of instructions and returns a value.
• The programmer does not need to know the inner details of this sub-procedure,
they only need to know the name, parameters and the return data type.
• So: modularization facilitates abstraction.
• A sub-program is a named section of code that performs a specific
task (in a program) / can be called by name / referred by the identifier
when needed;
• without knowing the details (of code and data structures) as these are
wrapped / hidden within the sub-program;
Real-world and abstraction
• A thematic map is an abstraction of reality that shows the spatial
distribution and emphasizes a particular theme, such as the average
distribution of income in a specific geographic area.
• Topographic maps show abstractions of selected physical features of
the three—dimensional real world at a reduced scale in two-
dimensions, paper or a screen.
• Political maps are designed to show on data such as the boundaries
of countries and states and the location of major cities.
• These maps are an abstraction of political territory.
• In these cases, various levels of abstraction occur.
Read the algorithm and state the
sequence of numbers that it
produces.
• (b) Draw a flowchart for an algorithm that ADDS UP the following
numbers and outputs the total.
• 2 + 4 + 8 + 16 + 32 + 64 + …. + 65536
• An array, numbers[], has
been declared and contains
the following values.
• 49 11 16 72 2 37 14 26
• Consider the following
code fragment.
• All variables have been
declared.
• (a) By using a trace table, determine the values of h and l after the c
loop has been completed (for all values of c) for the first time.
• (b) Deduce the purpose of this loop.
• (c) Copy and complete the following trace table for the whole
algorithm.
i j l h Numbers[]

• (d) State the purpose of the algorithm


Variable, constant, operator, object
• Variable:
• A named memory location
• which can store a value
• of specified datatype
• The stored value can be changed during the program execution.
• A variable has a name (or identifier) and a datatype.
• The name of the variable should not clash with reserved keywords and
literals of the language.
• It is highly recommended to use meaningful variable names (e.g. roomsize).
• The type of the variable could be an integer, double, string etc.
Variable, constant, operator, object
• Constants represent values that don’t change during the program execution.
• They can also be seen as non-modifiable variables.
• e.g. in Java: final double PI = 3 . 14159.
• Size of the array can be constant
• const int MAX = 30;
• int[] arr = new int[MAX]
• for (int i = 0 ; i < MAX; i++) // MAX can be used in all processing loops for the array now
• Later when you want to change array size as 50, only the first statement const int MAX = 50;
needs to be changed.
• Operator: Operators are used to manipulate operands.
• The expression 2+3 has as an operator the ”+" (sign of addition) and two operands ”2”, ”3”.
• Operands can be variables, literals, boolean values, numerical values, text etc.
Variable, constant, operator, object
• Object: An object is comprised of data and actions.
• Actions refer to the operations that can be performed by the object.
• Object data may include a number of data members, while actions
may also be referred to as methods.
• Data members are used to store the current state of an object and
methods are used to change or access or process those data
members.
The concept of Object
• Data members (variables)
• Member methods (functions / subroutines)
Name Grade Bus Route Address
• Object is like a record in a table
Ajay 11 6 Vignan Nagar

• Student object S Vikram 11 7 Indira Nagar


• Name
• Grade
• Bus Route
• Address
• calculateGrade()
• resetAddress()

• Calling the members using dot operator


• S.calculateGrade()

• Assume S1 is a student object, S2 is another student object.


• These two objects will be stored in separate memory locations.
• S1 will have its own name, grade, bus route etc. The methods will act on the S1 data.
Define various operators
• = Defined as ”is equals to”.
• It is also used to assign a value to a variable.
• Min=6 means that the value of 6 is assigned to variable Min
• ≠ or <> Defined as ”not equal to”.
• Min≠Max means that Min is not equal to Max
• > Defined as "is greater than"
• >= Defined as ”is greater than or equal to”
• < Defined as ”is less than"
• <= Defined as "is less than or equal to”
• Div defined as the integer part of the quotient, 22 div 3 = 7
• Mod defined as modulo operation. It gives the remainder of the division
operation. 22 mod 3 = 1
Local and global value
• The scope of a variable defines the visibility of that variable.
• It defines which parts of the algorithm can store, access and retrieve
the data of the variable.
• Sometimes it is very useful to limit the scope of a variable.
• A global variable is visible to all parts of your program while a local
variable has a limited scope (e.g within a code block, within a
method)
Algorithm planning and design
• Representation using pseudo code
• Assignment statements
• TOTAL=0
• set TOTAL to 0
• TOTAL= TOTAL+NUMBER
• TOTAL TOTAL+NUMBER
• increment TOTAL by 1
Algorithm planning and design
• Representation using pseudo code
• Arithmetic operators
• +, - , * , / , ^, mod
• Comparison operators
• =, <>, <, >, <=, >=,
• Looping instructions
• loop while ….. end loop
• loop while (X<M)
• SUM= SUM+X
• print SUM
• end loop
• Check first and then execute
• If the condition is not satisfied, control goes to the next
instruction after end loop.
Algorithm planning and design
• Representation using pseudo code
• Looping instructions
• loop from to………end loop
• loop COUNT from 1 to 10
• <Set of instructions>
• end loop
Algorithm planning and design
• Representation using pseudo code
• Decision making
• if <Condition> then
• <Set of instructions>
• else
• <Set of instructions>
• end if
• Nested loops are also possible.
• A town contains 5000 houses. Each house owner must pay tax based
on the value of the house. Houses over $200 000 pay 2% of their
value in tax, houses over $100 000 pay 1.5% of their value in tax and
houses over $50 000 pay 1% of their value in tax. All others pay no
tax. Write an algorithm to show the actual tax amount in the form of
a flowchart and pseudo code.
• Write an algorithm in the form of a flowchart which takes
temperatures input over a 100 day period (once per day) and outputs
the number of days when the temperature was below 20C and the
number of days when the temperature was 20C and above.
Speed cameras read the time a vehicle passes the point A on the road and the time the
vehicle passes another point B on the same road. The distance between A and B is 100
metres. The speed of the vehicle is calculated by using the following formula
Speed in metres/sec = 100/(Time at point B- Time at point A)
The maximum allowed speed is 100 kilometres per hour. 500 vehicles were monitored
over 1 hour period.
Write an algorithm using pseudo code which
Inputs the start time and end time for each of the 500 vehicles
Calculate the speed for each vehicle using the formula above
Outputs the speed for each vehicle and a message if the speed exceeds 100 km per hour.
Output the highest speed of all the 500 vehicles monitored.
All inputs should have validation checks built in
• A real estate agent is computerising his operations. He receives large number of enquiries
in a day which remain active for a period of 30 days. You have to develop an algorithm in
the form of pseudocode to achieve the following.
• The program should input
• The no of enquiries received in each day for 30 days
• Value for each enquiry
• The program should output
• Total value of enquiries for each day
• Highest value for a single enquiry for 30 days
• Lowest value for a single enquiry for 30 days
• No of times in 30 days the value of an enquiry exceeded 1M
• No of days with the total enquiries are more than 21.
• Write an algorithm in pseudo code to collect some numbers, identify
prime numbers and print the fraction of prime numbers to total
numbers input.
One dimensional arrays or linear
• Onearrays
variable can only store a data element of a program.
• If a second data element is needed then another variable should be created.
• The more data elements needed, the more distinct variables should be created by the programmer.
• An array can hold multiple data elements of the same type (integers, strings, boolean etc.).
• An array has a name, a size that cannot be changed during program execution (static data structure)
and a data type that describes the type of data that it can store.
• A one-dimensional array is a type of linear array.
• Many programming languages, including Java, always define the lower bound of an array starting
with the number 0.
• The pseudocode described in the IBO Computer Science Guide, uses zero as lower bound.
• Consider the following array of integers: The size of the array is 10, the type is integer and the name
is A.
Data structures - Arrays
• Arrays
• Declaration
• <type> <array name> [<array_size>]
• int ar[10]
• All array elements should be of the type mentioned
• Type can be integer, string, float etc.
• array_size is an integer constant or a constant expression representing number of
elements in the array.
• Array operations
• ar[3]=1 - Fourth element is 1
• int x = Ar[3]- x=1
Data structures - Arrays
• Reading an array and printing
loop i from 0 to 9
int x= A[i]
print x
end loop
• Filling an array with numbers
int A[10]
loop i from 0 to 9
output “give number”
input x
A[i] = x
end loop
Data structures - Arrays
• Finding largest number in an array
large = A[0]
loop i from 0 to 9
if A[i] > large
large = A[i]
end loop
• Copy from one array to another array
• Find the sum and average of the elements in an array.
The following program will fill the array A with
values from 1 to 10 and then print the values of the
array.
• Output:
// ==== Arrays ====
Array position 0 contains the value 1
A [10] Array position 1 contains the value 2
N=0 Array position 2 contains the value 3
Array position 3 contains the value 4
loop N from 0 to 9
Array position 4 contains the value 5
A[N] = N+1 Array position 5 contains the value 5
end loop Array position 6 contains the value 7
loop N from 0 to 9 Array position 7 contains the value 8
Array position 8 contains the value 9
output " Array position " , N , "
Array position 9 contains the value 10
contains the value", A[N]
end loop
The following program evaluates if an array is
symmetric with respect to its middle element. If the
array size is even, then the program stops.
ARRAY[50] loop while (I>=0) AND (J<N)
I=0 if ARRAY[I] = ARRAY[J] then
X = X+1
J=0
end if
X=0 I = I-l
N = input("Enter the size of array") J = J+1
end loop
if (N mod 2 = 0) then
if X = (N-1)/2 then
output "Works only with odd numbers (eg output "Array is symmetric"
3 5 7 ..... )"
else
else output "Array is not symmetric"
loop I from 0 to N - 1
ARRAY[I] = input("Enter the next element") End if
end loop End if
I = (N div 2) — 1
• Write an algorithm that finds the two neighboring numbers in an
array with the smallest distance to each other.
• The program should output the distance, index of the first number
and the index of the second number.
• For example, in the array A = [5 , 1 , 4 , 7 , 9 , —12] the minimum
distance is 2 (between array element 3 and 4).
• This algorithm should return: distance 2 between element 3 and
element 4.
//Use of Math.abs() function that returns the absolute value of a
//number. It is not included in the approved notation
A = [5,1,4,7,9,-12]
SIZE = 6
MINIMUM = Math.abs(A[0]—A[1])
MININDEX = 0
loop I from 1 to SIZE-2
if Math.abs(A[I]—A[I+1])<MINIMUM then
MINIMUM = Math.abs(A[I]-A[I+1])
MININDEX = I
end if
end loop
output "DISTANCE" , MINIMUM, "BETWEEN ELEMENT" , MININDEX, "AND ELEMENT",
MININDEX+1
Parallel arrays
• Parallel arrays are extremely useful when a programmer wants to
store different properties of an entity (fields of a record).
• All elements of an array should be of the same data type.
• So, if a programmer wants to store different data types of an entity
(e.g. student) parallel arrays offer a convenient solution.
• Parallel arrays have the same size
• In the following example 10 students’ names and their equivalent grades will be
used.
• The array NAMES of type String will be used to hold the names of the students,
• while the array GRADES of type Integer will hold the equivalent grades.
• The index of each array is the same for the same student.
• It is very important when using parallel arrays to always access each array at the
same index when storing or retrieving values.
• This process guarantees the reference of corresponding data elements.
• But the disadvantage is when an array needs to be sorted, all the other arrays
need to be rearranged. (Array of objects would help here)
// ==== Arrays ==== loop M from 0 to 9
NAMES = [ “May" , "Eri“ , "Elen" , “Rit" , if MIN >= GRADES[M] then
"Rato" , "More" , "Epi" , "Ent" , "Ronal" , MIN = GRADES[M]
“Bib”] WORST = NAMES[M]
end if
GRADES = [99,55,77,45,89,9B,76,45,33,75]
end loop
MIN = GRADES[0]
loop M from 0 to 9
MAX = GRADES[0]
AV = AV + GRADES [M]
AV = 0 if MAX <= GRADES [M] then
AVERAGE = 0 MAX = GRADES[M]
BEST = NAMES[M]
M=0 end if
BEST = “0” end loop
WORST = “0” AVERAGE = AV/10
output " ————————————————" output " ————————————"
output "STUDENTS LIST" output "Statistics"
output " ——————————————— " output " ————————————"
loop M from 0 to 9 output "Minimum mark ", MIN , "Student ",
output "No", M+1, "——Student ", NAMES[M] , " WORST output "Maximum mark ", MAX ,
GRADES[M] "Student ", BEST output "Class average ",
Sequential search
• A sequential or linear search algorithm is a very simple method to find
a particular element in an array.
• It is considered to be the simplest search algorithm
• The implementation of this algorithm does not require the use of
ordered elements (sorted arrays).
• May work well for smaller arrays, may not be efficient for large arrays
//==== Sequential Search =========
N = [2, 9, 5, 6, 7, 8] //Array elements
x = 7 //Search value
Found= false //Boolean value
Counter = 0 //It will be used for the loop
loop Counter from 0 to 5 //Number of array elements — 1
if N[Counter] = X then
Found = true
output N[Counter],"found at position" , Counter
end if
end loop
if Found = false then
output X,"not found"
end if
BINARY SEARCH
• Binary search algorithm is a searching method used only in sorted arrays.
• It relies on divide and conquer strategy to accomplish its purpose.
• In every search iteration, half of the elements of the array are eliminated
as possible solutions.
• Binary search is very efficient for large arrays.
• In each iteration, the algorithm
• 1. Compares the search value with the value of the middle element of the array.
• If the values match, then the value was found.
• If the search value is less than the middle element of the array, then the algorithm repeats its
action on the sub-array to the left of the middle element.
• if the search value is greater than the middle element of the array, then the algorithm repeats
its action on the sub-array to the right of the middle element.
• 2. If the remaining array to be searched is empty, then the value was not found.
//==== Binary Search =====
if FOUND = true then
VALUES = [11,12,15,16,112,118,123,145]
output TARGET , "FOUND AT ARRAY
//sorted array elements
INDEX" , ANSWER
TARGET = 15 //search value
MIN = 0
else
HIGH = 7 // Number of array elements - l output TARGET , " was not found"
FOUND = false end if
ANSWER = 0
MID =0
loop while FOUND = false AND MIN <= HIGH
MID = ((MIN + HIGH) div 2)
if VALUES[MID] = TARGET then
FOUND = true
ANSWER = MID
else if TARGET > VALUES [MID] then
MIN = MID + 1
else
HIGH = MID — 1
end if
Comparison table of linear search
and binary search
Bubble sort
• Bubble sort is a simple sorting algorithm that repeatedly steps through the
array to be sorted.
• It compares adjacent items (pairs of adjacent array elements) and exchanges
them if they are not in the correct order (ascending or descending).
• The algorithm makes multiple passes until no swaps are necessary and the
elements of the array are sorted.
• The algorithm is named for the way elements "bubble" to the top of the array.
• After each loop, one less element (the leftmost) needs to be compared.
• The algorithm is very slow.
• Refer to text book for Trace Table
Selection sort
• Also called exchange or interchange sort
• The list is split into two parts- sorted and unsorted
• All members belong to unsorted part, initially
• Unsorted part is scanned to locate the smallest member and it is swapped with the first
one
• This becomes the sorted part and the boundary is incremented by 1
• The process continues till the list is sorted and all elements are at their right positions.
A = [12, 663, 1, 24, 45, 56, 89, 19, 22, 66]
loop I from 0 to N – 2 Output “The Sorted Array is:"
SMALL = A[I]; loop K from 0 to N – 1
POS = I;
loop J from I + 1 to N – 1
Output A[K]
if (A[J] < SMALL) then end loop K
SMALL = A[J];
POS = J;
end if
end loop J
//next 3 steps are for swapping
TMP = A[I];
A[I] = A[POS];
A[POS] = TMP;
Output "The Array after Pass ", (I+1), " is : "
loop K from 0 to N – 1
Output A[K]
end loop K
Comparison of bubble and selection
sort
• Similarities
• Both use nested loops; Each time reducing the inner loop;
• Differences
• Bubble sort swaps adjacent items each time it goes through the list;
• Selection sort finds the next smallest each time it goes through the list;
• Bubble sort can exit early if already sorted;
Standard operations of collections
• An array is a perfect choice when a programmer wishes to store the
same type of information; a group of strings for example
• knows in advance the number of items that he/she wishes to store.
• A collection is a set of elements of any type (numbers, objects, arrays,
Strings, etc)
• Dynamic in nature - they act like a resizable array.
• The programmer does not need to know in advance the number of
items that will be placed in the data structure.
• Standard operations
• addItem()
• It is used to add an item in the collection (addition).
• TEMPERATURES is a collection of temperatures.
• TEMPERATURES.addItem(32) will add 32 to the collection TEMPRATURES.
• getNext()
• It is used to return the first item in the collection when it is first called (retrieval).
• TEMPERATURES is a collection of temperature measurements.
• A=TEMPERATURES.getNext() will assign the value of the first item in the
collection to the variable A.
• However, getNext() will not remove the item from the collection.
• Additional operations
• resetNext()
• It is used to restart the iteration through the collection.
• TEMPERATURES is a collection of temperatures.
• TEMPERATURES .resetNext () will restart the iteration through the collection TEMPERATURES.
• hasNext()
• It is used to identify if there are remaining elements in the collection that have not been accessed
by the present iteration.
• TEMPERATURES is a collection of temperatures.
• If TEMPERATURES.hasNext() will return TRUE if there are one or more elements in the collection
TEMPERATURES that have not been accessed by the present iteration.
• isEmpty()
• It is used to test if the collection is empty.
• TEMPERATURES is a collection of temperatures.
• If TEMPERATURES . isEmpty () will return TRUE if the collection is empty.
• A collection provides a mechanism to iterate through all of the elements
that it contains.
• The following code is guaranteed to retrieve each item in the collection
exactly once.
// STUFF is a collection that already exists
STUFF.resetNext()
loop while STUFF.hasNext()
ITEM = STUFF.getNext() // process ITEM in whatever way is needed
end loop
COPYING FROM A COLLECTION INTO
AN ARRAY
• The following pseudocode presents an algorithm that reads all the names from a collection, NAMES, and copies
them into an array, LIST, but eliminates any duplicates.
COUNT = 0 // number of names currently in LIST
loop while NAMES.hasNext()
DATA = NAMES.getNext()
FOUND = false
loop POS from 0 to COUNT-1
if DATA = LIST[POS] then
FOUND = true
end if
end loop
if FOUND = false then
LIST[COUNT] = DATA
COUNT = COUNT + 1
end if
Use of collection of arrays
Algorithm to solve a specific
problem
Analyse an algorithm presented as a
flow chart
Analyse an algorithm presented as
pseudocode
Construct pseudocode to represent
an algorithm
Suggest suitable algorithms to solve
a specific problem
• Efficiency of an algorithm refers to the amount of the computer resources required to
perform its functions.
• Minimizing the use of various resources such as the CPU and computer’s memory is very
important.
• Avoid unnecessary iterations
• Avoid declaring unnecessary variables or large arrays.
• Correctness of an algorithm refers to the extent to which the algorithm satisfies its
specification, is free from faults, and fulfils all objectives set during the design and
implementation phase.
• Reliability refers to the capability of the algorithm to maintain a predefined level of
performance and perform all required functions under stated conditions, having a long
mean time between failures.
• Flexibility of an algorithm refers to the effort required to modify the algorithm for
other purposes than those for which it was initially developed.
• The performance of an algorithm depends on the following internal and external
factors.
• Internal factors specify algorithm’s efficiency in terms of:
 Time required to run.
 Space (Memory) required to run.
• External factors affect algorithm’s efficiency in terms of:
 Size of the input to the algorithm.
 Speed of the computer on which it runs.
 Quality of the compiler.
• Since, external factors are controllable to some extent, mainly internal factors are
studied and measured in order to determine an algorithm’s efficiency/complexity.
• Therefore computational complexity of an algorithm is determined by studying and
measuring the internal factors affecting the algorithm.
MEASURING EFFICIENCY
• Loops: The running time of a loop is at most equal to
the running time of the statements inside the loop
(including tests) multiplied by the number of
iterations. For example:

• So, total time = c * 2 * n = 2cn (c is time taken by 1


step and 2n is number of steps in the loop)

• Since n is the dominant term, its performance is O(n).


Measuring Efficiency
• Nested Loops: The running time of a nested loop is the
product of the sizes of all the loops. For example:

• Total Time = c * n * n = cn2.


• Since n2 is the dominant term, its performance is O(n2).
Measuring Efficiency
• Consecutive statements: The running time of a nested
loop is the sum of time complexities of each statement.
For example:

• Total Time = c1 + c2 * n2 + c3 * 2*n.


• Since n2 is the dominant term, its performance is O(n2).
Deduce the efficiency of an
algorithm in the context of its use
• Big O notation is extremely useful when analyzing algorithms as it is a measure of the
efficiency of an algorithm.
• Big O notation is used in Computer Science to describe the performance or complexity
of an algorithm.
• Big O specifically describes the worst-case scenario, and can be used to describe the
execution time required or the space used (e.g. in memory or on disk) by an algorithm.
• Big-O notation typically does not call for inclusion of constants.
• Also, if you are determining the order of an algorithm and the order turns out to be
the sum of several terms, you will typically express the efficiency as only the term with
the highest order.
• For instance, if you have an algorithm with efficiency n2 + n, then it is an algorithm of
order O(n2).
Size 10 20 30 40
O(N2) 100 400 900 1600
O(2N) 1024 1048576 1,073,741,824 1,099,511,627,776

• From the above table we can state that the algorithm with complexity
O(N2) is better than the one with complexity O(2N).
O(1)
• O(1) describes an algorithm that will always execute in constant time
(or space) regardless of the size of the input data.
O(N)
• O(N) describes an algorithm whose performance will grow
linearly and in direct proportion to the size of the input data
set.
• Example – Linear Search
• The example below also demonstrates how Big O favours the
worst-case performance scenario
• a match could be found during any iteration of the for loop and
the function would return early, but Big O notation will always
assume the upper limit where the algorithm will perform the
maximum number of iterations.
O(log N)
• Binary search is a technique used to search sorted data sets.
• This type of algorithm is described as O(log N).
• The iterative halving of data sets described in the binary search
example produces a growth curve that peaks at the beginning and
slowly flattens out as the size of the data sets increase e.g. an input
data set containing 10 items takes one second to complete, a data set
containing 100 items takes two seconds, and a data set containing
1000 items will take three seconds.
A Comparison of n and log n

106
O(N2)
• O(N2) represents an algorithm whose performance is directly
proportional to the square of the size of the input data set.
• This is common with algorithms that involve nested iterations over
the data set.
• Example – Bubble Sort, Selection sort
• Deeper nested iterations will result in O(N3), O(N4) etc.
Comparison of n and n2

108
Fundamental Operations of a
computer
• Computers normally have simple operations
• Add, compare, store and retrieve
• These operations cannot be broken down any further
• Conditional instructions and Boolean operations (AND, OR, XOR, NOT)
• Data handling and memory operations
•Set a register to a fixed constant value.
•Copy data from a memory location to a register, or vice versa
• Arithmetic and logic operations
• Add, subtract, multiply, or divide the values of two registers, placing the result in a register
• Perform bitwise operations
• Compare two values in registers
Complex / Compound Operations
• Complex operations are a combination of the basic operations.
• Multiple compare / add / store / retrieve instructions are used to
accomplish a given task (for example, finding the max of n given
numbers)
• Programming languages build on the basic operations to complete
complex tasks.
• Searching, Sorting, Data modification
Essential features of a programming
language
• Consistent grammar(semantics) and syntax
• Syntax – related to the structure of a command
• Semantics – defines the meaning of every command possible in the language

• Fixed Vocabulary – reserved keywords


• Unambiguous meaning for each keyword and each command formed
with the keywords
Essential features of a programming
language
• Additional features
• Facilitates data transfer instructions, control instructions, looping instructions,
decision making instructions and arithmetic and logical operations.
• Abstraction through libraries
• Sub programs with parameter passing - helps in reusability
• Sub programs does a function - may or may not return a value.
• Data typing to ensure that the format of the data is maintained.
• Boolean expressions to ask questions and make decisions
Need for higher level languages
• CPU understands only machine codes which are a series of 1s and 0s.
• It is difficult for a programmer to develop the program in machine
code remembering different combinations of 0s and 1s to make
commands
• Each computer has its own machine language
• Machine language programs are hard to write, difficult to debug and
maintain.
• A programmer has to keep track of memory locations
• Machine language programs written for a computer of one kind are
not suitable for a computer of another kind.
Need for higher level languages
• Next evolution – Replacement of binary code with mnemonics (symbols to
represent instructions and reference to address locations)
• These mnemonics comprise the assembly language
• An assembler was used to convert/translate the assembly language instructions
to equivalent machine language instructions.
• But again, assembly language programs written for a computer of one kind are
not suitable for a computer of another kind.
To decide on a Programming
language
• Is programming language complex or easy to use / know the syntax?;

• Is there a good base of prewritten library functions?;


• Is portability good?;
• Is the compiler available over a wide range of hardware and software
platforms?;
• Is speed of execution good?;
• Is the language appropriate to the problem?;
• Web-based/mobile?;
Need for higher level languages
• As programming evolved, programmer need to have more of data management
and logical operational skill rather than technical skill.
• Programming was becoming more of a science and a separate realm of study
• Thus the evolution of higher level language and software development became
independent of hardware.
• Reasons for the evolution of High level languages
• Lack of abstraction in machine/assembly language
• To focus on problem solving
• To improve efficiency
Need for higher level languages
• Next evolution – High Level Programming languages
• Higher level languages are more close to the user than to the
machine/hardware.
• Uses elements of natural language
• Easy to use
• Facilitates abstraction by hiding significant areas of computing systems
• Makes the program development simpler, faster and more understandable
Need for a translation process from
a higher-level language to machine
executable code
• Compiler converts the HLL programs (Source program) to machine code (Object program).
• Earlier compilers converted the program first to assembly language and then used an assembler to
convert to machine code.
• Current compilers use a single step process.
• Different operating systems have different compilers for the same language
• Compiler compiles the entire program at one go and produces an executable or object file
• which can then be executed independently.
• If there are no errors, the object program is saved and next time, no recompilation is required.
• If there are errors, the compiler reports error messages for all the syntax /semantic / type errors
along with line numbers and no object program is produced.
• Compilation ends only when all errors are corrected and object program is produced.
• Compilers are faster than interpreters. Examples of compiled languages – C, C++
• Executable can be distributed without exposing the source code.
Need for a translation process from
a higher-level language to machine
executable code
• An interpreter converts and executes the program line by line
• No executable or object file
• Good for debugging
• Interpreter stops at every error. Only if the error is corrected, it
proceeds to the next line of the program
• Interpreter should be loaded for every run
• Source code is exposed
• Example of interpreted language - Python
Need for a translation process from
a higher-level language to machine
executable code
• Java combines compilation and interpretation.
• Source code is compiled to Java Virtual Machine bytecode.
• When a Java program is compiled from .java file to a .class file, the
class file contains JVM bytecode.
• This JVM bytecode can be interpreted by the Java Virtual Machine
interpreter.
• The Java architecture allows code to run on any machine/hardware in
which the Java Virtual Machine interpreter has been installed.
Characteristics and applications of a
collection
• consists of zero or more elements such as objects and values
• Contains necessary methods to handle data elements
• have elements of same datatype
• Can grow or shrink
• Examples – Stack, Queue, HashMap, Tree, List
• Application
• Bulk handling and processing of records taken from a database
• Implement a queue of entities
Importance of sub-programs and
collections within programmed
solutions
• A sub-program is a unit that contains a sequence of computer
instructions that perform a specific and predefined task.
• Code reuse - it allows programmers to take advantage of existing code
and solutions developed by other programmers (or by themselves) to
speed up the development.
• Code reuse saves time and resources and allows the completion of
demanding projects in the shortest period of time.
• Authors of new programs can take advantage of software libraries,
which contain subprograms that can be used whenever required
• Advantages of breaking a program into sub—programs:
• Breaking down a complex programming job into simpler jobs
• Distributing a very large programming problem among various programmers
• Enabling code reuse across multiple programs
• Facilitation of abstraction by hiding implementation details from users of the
subprogram
• Improving maintainability and traceability
• Reducing programming code duplication within the same program
• A large/difficult program could be divided into smaller/easier parts (sub-
programs); A sub-program could be used many times in this and other programs;
A sub-program could be written independently; A sub-program could be tested
independently; Easier maintenance – only sub-program could be
changed/modified as needed;
• Advantages of using collections:
• The methods of collections are predefined algorithms that the programmer
can immediately use
• Performance is increased by the data management capabilities provided by
the collection
• Software reuse is facilitated because the use of methods is based on a
common language and a standard interface
Subprogram, procedures…
• Different computer programming languages use the terms procedure, sub-
procedures, function, routine, method, subroutines, modules etc. to refer to
subprograms.
• A sub- program is a unit that contains a sequence of computer instructions
that perform a specific and predefined task.
• This unit can then be used in various computer programs wherever that
specific and predefined task should be implemented.
• Subprograms may be defined within programs, or separately in libraries that
can be used by multiple programs.
• in most cases a function returns a value and a procedure just executes
commands.
• In C++ programming language, for example, a procedure performs a task
Subprogram, procedures…
• Java uses methods to represent subprograms.
• A Java method may return a value and the main program may pass one or
more variables to a method.
• A parameter is the name of the information that is used in a method,
function or procedure while an argument is the value that is passed into a
method, function or procedure.
• Usually, a module refers to a small section of a program that is customized
to perform a particular task.
• Modules can be customized by a programmer to do a particular task,
Collection of objects
Array Operations
• Traversal
• Sum of elements
• Max, Min elements in an array
• index of the largest element
• index of the largest element
• Shift the elements of the array (right / left)
• Rotate the elements

You might also like