Module1 - Intro To Prog Paradigm
Module1 - Intro To Prog Paradigm
COURSE CODE:
(COS201)
COURSE LECTURERS
First Semester
2024/2025 Session
Outline
Introduction to Computer Programming
Definition of Programming
Programming Languages
Importance of Learning Programming
Overview of Programming Paradigms:
Procedural Programming
Functional Programming
Declarative Programming
Logic Programming
Scripting Languages
First Assignment
2
Computer Programming
The art of writing computer programs using a particular programming
3
Programming Languages
A programming language is a set of rules that provides a way of telling a computer what
operations to perform.
Programming languages can be broadly categorized into several types, including:
Low-level languages: These languages are close to the hardware and provide direct
control over computer hardware resources. Examples include assembly language and
machine code.
High-level languages: These languages are designed to be closer to human language,
making it easier for programmers to write and understand code. Examples include Python,
Java, C++, and C.
Scripting languages: These languages are often used for automating tasks, writing
scripts, and web development. Examples include Python, Ruby, and Perl.
Domain-specific languages (DSLs): These languages are tailored to specific domains or
applications, such as SQL for database queries, HTML/CSS for web development, and
MATLAB for scientific computing.
4
Importance of Learning Programming
1. Problem-Solving Skills
It teaches how to break complex problems into smaller, manageable tasks that can be solved
step by step.
2. Career Opportunities
The demand for programming skills in industries like technology, finance, healthcare, and
education is growing rapidly. Knowledge of programming languages opens the door to
various career paths such as software development, data science, artificial intelligence, and
system administration.
3. Automation and Productivity
By learning programming, you can automate repetitive tasks, increasing productivity and
efficiency.
4. Innovation and Creativity
Programming allows you to build innovative solutions and applications. Whether it's a
mobile app, a website, or a game, programming gives you the tools to bring creative ideas to
life.
5. Interdisciplinary Applications
Programming is not limited to computer science alone. It can be applied in various fields
such as biology (bioinformatics), physics (simulations), and economics (financial
modeling).
5
Programming Paradigms
A programming paradigm refers to a style or way of
thinking about programming problems and
structuring solutions.
Different paradigms offer different approaches to
solving problems, each with its strengths and use
cases.
Understanding various paradigms helps a programmer
choose the best tools for specific tasks.
6
Programming Paradigms
Programming paradigms are categorized into:
1. Procedural Programming;
2. Functional Programming;
3. Declarative Programming;
4. Logic Programming; and
5. Scripting Languages.
7
Procedural Programming
Definition: Procedural programming is a paradigm centered on the concept of
procedure calls or routines. Programs are structured as a sequence of instructions or steps
that modify data.
Key Concepts:
Functions/Procedures: Reusable blocks of code that perform specific tasks.
Control Structures: Conditional statements (if-else) and loops (for, while) that
control the flow of the program.
Data and State: Data is stored in variables, and procedures operate on this data.
9
Functional Programming
Definition: Functional programming treats computation as the evaluation of
mathematical functions and avoids changing state or mutable data.
Uses functions as the fundamental building blocks of programs. Functions in this paradigm
avoid side effects and focus on return values.
Key Concepts:
Pure Functions: Functions that always return the same result given the same input and have no side
effects.
Immutable Data: Data is not modified after it's created; new data structures are created instead.
Higher-Order Functions: Functions that take other functions as arguments or return functions as
results.
Recursion: Functions that call themselves, commonly used for looping in functional programming.
Use Cases: Beneficial for tasks requiring parallelism, data transformations, and
situations where side effects (changes in state) need to be avoided.
10
Functional Programming Example
Summing a List in Haskell
sumList :: [Int] -> Int
sumList [] = 0
sumList (x:xs) = x + sumList xs
main = print (sumList [1, 2, 3, 4, 5]) -- Output: 15
11
Functional Code Explanation
This line specifies the type signature of the function sumList.
sumList takes a list of integers ([Int]) as input and returns an integer (Int), which will be
the sum of the integers in the list.
This line defines the base case for the recursion.If the input list is empty ([]), the sum is
0. This is because the sum of no numbers is zero.
This line handles the case where the list is not empty.
The expression (x:xs) is a pattern that matches a list where x is the first element (head)
and xs is the rest of the list (tail).
The function adds x (the first element) to the result of sumList xs, which recursively calls
sumList on the remaining elements of the list.
The main function serves as the entry point for the program.It calls sumList with the list
[1, 2, 3, 4, 5] and prints the result.The expected output is 15, as the sum of these numbers
is indeed 15.
12
Declarative Programming
Definition: Declarative programming is a paradigm where the programmer specifies
what the program should accomplish, without explicitly defining how it should be done.
The emphasis is on the result rather than the process.
Key Concepts:
Statements vs. Instructions: Declarative programs consist of high-level statements
that describe the desired output.
Data-Driven: Focuses on relationships between data rather than on the control flow
of the program.
Examples of Declarative Languages: SQL (for database queries), HTML (for web
structure), CSS (for web styling).
Use Cases: Declarative programming is best suited for domain-specific problems, such
as querying databases, configuring user interfaces, or managing large datasets.
13
Declarative Programming Example
Suppose we have a database table called Employees with the following columns: id, name, department,
and salary. Here’s how you can use SQL to perform various tasks declaratively.
INSERT INTO Employees (name, department, salary) VALUES ('Jane Doe', 'Marketing', 60000);
This SQL statement inserts a new employee into the Employees table. You specify what data to insert without
detailing how the insertion is carried out.
Key Concepts:
Facts: Statements about what is true in the problem domain.
Rules: Logical assertions that define relationships between facts and how new facts
can be derived.
Queries: The user poses questions, and the system uses facts and rules to generate
answers.
Use Cases: Logic programming is ideal for tasks that involve knowledge representation,
natural language processing, and expert systems (e.g., medical diagnosis systems).
15
Logic - Prolog Example
% Facts: define relationships
parent(john, mary).
parent(mary, susan).
parent(mary, james).
parent(susan, tom).
16
Logic Explanation
Facts:
parent(john, mary). means "John is the parent of Mary."
These facts define known relationships in the family tree.
Rules:
grandparent(X, Y) defines that X is a grandparent of Y if X is the parent of Z
and Z is the parent of Y.
sibling(X, Y) defines that X and Y are siblings if they share a parent and are
not the same person.
Query:
You ask Prolog questions (queries) like ?- grandparent(X, tom)., which
asks, "Who is a grandparent of Tom?" Prolog will use the facts and rules to
find that mary is the grandparent of tom.
17
Scripting Languages
Definition: Scripting languages are often interpreted rather than compiled and are
typically used to automate tasks, interact with other software, or manipulate system-level
operations. Scripts are generally shorter and simpler than programs written in other
languages.
Key Concepts:
Interpreted Execution: Scripting languages are often executed line by line, which
makes them well-suited for rapid development and testing.
Automation and Integration: Scripts are commonly used to automate repetitive
tasks or integrate different software systems.
Dynamic Typing: Variables in scripting languages are usually not required to be
declared before use.
Examples of Scripting Languages: Python, JavaScript, Bash, PHP.
Use Cases: Scripting languages are widely used for web development (e.g., JavaScript for
client-side interaction), system administration tasks (e.g., Bash scripts), and rapid
prototyping.
18
Scripting Languages Example
# Script to read numbers from a file and calculate their sum
def read_numbers_from_file(filename):
"""Read numbers from a file and return a list of integers."""
with open(filename, 'r') as file:
numbers = [int(line.strip()) for line in file]
return numbers
def main():
filename = 'numbers.txt' # Assume this file contains a list of numbers
try:
numbers = read_numbers_from_file(filename)
total_sum = sum(numbers) # Calculate the sum of the numbers
print(f"The sum of the numbers in {filename} is: {total_sum}")
except FileNotFoundError:
print(f"Error: The file {filename} was not found.")
except ValueError:
print("Error: Please ensure all lines in the file contain valid integers.")
if __name__ == "__main__":
main()
19
Scripting Explanation
Interpreted Execution:
This script can be executed directly without the need for compilation, typical of scripting
languages.
File I/O:
The script reads from a file (numbers.txt) which is a common task in scripting to handle
data manipulation.
High-Level Abstractions:
The use of functions like open(), read(), and sum() demonstrates the ease of performing
operations without dealing with lower-level details.
Error Handling:
The script includes basic error handling using try-except blocks to manage common
issues like missing files or invalid data formats.
Automation of Tasks:
This script automates the process of reading data, calculating the sum, and printing the
result, demonstrating the primary purpose of scripting languages.
20
Module Summary
This module provides students with a foundational
understanding of different programming paradigms,
each of which offers a unique way to think about and
solve programming problems.