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

PROGRAMMING

The document discusses algorithms for calculating Fibonacci series and factorials. It describes the steps involved in writing and executing a program, including defining the problem, planning the solution, coding, testing and documenting. Programming paradigms like procedural, object-oriented and event-driven are also explained.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

PROGRAMMING

The document discusses algorithms for calculating Fibonacci series and factorials. It describes the steps involved in writing and executing a program, including defining the problem, planning the solution, coding, testing and documenting. Programming paradigms like procedural, object-oriented and event-driven are also explained.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

Pearson Higher Nationals in

Computing
Unit 01: Programming
Assignment 01

1 | Page W.H.M.A.D. Dharmadasa Programming Assignment No. 01


Table of Contents
Table of Contents............................................................................................................................2
ACTIVITY 01..................................................................................................................................4
1.1 What is an “Algorithm”................................................................................................4
1.2 What are the characteristics of a good algorithm..............................................................4
1.3 Algorithms to display Fibonacci series and Factorial value..............................................6
1.3.1 Algorithm for Fibonacci series......................................................................................6
1.3.2 Algorithm for Factorial value.......................................................................................6
1.4 Steps involved in the process of writing and executing a program..................................7
1.5 Analysis of writing the code phase.......................................................................................9
1.5.1 Challenges faced when writing the code phase............................................................9
1.6 Sample dry run for designed algorithms...........................................................................11
1.6.1 Fibonacci series.............................................................................................................11
1.6.2. Factorial Value............................................................................................................11
1.7 Big-O notation.....................................................................................................................12
1.7.1. What is Big-O notation...............................................................................................12
1.7.2. How Big-O notation helps to evaluate algorithm efficiency....................................12
1.8 Python codes for Fibonacci series and Factorial value....................................................14
1.8.1. Fibonacci Series...........................................................................................................14
1.8.2. Factorial Value............................................................................................................14
1.8.3. Evaluation the efficiency of above codes using Big-O notation..............................15
ACTIVITY 2..................................................................................................................................16
2.1 Programming Paradigms...................................................................................................16
2.1.1 What is a Programming Paradigm.............................................................................16
2.2. Characteristics of some programming paradigms..........................................................17
2.2.1 Procedural Programming Paradigm..........................................................................17
2.2.2 Object Oriented Programming Paradigm.................................................................19
2.2.3. Event Driven Programming Paradigm.....................................................................23

2 | Page W.H.M.A.D. Dharmadasa Programming Assignment No. 01


Figure 1 Different Programming Paradigms.....................................................................15

3 | Page W.H.M.A.D. Dharmadasa Programming Assignment No. 01


ACTIVITY 01

1.1 What is an “Algorithm”

According to the Oxford English Dictionary the word “Algorithm” is defined as


follows,

A process or set of rules to be followed in calculations or other problem-


solving operations, especially by computers.

1.2 What are the characteristics of a good algorithm.

 Well – described steps:


Algorithms consist of a clear and precise series of instructions or steps that can
be followed to carry out a given activity or resolve an issue. Every step should be
crystal clear, with no space for doubt or uncertainty.

 Efficiency:
Algorithms aim to maximize efficiency in terms of resources and time. Their
objective is to resolve problems or do tasks in a reasonable amount of time while
making the most use of computational resources like memory, processing power,
or garage.

4 | Page W.H.M.A.D. Dharmadasa Programming Assignment No. 01


 Correctness:
An algorithm's design must ensure that it generates accurate results for all valid
inputs falling within its domain. They must correctly resolve any issue for which
they may have been created, and the results they provide must correspond to the
expected outcomes.

 Modularity and reusability:


Algorithms have the potential to be modular, which allows them to be broken
down into more manageable subproblems or features that can be applied to
different sections of the algorithm or to other algorithms. This encourages code
reuse, maintainability, and agency.

5 | Page W.H.M.A.D. Dharmadasa Programming Assignment No. 01


1.3 Algorithms to display Fibonacci series and Factorial value.

1.3.1 Algorithm for Fibonacci series.

function fibonacci(n)
if n <= 1
return n
else
a=0
b=1
print a
print b
for i from 2 to n
c=a+b
print c
a=b
b=c

1.3.2 Algorithm for Factorial value.

function factorial(n)
if n <= 1
return 1
else
result = 1
for i from 2 to n
result = result * i
return result.

6 | Page W.H.M.A.D. Dharmadasa Programming Assignment No. 01


1.4 Steps involved in the process of writing and executing a
program.

1. Defining the process:


Let's say that you are contacted as a programmer because someone needs
your help. You meet with a systems analyst who discusses the project, or
you meet with users from the client organization to examine the issue.
Determining what you already know (the input data) and what you wish to
get (the result) is the specific task of describing the problem. In the end, you
create a formal contract that details the necessary input, processing, and
output, among other things. This is not an easy procedure.

2. Planning the solution:


Making a flowchart and writing pseudocode are two popular methods for
organizing a problem's solution—or maybe both. A flowchart is essentially
a visual depiction of a problem's step-by-step solution. It is made up of
boxes and other symbols that stand in for activities, and arrows that indicate
the program's path. It serves as a blueprint for the tasks and methods that
your program will carry out. A set of standard symbols for flowcharts has
been produced by the American National Standards Institute (ANSI).

3. Coding the problem:


The next task for the programmer is to write the program's code, or to
translate your solution into a programming language. The reasoning in the
flowchart, pseudocode, or other tool will be translated into a programming
language by you. A programming language is a collection of rules that
gives the computer instructions on what operations to carry out, as we have
already mentioned. There are numerous programming languages; a few of
them are C, C#, C++, Python, Java. One or more of these might come up in
your work. Later in this chapter, we will go over the various linguistic
varieties in more detail.

7 | Page W.H.M.A.D. Dharmadasa Programming Assignment No. 01


4. Testing the program:
Certain experts maintain that if a program is well-designed, it may be
programmed correctly from the start. They also claim that there are
mathematical methods for demonstrating the correctness of a program. But
since the world is still not flawless, most programmers learn to accept that
their freshly built programs will likely contain a few bugs. At first, this is a
little depressing because programmers are typically exact, cautious, detail-
oriented individuals who take pride in their work. Nevertheless, there are
plenty of opportunities for errors to be introduced into programs, and you
will almost certainly uncover a few, just like many who came before you.

5. Documenting the program:


Although you may be anxious to explore more interesting computer-
centered tasks, as many programmers are, documentation is a constant and
required effort. Written descriptions of the programming cycle and
particular program details are called documentation. Program listings, data-
record descriptions, flowcharts, pseudocode, the nature and cause of the
problem, a brief narrative description of the program, and the results of
testing are examples of typical program documentation items. Program
comments are also regarded as an integral component of the documentation.
While they code, many programmers also document. Program
documentation can, more broadly speaking, be a component of system
documentation.

8 | Page W.H.M.A.D. Dharmadasa Programming Assignment No. 01


1.5 Analysis of writing the code phase

1.5.1 Challenges faced when writing the code phase.

1. Identifying the problem:


It can occasionally be difficult to understand the needs of the challenge,
particularly if they are complex or poorly stated.

2. Algorithm Design:
Designing an efficient algorithm can be tricky, especially for complex
problems. It requires critical thinking and problem-solving skills.

3. Translating algorithm to code:


Converting the algorithm into actual code can be challenging, especially for
beginners. Syntax errors, logical errors, and bugs are common at this stage.

4. Debugging:
Identifying and fixing errors (bugs) in the code can be time-consuming. It
requires good debugging skills and patience.

5. Choosing the suitable data structures:


Selecting the appropriate data structures and algorithms for the problem at
hand is crucial for efficient and scalable solutions.

6. Testing and validation:


Testing the program thoroughly to ensure it works as expected under various
scenarios can be challenging. It requires designing comprehensive test cases
and handling edge cases.

9 | Page W.H.M.A.D. Dharmadasa Programming Assignment No. 01


7. Optimization
Optimizing the code for performance and memory usage can be challenging,
especially for large-scale or resource-constrained applications.

8. Documentation and code readability:


Writing clear and concise documentation and maintaining readable code can
be challenging but is essential for code maintainability and collaboration.

9. Version Control:
Managing code changes, collaborating with team members, and resolving
conflicts in version control systems like Git can be challenging, especially for
large projects with multiple contributors.

10 | Page W.H.M.A.D. Dharmadasa Programming Assignment No. 01


1.6 Sample dry run for designed algorithms.

1.6.1 Fibonacci series

function fibonacci(n)
if n <= 1
return n
else
a=0
b=1
print a // Iteration 1: 0
print b // Iteration 1: 1
for i from 2 to n
c=a+b
print c // Iteration 2: 1
// Iteration 3: 2
// Iteration 4: 3
// Iteration 5: 5
a=b
b=c

when n=5;
fibonacci 5 = 0,1,1,2,3,5

1.6.2. Factorial Value

function factorial(n)
if n <= 1
return 1
else
result = 1
for i from 2 to n
result = result * i
return result

when n=5;
result = 5*4*3*2*1 = 120

11 | Page W.H.M.A.D. Dharmadasa Programming Assignment No. 01


1.7 Big-O notation.

1.7.1. What is Big-O notation.

Big O notation is a mathematical notation used in computer science to describe the


upper bound or worst-case scenario of the runtime complexity of an algorithm in terms
of the input size. It provides a standardized and concise way to express how the
performance of an algorithm scales as the size of the input grows.

In simpler terms, Big O notation helps us understand how an algorithm's efficiency


changes as the amount of data it processes increases. It focuses on the dominant factor
influencing an algorithm's runtime, ignoring constant factors and lower-order terms.
This makes it a powerful tool for comparing and analyzing algorithms without getting
bogged down in implementation details.

1.7.2. How Big-O notation helps to evaluate algorithm efficiency.

 Standardized Comparison:
Big-O notation allows us to compare the efficiency of different algorithms
independently of the hardware or software environment. It provides a
standardized way to assess and compare algorithms based on their scalability.

 Focus on growth rate:


Big-O notation focuses on the growth rate of the algorithm's resource usage
(time or space) as the size of the input increases. It helps in understanding how
an algorithm performs as the input size becomes very large.

 Identify dominant terms:


The dominating terms in the algorithm's complexity function can be found with
the use of Big-O notation. It captures the most important element that adds to the
overall efficiency of the algorithm.

12 | Page W.H.M.A.D. Dharmadasa Programming Assignment No. 01


 Predicting performances:
By analyzing the Big-O notation of an algorithm, we can make predictions about
its performance for large input sizes. Algorithms with lower order complexities
(e.g., O(log n), O(n)) generally perform better than those with higher order
complexities (e.g., O(n^2), O(2^n)) for large inputs.

 Optimization Guidance:
Gaining knowledge of an algorithm's Big-O notation might help identify possible
areas for optimization. It assists in pinpointing the algorithmic components that
are primarily responsible for the overall inefficiency of the system, directing
programmers in the optimization of crucial code segments.

 Algorithm Selection:
Big-O notation assists in selecting the most suitable algorithm for a given
problem based on its complexity requirements. For example, if real-time
performance is crucial, algorithms with lower time complexity (e.g., O (log n),
O(n)) may be preferred over those with higher time complexity (e.g., O(n^2),
O(2^n)).

13 | Page W.H.M.A.D. Dharmadasa Programming Assignment No. 01


1.8 Python codes for Fibonacci series and Factorial value

1.8.1. Fibonacci Series

def fibonacci(n):
if n <= 1:
return n
else:
a, b = 0, 1
fib_series = [a, b]
for i in range(2, n+1):
c=a+b
fib_series.append(c)
a, b = b, c
return fib_series

# Test the Fibonacci function


print ("Fibonacci Series:", fibonacci(5))

1.8.2. Factorial Value

def factorial(n):
if n <= 1:
return 1
else:
result = 1
for i in range(2, n+1):
result *= i
return result

# Test the factorial function


print("Factorial:", factorial(5))

14 | Page W.H.M.A.D. Dharmadasa Programming Assignment No. 01


1.8.3. Evaluation the efficiency of above codes using Big-O notation.

 Fibonacci series
The time complexity of the Fibonacci series algorithm implemented above is
O(n), where 'n' is the input number. This is because each number in the
Fibonacci series is calculated by adding the previous two numbers, and the
algorithm iterates 'n' times to generate the series.

 Factorial value
The time complexity of the factorial algorithm implemented above is also O(n),
where 'n' is the input number. This is because the algorithm iterates 'n' times,
multiplying each iteration by the current value of 'result'.

Because both algorithms have linear time complexity, the size of the input has a
linear effect on how long they take to execute. They are therefore effective with
modest to moderate input sizes. Their efficiency, however, may become a
bottleneck for very large inputs when contrasted to algorithms with smaller
complexities, such O(log n) or O(1).

15 | Page W.H.M.A.D. Dharmadasa Programming Assignment No. 01


ACTIVITY 2

2.1 Programming Paradigms

2.1.1 What is a Programming Paradigm.

The term Programming Paradigm can be defined as


“A way or style of programming”

There are several types of programming paradigms,


 Imperative
 Declarative
 Structured
 Procedural
 Functional
 Object – Oriented
 Event – driven.
 Flow – driven
And many other paradigms.

Figure 1 Different Programming Paradigms

16 | Page W.H.M.A.D. Dharmadasa Programming Assignment No. 01


2.2. Characteristics of some programming paradigms.

2.2.1 Procedural Programming Paradigm

This paradigm places a strong emphasis on process using the underlying machine
concept. The imperative approach and the procedural approach are identical. Reusing the
code was a benefit at the time it was in use because it allowed for code reuse.

Advantages of Procedural Programming

 Versatility:
With the flexible paradigm of procedural programming, developers can design
coding projects that achieve a wide range of objectives. There is probably a
procedural programming language that you may use to achieve your objectives, as
these languages are made for a wide range of development tasks, such as software
and web development.

 Simplicity:
One comparatively easy method of programming computers is procedural
programming. Because procedural programming languages offer a basis for
coding that can be applied to other languages, including object-oriented
languages, this is the reason that many developers begin their work with them.

 Accessibility:
Procedural programming is used by many popular programming languages,
therefore learning them can be facilitated by a wealth of resources for a
prospective developer. This can hasten your progress by providing access to both
free and paid online communities and resources that you can use when faced with
obstacles.

17 | Page W.H.M.A.D. Dharmadasa Programming Assignment No. 01


Disadvantages of Procedural Programming

 Complexity:

When trying to construct sophisticated programs, procedural programming


languages' simplicity can present a problem. For increasingly complex
applications, selecting a language with an object-oriented approach is frequently
simpler.

 Troubleshooting:
Finding the source of mistakes in your code can be difficult in procedural
programming languages because of the usage of global data. This may result in a
difficult debugging procedure that extends the time allotted for development.

 Strict data types:


Programming languages that use procedures allow for immutable data. In contrast
to the neighboring option in other languages, this implies you cannot alter its
structure or functionality after it has been created, which can be restrictive.

Example code snippet,

num = int(input("Enter any Number: "))

fact = 1 # Initialize factorial variable

# Calculate factorial
for i in range(1, num + 1):
fact = fact * i

# Print the factorial


print("Factorial of", num, "is:", fact)

18 | Page W.H.M.A.D. Dharmadasa Programming Assignment No. 01


Relationship of above code snippet with procedural programming paradigm

 Sequential Execution:
The steps in the code are organized in a linear fashion. It first requests input from
the user, uses a loop to calculate the factorial, and then outputs the result. This
sequential flow reflects the procedural paradigm's focus on doing things step-by-
step.

 Procedures / Functions:
This little piece of code exemplifies the idea of segmenting a program into more
manageable, reusable code parts, even if it doesn't specifically define any distinct
procedures or functions. It would be simple to put the factorial computation within
a function, as is frequently done in procedural programming.

 No emphasis on encapsulation and inheritance:


Encapsulation and inheritance are key ideas in object-oriented programming,
although they are not stressed in procedural programming. This little piece of code
doesn't illustrate inheritance or polymorphism, nor does it define any classes or
objects.

2.2.2 Object Oriented Programming Paradigm.

The program is written as a set of objects and classes designed to be used together for
communication. Objects are the smallest and most fundamental entities, and they are the
sole subjects of all computations. Data is given more weight than process. It is capable
of handling nearly any type of real-world issue that arises nowadays.

19 | Page W.H.M.A.D. Dharmadasa Programming Assignment No. 01


4 principles of Object-Oriented programming

 Encapsulation:
Encapsulation is the process of enclosing data inside an object. Encapsulation
creates a wall around data in OOP to keep it safe from the rest of the code. By
incorporating the data and its functions into a class, encapsulation can be
accomplished. This action only reveals the functionality required to interface with
a class; it hides all other features. A class is considered well-encapsulated when it
prevents direct access to its private data.

 Abstraction:
Abstraction is the process of accessing objects through simpler classes as opposed
to intricate implementation code. It's usually easier to write programs when you
can keep a class's interface and implementation distinct. Through the class
member functions in object-oriented programming, you can abstract the
implementation details of a class and provide a clear, user-friendly interface. In
the event of an error, the change only impacts the implementation details of a
class and not the outside code thanks to abstraction, which helps to isolate the
impact of code modifications.

 Inheritance:
Because inheritance is supported by most object-oriented languages, a new class
inherits its parent class's functions and attributes by default. Classes can be
arranged hierarchically thanks to inheritance, where a class may have one or more
parent or child classes. A class is said to have inherited its parent's properties if it
has a parent class. The behavior of the parent class can also be expanded upon or
changed by the child class. You can reuse code through inheritance without
having to redefine a child class's functionalities.

20 | Page W.H.M.A.D. Dharmadasa Programming Assignment No. 01


 Polymorphism:
The creation of objects having shared behaviors is referred to as polymorphism.
Polymorphism in OOP enables classes to be treated consistently in a hierarchy.
Any objects created by a child class inside the hierarchy have the same functions
when you write code for objects at the base of the hierarchy. An object may
behave differently depending on what kind it is.

Advantages of Object – Oriented Programming

 Reusable Code:
OOP's inheritance principle enables you to reuse code without having to write it
from scratch. When writing code, this feature can help to decrease errors.

 Increased productivity:
When developing new software, you can save time by constructing objects from
classes. Libraries and reusable code are other tools you can utilize to boost
productivity.

 Enhanced Security:
Encapsulation and abstraction are useful techniques for revealing sensitive
information while displaying a limited amount of data. When creating
sophisticated code, these features can offer increased security.

21 | Page W.H.M.A.D. Dharmadasa Programming Assignment No. 01


Example code snippet

class Signup:
def __init__(self):
self.userid = 0
self.name = ""
self.emailid = ""
self.sex = ""
self.mob = 0

def create(self, userid, name, emailid, sex, mob):


print("Welcome to ESOFT\nLets create your account\n")
self.userid = 132
self.name = "Radha"
self.emailid = "[email protected]"
self.sex = 'F'
self.mob = 900558981
print("your account has been created")

if __name__ == "__main__":
print("Hello!")
s1 = Signup()
s1.create(22, "riya", "[email protected]", 'F', 89002)

22 | Page W.H.M.A.D. Dharmadasa Programming Assignment No. 01


Relationship of above code snippet with Object - Oriented programming paradigm

 Class definition:
The attributes and actions pertaining to user sign-up capabilities are contained in
the Signup class. It describes characteristics that indicate a user account's status,
such as userid, name, emailid, sex, and mob.

 Constructor method(__init__):
The class's constructor is the __init__ function. When an instance of the class is
created, it initialises all of the attributes (userid, name, emailid, sex, and mob) to
their default values.

 Encapsulation:
The class combines functionality (methods) and data (attributes) into a single
entity. Encapsulation reveals only the methods required to interact with an object,
while concealing its internal state. Here, the create method abstracts away the
implementation specifics and offers an interface for making a user account.

2.2.3. Event Driven Programming Paradigm.

A programming paradigm known as "event-driven programming" bases a program's


execution on external events, such as messages or user actions. Asynchronous and
responsive behavior—often observed in distributed systems and GUI applications—is
made possible by programmers’ ability to react to inputs with predetermined actions.

23 | Page W.H.M.A.D. Dharmadasa Programming Assignment No. 01


Advantages of Event driven programming

 Enables asynchronous processing, optimizing resource utilization and


responsiveness, crucial for real-time applications and user interfaces.
 promotes the reuse of code and encourages the division of responsibilities to
facilitate maintenance and scalability through modular code design.
 Events are used by components to interact with one another, which lowers
dependencies and increases system flexibility and facilitates maintenance and
modification.

Disadvantages of Event driven programming

 Because event-driven systems are asynchronous, it might be difficult to pinpoint


mistakes in them, which makes debugging them difficult.
 Race conditions brought about by concurrent events can cause unpredictable
behaviour and complicate synchronisation and debugging.
 Inversion of control in event-driven systems can make code more difficult for
developers not familiar with the design to follow and comprehend.

24 | Page W.H.M.A.D. Dharmadasa Programming Assignment No. 01


Example code snippet
import tkinter as tk

def button_click():
label.config(text="Button clicked!")

# Create the main application window


root = tk.Tk()
root.title("Event-Driven Example")

# Create a label widget


label = tk.Label(root, text="Click the button!")
label.pack()

# Create a button widget


button = tk.Button(root, text="Click Me", command=button_click)
button.pack()

# Start the event loop


root.mainloop()

Relationship of above code snippet with Event driven programming paradigm

 Event handling:
The command argument designates the event handler that is linked to the Button
widget. In this instance, clicking the button initiates the button_click function.
This function reacts to the button click event by acting as an event handler.

25 | Page W.H.M.A.D. Dharmadasa Programming Assignment No. 01


 Event loop:
An event loop that continuously watches for events like button clicks, mouse
movements, or keyboard inputs is started by the mainloop() function. The
relevant event handler is called when an event happens.

 Responsive UI:
Responsive user interfaces can be made with event-driven programming. The
corresponding event handler is instantly activated when the user interacts with
the GUI (by, for example, clicking a button), giving the user feedback in real
time.

2.3 Relationship between Procedural, Object Oriented and


Event Driven programming paradigms.

Programming Paradigm Comparison between OOP, Event


driven and Procedural paradigms

26 | Page W.H.M.A.D. Dharmadasa Programming Assignment No. 01

You might also like