You are on page 1of 92

General principles, Connecting

computational thinking and


program design
Syllabus
•1 General principles
•1.1 Thinking procedurally
•1.1.1 Ask questions
•1.1.2 Look for familiar things
•1.2 Thinking logically
•1.3 Thinking ahead
•1.4 Thinking concurrently
•1.5 Thinking abstractly
•2 Connecting computational thinking and program design
•2.1 Searching algorithms
•2.1.1 Sequential search
•3 Introduction to programming
•3.1 Nature of programming languages
•3.2 Use of programming languages
• 4.1 General principles

4.1.1 Identify the procedure appropriate to solving a problem.
4.1.2 Evaluate whether the order in which activities are undertaken will result in the
required outcome.
4.1.3 Explain the role of sub-procedures in solving a problem.
4.1.4 Identify when decision-making isrequired in a specified situation.
4.1.5 Identify the decisions required for the solution to a specified problem.
4.1.6 Identify the condition associated with a given decision in a specified problem.
4.1.7 Explain the relationship between the decisions and conditions of a system.
4.1.8 Deduce logical rules for real-world situations.
4.1.9 Identify the inputs and outputs required in a solution.
4.1.10 Identify pre-planning in a suggested problem and solution.
4.1.11 Explain the need for pre-conditions when executing an algorithm.
4.1.12 Outline the pre- and post-conditions to a specified problem.
4.1.13 Identify exceptions that need to be considered in a specified problem solution.
4.1.14 Identify the parts of a solution thatcould be implemented concurrently.
4.1.15 Describe how concurrent processing can be used to solve a problem.
4.1.16 Evaluate the decision to use concurrent processing in solving a problem.
4.1.17 Identify examples of abstraction.
4.1.18 Explain why abstraction is required in the derivation of computational solutions for
a specified situation.
4.1.19 Construct an abstraction from a specified situation.
4.1.20 Distinguish between a real-world entity and its abstraction.
Thinking procedurally
4.1.1 Identify the procedure appropriate to solving a problem.

• Generally speaking, all problems begin with an idea. Finding


the connection between this information and the solution lies
at the heart of problem solving. To do this, the following
strategies can be utilized.
Ask questions
• When given a problem or task verbally, one typically asks questions until what is
needed is known fully and clear. Generally, when, why, and where are asked until the
task is completely specified. If the instructions are written, one might put question
marks in the margin; underline a word, a group of words, or a sentence; or in some
other way indicate the parts of the task that are not clear. Perhaps the questions
might be answered in a later paragraph, or one might have to discus them with the
person giving the task. If the task is one that it self-set, this sort of questioning
might not be verbal, but instead takes place on the subconscious level.
• In this case, some typical questions that one should consider are:
• What should I know about the problem?
• What does the solution look like?
• What sort of special cases exist?
• How will I recognize that I have found the solution?

• Look for familiar things


Basic Principles of Solving
Computer Programming Problems
• Use Pen and Paper
• Generate Ideas and Give Them a Try!
• Decompose the Task into Smaller Subtasks
• "Cards Shuffle" Problem – Example
• Let’s give the following example: we have one ordered deck
of cards and we have to shuffle it in random order. 
Steps:-
First Subtask: a Single Swap
Second Subtask: Choosing a Random Number and
divide the stack
Third Subtask: Combining Swaps
Another Example:
Sorting Numbers
Let’s think of another example. We are given an array
of numbers and our task is to sort it in ascending
order.
First idea: We can find the smallest number, print it and then remove it from the
array of numbers. The next thing to do is to repeat the same action until the
array is empty. Thinking like this, we can decompose this task into simpler tasks:
finding the smallest number in array; deleting a number from array; printing a
number.
 Next idea: We can find the smallest number and put it at the first position of the array (swap operation). Then we
can do the same action for the rest of the array. Since we have already placed number on the first position, we go
to the next one. If we repeat this k times, we will have the first k smallest numbers from the array at the first k
positions. This approach takes us naturally to a task, which can be very easily divided into smaller subtasks:
finding the number with the smallest value in a part of the array and exchanging the positions of two numbers
from the array. The second subtask can be divided one more time: removing an element from a given position and
placing an element at a given position.
 Another idea, Which uses a method, conceptually different from
the previous two solutions: we split the array into two subarrays
with approximately the same number of elements. Then we sort
them individually and finally we merge them into one.
Verify Your Ideas!
It seems that we have figured out everything. We have
an idea. It seems to work properly. The only thing for us
to do is to check if our idea is correct or it is only
correct in our minds. After that we can start with the
implementation.
How to verify an idea? Usually this happens with the
help of some examples. We should choose examples
that fully cover all different cases, which our algorithm
should be able to pass. The sample examples should not
be too easy for your algorithm, but also they should not
be so hard to be sketched. We call these certain types of
examples "good representatives of the common
case".
4.1.2 Evaluate whether the order in which activities
are undertaken will result in the required outcome.

• We constantly break up a large problem into smaller


units that we can handle. The task of cleaning the
house or apartment may seem over-whelming. The
task composed of cleaning the living room, the dining
room, the kitchen, the bedrooms, and the bathroom
seems more manageable. This principle is especially
relevant to computing.
4.1.3 Explain the role of sub-
procedures in solving a problem.
•Do not reinvent the wheel. If a solution exists, use it. If you have solved the same or a similar
problem before, just repeat the successful solution. We usually do not consciously think, "I
have seen this before, and I know what to do" - we just do it. Humans are good at
recognizing similar situations. We do not have to learn how to go to the store and buy milk,
then to buy eggs, then to buy candy. We know that going to the store is always the same and
only what we buy is different.
•Recognizing familiar situations is particularly useful in computing. In computing, you see
certain problems again and again in different guises. A good programmer sees a task, or
perhaps part of a task (a subtask), that has been solved before and plugs in the solution. For
example, finding daily high and low temperatures in a list of temperatures is exactly the
same problem as finding the highest and lowest grades in a list of test scores. You want to
the largest and smallest values in a set of numbers.
• Thinking logically
Sub-procedures are functions that have no use on their own but are used in other procedures to contribute to solving a larger problem, for example a function that searches an array for a given item in a
library management system. Putting these tasks down into sub procedures has many advantages:

the complexity of the main procedure is reduced (only the abstraction of the sub-procedure, the calling command, is displayed)
this allows easier understanding of the working of the procedure
each sub-procedure has its own task
if many procedures use the sub-procedure, code duplication can be avoided → reduced risk of bugs in the code
easier management of the code as each function can be developed on their own
4.1.4 Identify when decision-making is required in a
specified situation.

• Every time there are two possible ways for the algorithm to go.
For example, decision making is required to decide if the
entered data is valid in a system.
4.1.5 Identify the decisions required for the
solution to a specified problem

• Lets take the example that a system needs the age of the users.
To prevent invalid values to be entered, a validation algorithm
is used. The decisions required for this algorithm:
• Is a negative value entered?
• Is the value not greater than 150?
• Depending on the system, is the age below 18?
4.1.6 Identify the condition associated with a
given decision in a specified problem

Decision making is critical to computer programming. There will be


many situations when you will be given two or more options and you
will have to select an option based on the given conditions. For
example, we want to print a remark about a student based on secured
marks and following is the situation:

1. Assume given marks are x for a student


2. If given marks are more than 95 then
3. Student is brilliant
4. If given marks are less than 30 then
5. Student is poor
6. If given marks are less than 95 and more than 30 then
7. Student is average
• 4.1.4 Identify when decision-making is required in a specified situation.
• Decision making structures require that the programmer specifies one
or more conditions to be evaluated or tested by the program, along with
a statement or statements to be executed if the condition is determined
to be true, and optionally, other statements to be executed if the
condition is determined to be false.
• Example – a programming language assumes any non-zero and non-
null values as true, and if it is either zero or null, then it is assumed
as false value.
S.N Statement & Description
.
1 if statementAn if statement consists of a
boolean expression followed by one or
more statements.
2 if...else statementAn if statement can
be followed by an optional else
statement, which executes when the
Boolean expression is false.
3 nested if statementsYou can use
one if or else if statement inside
another if or else ifstatement(s).
4 switch statementA switch statement
allows a variable to be tested for equality
4.1.5 Identify the decisions required for the solution
to a specified problem.
• Check Whether a Number is Even or Odd
• user is asked to enter three numbers and this program will find the
largest number among three numbers entered by user.
• program to check whether a year is leap year or not
• checks whether that number is either positive or negative or zero.
• A=5 assignment operator – passing values
• A<=5 (1,2,3,4,5) a<5= 1,2,3,4
• A==5 – checking the value of variable A is 5 or not- comparison
operator
• 4.1.6 Identify the condition associated with a given decision in
a specified problem.
• 4.1.7 Explain the relationship between the decisions and
conditions of a system.
• 4.1.8 Deduce logical rules for real-world situations.
Thinking ahead
• 4.1.9-Identify the inputs and outputs required in a solution.
A computer:
Accepts input from a user
Processes the input
Generates output
The computer activities are broken into the following three phases:
Input phase
Process phase
Output phase
Identify the IPO cycle
Calculation of the average salary of a department falls under which of
the following phases?
1. Input phase
2. Process phase
3. Output phase
Programs and Programming Languages

A computer needs a set of instructions, called programs, to perform the I-P-O cycle.
A program needs to be written in a specific language, called a programming language.
Program
A program specifies:
Input to be provided
Process to be done
Output expected
Machine language code:
Collection of binary digits 0 and 1
Represents Data and Instructions
Machine code to represent the commands, ADD and SUBTRACT
• Command
• Machine Code
• ADD
• 1010000100
• SUBTRACT
• 1010001000

Disadvantages of using machine language:


Difficult to remember instructions
Highly dependent on the hardware being programmed for
To overcome the above disadvantages, high-level programming languages are used.
High-level programming languages:
Represents instructions using simple English words
Has a vocabulary and grammar - syntax
Examples: C, C++, and Java
• Can computers directly understand the instructions
written in any programming language?
No, you need a translator
that converts the high-
level language
instructions into machine
language.
Compiler: translator convert programming language to
machine language
Converts the instructions into machine language
Follows the I-P-O cycle
Takes instructions as input
Processes instructions and converts them to machine
language
The following figure depicts the working of a compiler.
Tools Used in Problem Solving - Algorithm

Characteristics of an algorithm:
Has fixed number of steps
Each specifies the action to be performed
Accepts input data
Generates one or more outputs after the input is processed
Let us see how to
write an algorithm
to withdraw a
required amount
from an ATM.
An algorithm is a sequence of instructions in English language written to solve a given
problem.
A flowchart is a graphical representation of the steps to be followed for solving a problem.
Pseudocode is a detailed yet readable description of what an algorithm must do, expressed
in a formally styled natural language rather than in a programming language.
The algorithm to add two numbers The following figure represents the pseudocode for the
and display their sum is: algorithm alongside
1. Start the algorithm.
2. Accept two numbers.
3. Calculate the sum of numbers.
4. Display the sum.
5. End the algorithm.
Algorithm to withdraw an amount from an ATM will be:
1. Start the algorithm.
2. Go to any local ATM.
3. Insert/swipe your ATM card.
4. Press the language button that you want to choose.
5. Enter the ATM PIN.
6. Press the account type (Savings or Current) button.
7. Press the cash withdrawal button.
8. Enter the amount you want to withdraw.
9. Collect the amount from the ATM machine.
10.A transaction slip confirming the successful transaction will be printed.
Collect the transaction slip from the ATM machine.
11.Collect your ATM card.
12.End the algorithm.
Let us look at
another algorithm to
troubleshoot the ‘No
sound’ problem of a
television.
Algorithm to troubleshoot the ‘No sound’ problem:
1. Start the algorithm.
2. Ensure that the Mute button is not pressed.
3. Ensure that the desired volume is set.
4. If sound is still inaudible, call the television engineer.
5. End the algorithm.
Flowchart:
A graphical representation of an algorithm
Consists of a set of symbols
Each symbol represents a specific kind of activity
Pseudocode:
Written in a formally-styled English language
Used as an initial in the process of developing a program
Provides a detailed template to programmers
You are asked to write a step-by-step procedure to solve a problem that involves a lot of nested conditions. Which among the following
tools should be the ideal tool to be used in this situation?
1. Flowchart
2. Pseudocode

Solution:
Flowchart
Let’s Practice

1. Write an algorithm to find out whether a number entered


by a user is divisible by 5.
2. Write an algorithm to display the first 10 multiples of 9
3. Write an algorithm to accept two numbers, divide
the first number by the second, and display their
quotient.
Summary

In this session, you learned that:


The activities performed by a computer follows the
I-P-O cycle.
A set of instructions to perform a particular job is called a program.
The language that the computer understands is called the machine language.
In a computer, everything is represented as a combination of on and off states.
The on state is represented by 1 and the off state by 0.
A high-level programming language consists a set of instructions.
A compiler is a special program that converts the instructions into machine language.
Problem Solving Using Flowcharts

Flowcharts:
Represent programming logic in a graphical form
Depict logic in a step-by-step process
Use a set of symbols
Use arrows to indicate the flow of process
Drawing Flowcharts

A flowchart is created by using a set of symbols which


represents various activities.
Rules of drawing a flowchart:
Represent the entire logic using standard symbols
Clear, precise, and easy to follow
Only one start point and one end point
Top-to-bottom or left-to-right approach
List necessary inputs in logical order
Only one flow line for the start and stop symbols
Use page connectors (if it extends over multiple pages)
Flowcharts allow you to represent:
Conditions
Repetitive processes
Make a flowchart for withdrawing an amount from an ATM.
Flowchart:
Lets look at a flowchart for accepting a number,
incrementing it by one, and displaying the result.

Lets dry run a flowchart and check the output


Which of the following symbols is used to connect one step
in flowchart to another step on a different page?
1. Decision
2. Annotation
3. On page connector
4. Off page connector

Solution:
Off page connector
Make a flowchart to determine whether a
number is Even or Odd.

Make a flowchart to find the largest of the three


numbers entered by a user.
flowchart to calculate and display the sum of the
first 10 natural numbers.
Dry run:
Helps perform a logic check
Helps understand the flow of control in a flowchart or in a
pseudocode
Evaluates the output of a program with a set of sample values
Provides a step-by-step evaluation of values in a program
Example:
Calculate and display the sum of the first 10 natural numbers
with dry run
Draw a flowchart that accepts two numbers and
checks if the first is divisible by the second.

Draw a flowchart that accepts three


numbers and displays the least of
these numbers.

Draw a flowchart to accept two


numbers and any one of the
following characters: +, -, *, and /.
Based on the character entered, the
numbers should be added,
subtracted, multiplied, or divided
and the result should be displayed.
Flowchart:
A graphical representation of an algorithm
Consists of a set of symbols
Each symbol represents a specific kind of activity

Advantages
• Helps in analyzing the problems effectively
• Acts as a guide during the program development phase
• Helps in easy debugging of logical errors

Limitations
Flowchart extended over multiple pages reduces readability
Drawing a flowchart is time consuming
Changes in a single may cause redrawing the entire
flowchart
Pseudocode:
Written in a formally-styled English language
Used as an initial in the process of
developing a program
Provides a detailed template to programmers
Advantages Limitations
Easier and faster to write Does not provide a
graphical representation
Does not need to be rewritten if Depiction of too many
any change is are made nested conditions
makes it difficult to
Can be easily converted to a understand
program
You are asked to write a step-by-step procedure to solve a
problem that involves a lot of nested conditions. Which
among the following tools should be the ideal tool to be
used in this situation?
1. Flowchart
2. Pseudocode

Solution:
Flowchart
• Write an algorithm to accept two numbers, divide the first number by
the second, and display their quotient.
(Allocated time to solve the problem is 10 minutes.)
• Write an algorithm that accepts distance in kilometers, converts it into
meters, and then displays the result.
(Hint: Distance in meters = Distance in kilometers * 1000
Allocated time to solve the problem is 10 minutes.)

• Write an algorithm that accepts five numbers and displays the sum and
average of the numbers.
(Allocated time to solve the problem is 15 minutes.)
Pseudocode:
Represents the logic of the solution to a problem
Can be converted into a program using:
Vocabulary of a programming language
Syntax of a programming language
Keywords used to write a pseudocode:
begin……end
accept
compute
display
if……else
repeat...until
while
for( ; ; )
call subroutine_name
Variable:
Refers to a memory location
Can store only one value at a time but the value can vary

Constant:
Refers to a memory location
Holds a fixed value
4560 4562 4564 Address of memory
location

10 15 25 Values stored in the


memory location

nNum1 nNum2 nSum Variable name


Data types are broadly categorized as:
Numeric
Character
Declaring variables:
Name should be specified
Type should be specified
Conventions for naming variables:
First letter may indicate the data type used
Name should clearly describe its purpose
Can consist of letters, digits, or underscores
Must begin with a letter or an underscore
Must not contain any embedded space and symbols, such
as ?, ! @ # $ % ^ & * ( ) { } [ ] . , : ; “ ‘ / \
Which of the following variables does not comply with the
variable naming conventions?
1. nQuantity
2. nUnit Price
3. nProduct_Name
4. nCost
Solution:
nUnit Price
Identify the constant in the following formula:
Area of circle = Pi * (radius * radius)

• Can we specify the memory location to store a variable value?


Methods to assign values to variables:
Direct assignment
Accept statement
Direct assignment:
Values can be assigned by using the equal to
(=) sign or the Compute keyword
Syntax:
variable_name = value
Compute variable_name as value
Example:
begin
numeric nHeight, nAge, nCounter
character cCode
nHeight = 172
nAge = 35
nCounter = nAge + 10
cCode = ‘XYZ’
end
accept statement:
Used to assign values to variables
Syntax:
accept variable_name
Example:
begin
character cName
numeric nAge
display ‘Enter your name:’
accept cName
display ‘Enter your age:’
accept nAge
end
Tools for predefined operations are known as
operators.
Categories of operators:
Arithmetic operators
Relational operators
Logical operators
Arithmetic operators:
Used to perform arithmetic calculations
Commonly used arithmetic operators:
*
/
+
-
%
Precedence of arithmetic operators.

Consider the following arithmetic expression:


12 + 5 * (10 / 2 + 6)
The step-by-step evaluation of the given expression is:
12 + 5 * (5 + 6)
12 + 5 * 11
12 + 55
67
Relational operators:
Used to compare two variables or constants
Relational operators:
==
>
<
!=
>=
<=
Logical operators:
Combine expressions containing relational
operators
Relational operators:
AND
OR
NOT

Precedence of logical operators.


Write the pseudocode to accept two numbers, divide the first number
by the second, and display their quotient.

Write the pseudocode to accept five numbers and display the sum and
average of the numbers.

Write the pseudocode to accept item name, price, and quantity from a
user and display the item name and its total value. The total value can
be calculated as the product of price and quantity.
Thinking ahead
4.1.9 Identify the inputs and outputs required in a solution
4.1.10 Identify pre-planning in a suggested problem and solution
4.1.11 Explain the need for pre-conditions when executing an
algorithm
Algorithms make decisions based on some pre-conditions. So, they need
some initial conditions after which they direct their working. Pre-conditions
are often given as parameters to the algorithm.
4.1.12 Outline the pre- and post-conditions to a specified problem
4.1.13 Identify exceptions that need to be considered in a specific
problem solution
4.1.14 Identify the parts of a solution that could
be implemented concurrently

Concurrent computing is a form of computing in which several computations


are executing during overlapping time periods – concurrently – instead of
sequentially (one completing before the next starts) Concurrent computing.
Many processes can be implemented concurrently:
•Some calculations (Brute force calculations are usually implemented
concurrently)
•GUI is usually implemented concurrently
•The programs in a modern computer run concurrently (parallel)
4.1.15 Describe how concurrent processing can be used to
solve a problem
In a production line many processes are running parallel.
Concurrent processing plays a crucial role here as it is what allows
the system to execute a large amount of tasks simultaneously.

4.1.16 Evaluate the decision to use concurrent processing in


solving a problem
You need to think ahead. Before you start designing the solution try
to think on which tasks can be run independently from each other.
For example, in a calendar software, the periodical check if any
reminders are due can happen independent from user input, so can
run parallel to the rest of the solution.
Thinking abstractly
4.1.17 Identify examples of abstraction
An abstraction could be a car engine. You don't need to know how it
works to be able to operate it, you only need to know how its abstraction
works. So, creating an abstraction requires a lots of thinking ahead as
you need to select the pieces of information that are relevant for an
abstraction.

4.1.18 Explain why abstraction is required in the derivation of


computational solutions for a specified situation
Computers cannot store an infinite number of things so we need to
reduce them to abstractions, containing only necessary information. Also,
this properties can then be grouped together into objects, which are a
fundamental concept in computing and algorithms.
4.1.19 Construct an abstraction from a specified situation
Lets say we need to create an abstraction from the people in a
school. We can decompose the people in the school into teachers
and students. Students can aslo be decomposed into boys and
girls.

4.1.20 Distinguish between a real-world entity and its


abstraction
A car engine. It is made up of hundreds of parts, but we still need
no nowledge on how they work. We only need to know how its
abstraction - the pedals, gearshifting and the steering - work to be
able to run it. In fact, the similarity of the abstractions allow us to
be able to operate many different kinds of engines and vehicles,
regardless on what type of engine they are using.
4.2 Connecting computational thinking and program design
4.2.1 Describe the characteristics of standard algorithms on linear arrays

Sequential search: The algorithm loops through the array one-by-one


until the required item is found or the end of the array has been
reached. It is the simplest of all search algorithms.
Efficiency for a list consisting of n elements: O(n)

Binary search: The algorithm needs an ordered list to work. It starts in


the middle of the array and checks if the desired result is either in the
first or second half of the list. The other half is then discarded and the
process is used for this sub-array until there is only one element left.
Efficiency for a list consisting of n elements: O(logn). However, if the list
is unsorted, the algorithm is useless.
Bubble sort: This is an algorithm to sort an unsorted array, based on
comparing and switching items.

Selection sort: The algorithm starts with the first element in the array. Then it loops through the
rest of the array and finds the smallest element and switches it with the first one. Then it goes on
to the second element and repeats the procedure until it reaches the end of the array.
Example: an array with content 4|2|1|6|3|5 should be sorted:
4 2 1 6 3 5 Minimum is
1, so switch
first and
third
element
1 2 4 6 3 5 Minimum is
2. Because
it is already
at the first
position
nothing is
changed
1 2 4 6 3 5 Switch 4
and 3
1 2 3 6 4 5 Switch 6
and 4
1 2 3 4 6 5 Switch 6
4.2.2 Outline the standard operations of collections
Lists: A finite ordered collection of values, where the same value may occur more than
once.

Operations:
•constructor for creating an empty list
•testing whether or not a list is empty
•prepending an entity to a list
•appending an entity to a list
•determining the first component (“head”) of the list
•referring to the list consisting of all components except for the first one (this is the “tail” of
the list)
Stack: A special kind of collection where the only operations are the
addition or removal of an entity to the collection, known as push and pop.
This makes a stack a Last-In-First-Out (LIFO) data structure.

Queue: A special kind of collection where the entities are kept in order and
the only operations permitted are the addition or removal on an entity,
where the first added entity is removed first. This makes a queue a First-
In-First-Out (FIFO) data structure.

You might also like