0% found this document useful (0 votes)
23 views17 pages

Programming and Pseudo Code Algorithms

Uploaded by

tammymam63
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
23 views17 pages

Programming and Pseudo Code Algorithms

Uploaded by

tammymam63
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 17

Programming and pseudo code Algorithms

Programming terminologies in Pascal & C++

• An identifier is a name which is used to refer to a variable, constant, function or type in


C++. When necessary, an identifier may have an internal structure which consists of a
prefix, a name, and a suffix (in that order).

• Variables is a name for a piece of memory that can be used to store information

• Operators: examples:

• Arithmetic Operators eg +,-,%,/,*

• Logical operators eg &&, ||, !

• Increment and decrement operators eg ++, --

• Relational Operators eg ==,! =,<,>,<>

• Assignment Operators =,+=,-=

Algorithms

• Algorithm - is a list of step-by-step instructions that, when followed, will solve a


problem.

• It is formally a type of effective method in which a list of well-defined instructions for


completing a task will, when given an initial state, proceed through a well-defined series
of successive states, eventually terminating in an end-state.

Properties of Algorithms

1) Input: It may accept zero or more inputs


2) Definiteness: Each instruction must be clear, well-defined and precise. There should not be
any ambiguity
3) Effectiveness: Each instruction must be simple and be carried out in a finite amount of time.
4) Finiteness: Algorithm should have finite sequence of instructions. That is, it should end after a
fixed time. It should not enter into an infinite loop
5) Output: It should produce at least one output.
How can we describe algorithms?
Algorithms can be designed using Pseudo codes, Programming language and flow charts.
They are written using statements and expressions.
• • Flowcharts:
• – graphical description of the flow of processing steps
• – however, sometimes useful to describe the overall structure of an application
• • Pseudo code:
• – artificial language based on vocabulary (set of keywords)
• syntax (set of rules used to construct the language’s “phrases”)
– Not as restrictive as a programming language
Designing an algorithm

When designing an algorithm, you need to assess how complex it could be. With a food recipe, a
simple command like 'spread butter on bread' could be made much more detailed. For example:

1. Remove lid from butter tub and place to one side.


2. Place 5 grams of butter on the tip of the knife.
3. Position the tip of the knife on the upwards side of the slice of bread with the butter
between the knife and the bread.
4. Move the knife backwards and forwards in a sweeping motion across the bread to spread
it at an even thickness.
5. Repeat steps 2 to 4 until one side of the slice of bread is evenly coated with butter.
6. Remove any excess butter from the tip of the knife.

Variables

Algorithms have values that can be constant or variable. These values are stored in a
memory location and can be changed, depending on the output that is needed. For
example, the main content for a sandwich could be cheese or jam. In this case 'main
ingredient' would be a value which is variable. You could require one sandwich or 57
sandwiches. This would be another variable.

Defining Variables

When devising an algorithm the programmer will need to use variables and assign values to
them. Many languages require a variable to be defined and given a data type before use.

DEFINE x AS integer
The five basic data types that can be used here include:

 char
 string
 integer
 real
 Boolean

Variable Assignments

Assigning a value to a variable is indicated in pseudo code using an arrow symbol (←). The
arrow points from the value being assigned towards the variable it is being assigned to.

The following line of pseudo code should be read as 'a becomes equal to 34'.

a ← 34

Totalling and Counting


- totalling (e.g. Sum ← Sum + Number)
- counting (e.g. Count ← Count + 1)

The assignment operator can also be used when finding totals, as shown in the following
example where x becomes equal to a plus b.

x←a+b

Similarly we can also use the assignment operator for counting, by assigning a variable to
become equal to the value of itself plus 1.

x←x+1

Input and Output


- INPUT and OUTPUT (e.g. READ and PRINT)

Output is the act or returning some data to the user of the program. This could be in the form of a
written message, a numerical value, an image, video or sound. This is shown in pseudocode by
writing OUTPUT followed by what the output will be. The example below shows how we would
output the message 'Hello World':

OUTPUT 'Hello World'

Sometimes the word PRINT may be used instead of OUTPUT, as in the following example:

PRINT 'Hello World'


Input on the other hand is when we expect some value to be provided by the user. The following
example will output a message asking the user to input their name and assign it to a variable
called 'name'.

PRINT 'What is your name?'


INPUT name

The word READ can also be used instead of INPUT.

PRINT 'What is your name?'


READ name

Pseudo code

You can write algorithms in plain English before you decide which programming language you
want to use. Writing algorithms this way is called pseudocode.

There is no 'exactly right' form for a pseudocode algorithm - as long as it makes sense to others.

The most important things about a pseudocode algorithm are:

 it is correct
 it is written in a form that can be understood by fellow programmers
 what is intended is clear, and not at all ambiguous
 it can be implemented on the computer system it is written for

General Rules for Pseudocode

1. "Camel casing" is recommended - capitalize the first letter of the second and each additional word.
2. Choose variable names that reflect the purpose of the variable or module. For example netPay,
totalNetPay, xSquared, xCubed.
3. Use appropriate white space and do so in a consistent fashion to make code easy to read.
4. Use the first part of the code to declare variables. If an algorithm needs to read the value of a
variable before it assigns input data or a calculated value to the variable, the algorithm should assign
an appropriate initial value to the variable. Take the example below. If total was not assigned the
value of 0 initially, we could not calculate total + number.
total ← 0

INPUT number

WHILE number >= 0 DO

total ← total + number

INPUT number

ENDWHILE

OUTPUT number

To avoid error, all variables should be declared and assigned.


5. Use comments appropriately to help someone else understand what you are doing in a section of
code.
6. Keywords in UPPERCASE are preferable.
7. Avoid pointless pseudocode. For example
INPUT number1

INPUT number2

INPUT number3

This is better:
INPUT number1, number2, number3

8. Common errors in pseudocode include:


 missing or faulty initialisation of variables
 faulty initial and final values for the control variable (loop counter) in a FOR…TO…NEXT loop
 incrementing the loop counter in a FOR…TO…NEXT loop, which interferes with the automatic
counting
 failing to increment an optional counter variable in the other sorts of loop
 failing to complete a structured statement with the requisite ending keyword ENDWHILE, UNTIL,
NEXT, ENDIF or ENDCASE
 misplacing a keyword so that statements are inappropriately inside or outside a loop.

The following example shows a pseudocode algorithm which has been written to describe the
movement of a robotic car. It uses slightly more technical language:

set 'stop' to False


repeat
if there is an obstacle
set 'stop' to True
otherwise
move forward 1 cm
until 'stop' is True
Examples
1.Write an algorithm to find sum and average of 3 numbers
Step 1: start
Step 2: read a,b,c[ input 3 numbers]
Step 3: sum a + b + c
Step 4: avg=sum/3
[Find average]
Step 5: print sum, avg
[Output the result]
Step 6: stop

2. Write an Algorithm to find whether an entered integer number is positive or


Negative (Decision making type)

Step 1: Start
[Beginning of the Algorithm]
Step 2: Read a number A[Input the integer number]
Step 3: If A is greater than 0[compare A to zero]
Print number as positive
Else
Print number as negative
Step 4: Stop
[End of the Algorithm]

3. Write an algorithm to find largest of two numbers


Step 1: Start
[Beginning of the Algorithm]
Step 2: Read a and b[Input two numbers a,b]
Step 3: if a is greater than b[ compare a and b]

print a as large
else
print b as large

[output the result]


Step 4: Stop
Flow charts

One way of representing algorithms is to use flow charts, also called flow diagrams. It is
diagrammatic or pictorial representation of an algorithm.

The various symbols are used to write different instructions/operations

A flow chart shows the key points in an algorithm:

 the start and end


 the order in which the sequences of instructions are performed
 the points where inputs and outputs occur
 the points where decisions are made about what to do next

A sequence of many instructions that does not involve any of these key points may be
represented as a single rectangular box.

Flow charts use a variety of standard flow chart symbols to represent different elements, and
arrows to show the flow or direction. The most commonly used symbols are:
For example, if the robot vehicle is 3 cm from the edge of the table and you tell it to move
forwards 5 cm, it will drive off the edge of the table. To stop this from happening, you might
write a condition-controlled loop like this

Loops and Iterations

Different patterns of algorithms


1) Sequential: In this different steps occur in a sequence.In a sequence, there is a linear
progression of statements. The result of one statement is used in subsequent statements. Here are
some key actions that are performed and the common words used in pseudo code:

 Input: READ, OBTAIN, GET


 Output: PRINT, WRITE
 Compute: COMPUTE, CALCULATE, DETERMINE
 Initialize: SET, INITIALIZE
 Add one: INCREMENT
 Subtract one: DECREMENT

2) Conditional: In this different steps are executed based on a condition (whether true/false). In
programming languages, a conditional pattern is implemented using decision making statements.
In a conditional statement you make a test. The result of the test is a Boolean - either True or
False. If the result of the test is True you take a certain course of action and if the result of the
test is False you take another course of action.

IF condition THEN
sequence 1
ELSE
sequence 2
ENDIF

If the condition is True sequence 1 is executed, otherwise sequence 2 is executed. The ELSE
sequence is optional.

IF THEN ELSE

An IF statement starts with a condition which is tested. If the condition evaluates as TRUE then
the THEN code block will be run. If the condition evaluates as false then the ELSE block will
run. In the following example "Hello" will be printed if x = 1, otherwise "Goodbye" will be
printed.

IF x = 1 THEN
print "Hello"
ELSE
print "Goodbye"
END IF

Often ELSE IF is used when there is more than one condition to check. The following example
would print "Hello" if x = 1, or "How are you?" if x = 2 or will otherwise print "Goodbye".

IF x = 1 THEN
print "Hello"
ELSE IF x = 2 THEN
print "How are you?"
ELSE
print "Goodbye"
ENDIF

CASE OF OTHERWISE ENDCASE

This structure is used when there are many possible outcomes to a condition. For instance, to
extend the above example, suppose you wanted the program to print a different message
depending on the value of a variable, xː

CASE x OF
1 : PRINT "Hello"
2 : PRINT "How are you?"
3 : PRINT "I am fine"
4 : PRINT "Have a good day!"

OTHERWISE
PRINT "Goodbye"
ENDCASE

In this example if x = 1 then we print "Hello", if x =2 then "How are you?", if x = 3 then "I am
fine." or if x = 4 then we print "Have a good dayǃ". If x is equal to anything else then we print
"Goodbye".

3) Iteration: In this a task (one or more steps) is repeated more than once. In programming
languages, an iteration pattern is implemented using loops.

LOOPS: A loop is a sequence that gets executed several times. A complete execution of a
sequence is called an iteration of the loop. There are two main loop constructs - WHILE and
FOR.

WHILE condition
sequence
ENDWHILE

The sequence is executed as long as the condition is True. The loop terminates when the
condition is False.

FOR range of iteration


sequence
ENDFOR
The phrase range of iteration specifies the beginning and the end of the iteration. Here are some
examples:
FOR each element in list

FOR each month of the year

FOR i = 1 to 10

You can use a WHILE loop and a FOR loop interchangeably. But normally you use a FOR loop
when you know the exact number of iterations of the loop. You use a WHILE loop when the
number of iterations is not known a priori. You can also nest one loop inside another or a
conditional inside a loop or vice versa. It is best to indent your pseudocode to delineate your
blocks of code.

Iteration is used when we need to repeat a block of code. We can make a code block repeat either
for a given number of repetitions or continuously either for as long as a condition continues to be
true or until a condition becomes true.

FOR TO NEXT

The FOR loop is used to repeat code for a given number of repetitions. We specify a counter
variable and set it to an initial value and then specify an end value. After every iteration of the
loop the counter variable is automatically incremented by 1. In the following example x starts at
1 and increases by 1 every time the code repeats until it reaches a value of 10, then the loop will
terminate.

FOR x = 1 TO 10
print x
NEXT

REPEAT UNTIL

A REPEAT loop will repeat the code block until the given condition is true. The condition is not
checked until after the code has run once, so regardless of whether the condition is true or not the
code will always run at least once. The following example will continue to take user input until
the user inputs a value less than 10. This structure is often used for validation checks.

REPEAT
INPUT x
UNTIL x < 10
WHILE DO ENDWHILE

In a WHILE loop the code block will run, and continue to run, until the given condition is no
longer true. A WHILE loop is similar to the REPEAT loop in that it decides when to terminate
based on a condition. However the while loop checks the condition prior to running the first
time. If the condition is not true then the code block will never run.

The below example is also used for input validation.

INPUT x
WHILE x < 10
INPUT x
ENDWHILE
Infinite loops

Condition-controlled loops can result in intentional or unintentional infinite loops. If we wanted


to loop indefinitely, we could set a condition that would never be met, thus iterating infinitely.
The following examples would result in an infinite loop:

WHILE:

count = 1
while count <>0:
print(count)
count +=1

DO WHILE:

count = 1
do
print(count)
count+=1
while count <>0

REPEAT UNTIL:

count = 1
repeat
print(count)
count+=1
until count =0

It is important to check that the conditions we set can be met if we wish them to be.

Trace Tables for Algorithms

A trace table is a technique used to test algorithms, in order to make sure that no logical errors
occur whilst the algorithm is being processed.

A trace table simulates the flow of execution. Statements are executed step by step, and the
values of variables change as an assignment statement is executed.

Trace tables are typically used by novice programmers to them visualize how a particular
algorithm or program works.

Hand tracing or 'dry running' allows you to use a trace table to

 see what code will do before you have to run it


 find where errors in your code are
Writing Algorithms – Using Trace Tables
 Dry running of flowcharts/pseudo code is basically a technique to:
• determine the output for a known set of data to check the flowchart/pseudocode carries out
the task correctly,
• check on the logic of the algorithm,
• determine the function of the algorithm.

When dry running a flowchart/pseudocode it is advisable to draw up a trace table showing how
variables change their values at each stage in the algorithm. The advantages of doing this are:

• If you make a mistake, it is easier to back track to where the error occurred rather than
starting from the beginning again.
• There is less chance of an error being made.
• It encourages a more logical approach.

A trace table has a column for each variable, usually in the order in which their values are first assigned,
and a column for OUTPUT. We leave unchanged values blank. Start a new line when you would need to
write over a value then continue on this line.

 Example with flowchart


START

Number ← 0
Total ← 0
Count ← 0

INPUT
Number

Number < 0? yes

no
no
OUTPUT
Total ← Total + Number Total

Count ← Count + 1

Count < 0?

yes

STOP

Number Total Count OUTPUT


0 0 0 Variables are initialised with these values
5 5 1 Start a new line as number changes to 5.
6 11 2
0 11 3
-9 11 Number is less than 0 so Total is OUTPUT

Example with pseudocode


sum ← 0
INPUT number
WHILE number != 0 DO
sum = sum + number
INPUT number
ENDWHILE
OUTPUT sum

sum number OUTPUT


0 12 Variable ‘sum’ is initialised with value 0, 12 is input
12 23 First iteration
35 34 Second iteration
69 0 69 Number is 0 so sum is OUTPUT

Taking a program like the one below we need to keep track (trace) all the variables and outputs.
Dim y as integer = 3
For x = 1 to 4
y = y + x
Loop
Console.writeline(y)

To do this we create a trace table:

y x output

3 1

4 2

6 3

9 4

13 13

Example: given the following Pseudo-code and Algorithm


1. Number = 3
2. PRINT number
3. FOR I from 1 to 3
4. number = number +5
5. PRINT number
6. PRINT “?”

Our trace table to understand the Pseudo code would look like:

You might also like