0% found this document useful (0 votes)
1 views22 pages

Imperative and Declarative Programming

The document compares imperative and declarative programming paradigms, highlighting that imperative programming focuses on step-by-step instructions while declarative programming specifies the expected outcome. It discusses examples of both paradigms, including procedural and object-oriented programming for imperative, and functional and logic programming for declarative. Additionally, it outlines the advantages and disadvantages of each approach, providing guidance on when to use them based on project requirements.

Uploaded by

sumitlone1912
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views22 pages

Imperative and Declarative Programming

The document compares imperative and declarative programming paradigms, highlighting that imperative programming focuses on step-by-step instructions while declarative programming specifies the expected outcome. It discusses examples of both paradigms, including procedural and object-oriented programming for imperative, and functional and logic programming for declarative. Additionally, it outlines the advantages and disadvantages of each approach, providing guidance on when to use them based on project requirements.

Uploaded by

sumitlone1912
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Imperative and Declarative

Programming
.
• imperative programming refers to a programming paradigm where
we provide the computer with step-by-step instructions on how to
perform a particular task.
• By contrast, declarative programming involves specifying what result
we're expecting from our code. This is mainly achieved through
special functions and tools that are provided by different frameworks
and libraries of a programming language.
• Eg. Suppose a friend of yours wants to come to your apartment
Imperative programming
• As we've said before, imperative programming involves giving the
computer a series of well-defined instructions. It is also the first
programming paradigm that is usually taught to new students.
• Because computers perform tasks in detailed and precise steps, the
imperative approach thus forces us to think more like machines than
humans.
Example
• Consider a C++ program to count even numbers in a vector. Here's
how we would write the program using imperative programming:
• Create an integer vector and initialize it with the necessary elements.
• Create an integer variable named even_numbers to store the number
of even integers.
• Run a loop and check each vector element.
• If the element is an even number, increase the value
of even_numbers by 1.
• Print even_numbers outside the loop.
• Vector is a sequential container to store elements and not index based. Array stores a fixed-size
sequential collection of elements of the same type and it is index based. Vector is dynamic in nature so,
size increases with insertion of elements. As array is fixed size, once initialized can't be resized.
• // 1. initialize vector of integers
• vector<int> numbers = {1, 2, 3, 4, 5, 8, 10, 12};
• // 2. create a variable to count even numbers
• int even_numbers = 0;
• // 3. ranged loop that iterates throughout the vector
• for (int num : numbers) {
• // 4. increase even_numbers by 1 if the vector element is e ven
• if (num % 2 == 0) {
• ++even_numbers;
•}
•}
• // 5. print even_numbers
• cout << even_numbers;
Declarative Programming

• Unlike imperative programming, the declarative paradigm relies on


supplying the expected result to the computer. We do this using
specialized functions and other pre-defined programming tools.
• Let us look at this more clearly with the same example of finding the
number of even integers in a vector.
• This time, instead of relying on step-by-step procedures, we'll simply
supply the vector and an appropriate lambda function to a standard
C++ component called the count_if algorithm. Here's the full
executable code:
• #include <iostream>
• #include <vector>
• #include <algorithm>
• using namespace std;

• int main() {
• vector<int> numbers = {1, 2, 3, 4, 5, 8, 10, 12};

• // supply vector and lambda function to count_if algorithm


• int even_numbers = count_if(numbers.begin(), numbers.end(), [](int num) {
• return num % 2 == 0;
• });

• cout << even_numbers;

• return 0;
• }
Notice the following block of code:

• int even_numbers = count_if(numbers.begin(), numbers.end(), [](int num) {


• return num % 2 == 0;});
• Here, we have supplied the entire numbers vector to count_if using
numbers.begin() and numbers.end().

• Then, we have specified what result we expect (number of even integers)


by using the following lambda expression:

• [] (int num) {return num % 2 == 0;}


• As you can see, these aren't step-by-step instructions; the entire operation
is performed in a single statement by the count_if algorithm.
• We only need to tell the algorithm what result we expect; the algorithm
then does all the processing for us.
Note
• There is always some element of imperative programming running in
the background when we use the declarative paradigm.

For example, the count_if algorithm in C++ runs an imperative code
to give us the result we've specified.

The main point here is that we don't provide the instructions to the
computer; the standard functions and tools run the instructions
themselves through pre-defined code.
Imperative vs. Declarative Programming
Imperative Programming Declarative Programming

We specify how to get the desired result by providing We specify what result we expect from the program.
detailed instructions.
Imperative programming specifies and directs the control Declarative programming specifies the expected result and
flow of the program. core logic without directing the program's control flow.

The programmer makes the major decisions about how The compiler makes the major decisions about how the
the program works. program works.
It is easy to learn and understand. The code is clean, readable, and effective.
It uses mutable variables, i.e., the values of variables can It uses immutable variables, i.e., the values of variables
change during program execution. cannot change.

Due to the use of mutable variables, imperative Declarative programming doesn't change the program's
programming often changes the program's state by state.
changing the internal data.
Procedural Programming and Object-Oriented Functional Programming and Logic Programming are
Programming are examples of imperative programming. examples of declarative programming.

C, C++, Java, PHP, JavaScript, Python, etc., are SQL, LISP, Scala, Haskell, Prolog, Absys, Alice, etc., are
programming languages that focus on the imperative programming languages that focus on the declarative
paradigm. paradigm.
Programming Paradigms of Imperative
Programming
There are two major paradigms of imperative programming that are
popular today. They are
• Procedural Programming
• Object-Oriented Programming
Procedural Programming
• This form of programming relies on giving a sequence of
well-structured commands and statements to produce a certain
result. The primary focus of procedural programming is on how the
result is derived, i.e., the procedure.
• This programming paradigm uses variables, arrays, loops, conditional
statements, and functions to perform various operations.
• Some examples of procedural programming languages are C, Basic,
Fortran, Pascal, etc.
Object oriented programming
• In this paradigm, problems are modeled in the form of classes and objects:
• Objects - They represent things we encounter in the real world, such as
employees, organizations, cars, electronics, or anything you can think of.

• Classes - They're blueprints for creating objects, i.e., they contain


everything the objects need (data in the form of variables, logic in the form
of methods/functions). This is known as encapsulation.
Thus, classes are small chunks of reusable code from which multiple
objects can be created. This makes programs written using OOP easy to
execute, modify, and debug.
• Languages like C++, Java, Python, C#, etc., are object-oriented
programming languages.
Programming Paradigms of Declarative
Programming
Similarly, the major paradigms of declarative programming are
• Functional Programming
• Logic Programming
Functional Programming
• The Functional Programming paradigm is centered around the concept of
functions. There is a special emphasis on how the function returns a value.
• The primary focus of functional programming is defining the expected result
rather than how we get the result.
• Here, programmers treat functions similar to how they treat data in variables and
constants, i.e., the functions
• can be stored in variables,
• passed as arguments to methods, and
• can be the return value of a method.
• Unlike other programming paradigms, functional programming uses conditional
statements like if-else and function recursion instead of relying on loops.
• Languages like Scala, Clojure, Haskell, Erlang, and F# are functional programming
languages.
Logic Programming
• This paradigm is based on formal logic. In Logic Programming, we use
a base of existing logic (called predicates) to build a set of facts
(called atoms).
• We then use predicates and atoms to build formulas and run queries
to display the required data.
• Logic programming is extremely useful for machine learning fields like
Natural Language Processing (NLP). They're also great for managing
and running queries on NoSQL databases.
• Prolog, Absys, Alice, ASP, etc., are logic programming languages.
Advantages of Imperative Programming

• Easy to Learn: Imperative programming is easy to learn and is often the first programming
method that is taught to beginners.

• Control Flow: We can direct the program's control flow with imperative programming.
This gives us more power to change, modify, and optimize our program.

• Visible Logic: Since imperative programming requires us to provide step-by-step


instructions, we can follow the logic of the code easily by reading the program.

• Model the Real World: Object-Oriented programming is an imperative paradigm that is


very useful for modeling real-world objects.

• Complex Applications: Procedural programming is great for small-scale projects due to its
simplicity, while Object-Oriented programming is ideal for making large and complex
software.
Disadvantages of Imperative Programming
• Difficult to Manage: Since imperative programming requires us to provide
systematic instructions, the code is much longer and is more difficult to
manage.

• Requires More Work: While pre-defined functions and objects are


available in imperative programming, we still have to do much of the work.
This includes figuring out the most efficient algorithm to perform a task,
writing code for that algorithm, and finally testing and debugging the code.

• Susceptible to Ineffient Code: Since most of the instructions are given by


the programmer, the code may become inefficient if the programmer uses
inefficient algorithms and coding methods.
Advantages of Declarative Programming
• Easy to Read and Manage: Because we use pre-defined functions or logic bases for our computations, our
programs end up short, clean, and simple.

• No Side-Effects: Declarative programming utilizes immutable variables. So there are no uncertain


side-effects in the program.

• Efficient Execution: The pre-defined functions and logic bases of declarative languages are optimized for
efficiency.

• Protects the Program from the User: The programmer has far less control over the program's internal
workings. This prevents the programmer from accidentally executing bad logic.

• Parallel Programming: Functional programming utilizes self-contained functions that don't produce any side
effects. Thus, it is very easy to run these functions concurrently, making functional programming ideal for
parallel programming.

• Database Management: Logic programming is great for running queries on NoSQL databases. SQL is also a
declarative language that runs queries on relational databases.

• Math and Logic: Functional programming utilizes lambda calculus, while logic programming utilizes formal
Disadvantages of Declarative Programming
• Difficult to Learn: Declarative languages are not beginner-friendly since they
require knowledge of some advanced programming concepts to understand.

• Cannot Model the Real World: While declarative programming is good for
databases and math/logic operations, it is not good for modeling the real world.

• Unsuitable for Large Applications: Functional programming is unsuitable for large


applications because it doesn't work well with uncertain elements such as user
input.

• Higher Memory Consumption: Programs written using the functional paradigm


often occupy more memory, thus reducing performance.
When Should We Use Imperative or Declarative
Programming?
• Use imperative programming if you want to build
• commercial applications,
• small projects for your portfolio,
• large projects that don't require too much mathematical modeling,
• and applications that require high performance, such as video games.
• By contrast, use declarative programming if you want to
• run queries on data and databases,
• use parallel programming,
• build programs that require advanced math or logic.

You might also like