0% found this document useful (0 votes)
26 views21 pages

Module1 - Intro To Prog Paradigm

Uploaded by

ayomikun569
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)
26 views21 pages

Module1 - Intro To Prog Paradigm

Uploaded by

ayomikun569
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/ 21

COMPUTER PROGRAMMING I

COURSE CODE:
(COS201)

COURSE LECTURERS

1 Dr. Olaniyan Deborah


2 Dr. Julius Olaniyan

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

language like Python, Java, C++, etc.


 Computer programming is the process of designing and building

executable computer programs to accomplish a specific task or set of tasks.


 It involves writing instructions, known as code, using a programming

language that a computer can understand and execute.


 Computer programs are written by computer programmers

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.

 Examples of Procedural Languages: C, Pascal, Python (can be used procedurally).

 Use Cases: Procedural programming is suited for straightforward, step-by-step problem-


solving like simple calculations, file handling, and system scripts. 8
Procedural Programming Example
public class SumArray {

// Function to calculate the sum of an array


public static int calculateSum(int[] arr) {
int sum = 0; // Variable to hold the sum
for (int i = 0; i < arr.length; i++) {
sum += arr[i]; // Add each element to the sum
}
return sum; // Return the final sum
}

public static void main(String[] args) {


// Declare and initialize an array of integers
int[] numbers = {10, 20, 30, 40, 43, 77};

// Call the function and store the result


int sum = calculateSum(numbers);

// Print the sum


System.out.println("The sum of the array elements is: " + sum);
}
}

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.

 Examples : Haskell, Lisp, Scala, Python

 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.

 SELECT * FROM Employees; Retrieve all employees

 SELECT name, salary FROM Employees WHERE department = 'Sales';


 This query retrieves only the name and salary columns for employees who belong to the "Sales" department. It
specifies the condition in a declarative way without detailing how the database engine should process the data.

 SELECT department, AVG(salary) AS average_salary FROM Employees GROUP BY department;


 Here, you’re asking the database to calculate the average salary for each department. The GROUP BY clause
specifies how to group the data, but again, you do not detail how the database should execute this operation.

 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.

 UPDATE Employees SET salary = salary * 1.10 WHERE department = 'Sales';


 This query updates the salary of all employees in the "Sales" department by increasing it by 10%. Again, it
specifies what needs to change (the salary) without detailing how to perform the update. 14
Logic Programming
 Definition: Logic programming is based on formal logic. In this paradigm, the
programmer defines facts and rules about a problem domain, and the program derives
the solution through logical inference.

 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.

 Example of a Logic Language: Prolog.

 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).

% Rules: define family relationships


grandparent(X, Y) :- parent(X, Z), parent(Z, Y).
sibling(X, Y) :- parent(Z, X), parent(Z, Y), X \= Y.

% Query: who is a grandparent of tom?


% ?- grandparent(X, 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.

Understanding these paradigms will allow students to


select the most appropriate approach for the tasks they
will encounter throughout their programming
journey.
21

You might also like