Declarative vs imperative programming: 5 key differences
Hunter Johnson
Posted on July 26, 2022
Imperative and declarative programming are two of the most popular programming paradigms in software development. Programming paradigms are approaches used to categorize or classify programming languages based on techniques and features they support.
When you're starting to learn to code, you often begin by mastering constructs such as loops, functions, keywords, etc. While these are vital to learn, beginners will sometimes see less emphasis placed on applying these constructs to coding solutions and structuring them in ways that can help you with real-world problem-solving. Learning about programming paradigms can help bridge that gap.
Today we'll go over declarative and imperative programming and their differences. By the end, you should have a solid foundational grasp of both paradigms, supported by a couple of code examples.
Let’s get started!
We'll cover:
- What is imperative programming?
- What is declarative programming?
- Imperative programming vs declarative programming: 5 key differences
- Declarative vs imperative programming: Code example
- Get started with declarative and imperative programming today
What is imperative programming?
Imperative programming is the oldest and most basic programming approach. Within the imperative paradigm, code describes a step-by-step process for a program’s execution. Because of this, beginners often find it easier to reason with imperative code by following along with the steps in the process.
The step-by-step process contains individual statements, instructions, or function calls. In the programming world, this process is called the control flow.
In other words, you’re interested in how the program runs, and you give it explicit instructions. Let's illustrate this with a pseudocode example.
Say you want to build an app that returns the current weather and forecast for a given location. At a high level, you might design the app to work something like this when using an imperative approach:
Begin
Accept location from user input of either location name or ZIP code.
Call OpenWeather's Geocoding API to convert location data into geographic coordinates.
Call OpenWeather's Current Weather Data API.
Send geographic coordinates to OpenWeather.
Call OpenWeather's Daily Forecast 16 Days API.
Resend geographic coordinates.
Parse JSON returned by the APIs to extract current weather and forecast data.
Return current weather and forecast.
Display current weather and forecast to user.
End
In this simple example, imperative instructions dictate what the app should do, when to do it, and how to do it. This pseudocode is comparable to imperative programming, with which you create the logic of the program by making looping statements, calling functions, etc., all in a particular order.
Examples of imperative programming languages include:
- Java
- C
- Pascal
- Python
- Ruby
- Fortran
- PHP
Supporting both paradigms
You can actually use Python in both declarative and imperative programming. Over the years, some other imperative languages have also received updates allowing them to support declarative-style programming. These include JavaScript, C++, and C#.
C++ in particular has seen several improvements in recent years, many of which make C++ more declarative. For example, newer versions of C++ have the Standard Template Library (STL), which provides four components: algorithms, containers, functions, and iterators.
Among these components are several built-in functions or operations that were previously performed manually, such as std::sort
and std::list
. Now you can easily use std::sort
and continue coding without having to develop an imperative sorting algorithm.
The following code example demonstrates this feature at work:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int arr[] = { 7, 5, 4, 9, 0, 1, 3, 8, 2, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
/*Array before sorting*/
for (int i = 0; i < n; i++) {
std::cout << arr[i] << ", ";
}
std::cout<<endl<<endl;
/*By default, "sort" takes two parameters, the beginning of the
array and the length of the array.*/
sort(arr, arr + n);
/*Array after sorting*/
for (int i = 0; i < n; i++) {
std::cout << arr[i] << ", ";
}
return 0;
}
--->
7, 5, 4, 9, 0, 1, 3, 8, 2, 6,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
What is declarative programming?
In contrast with imperative programming, declarative programming describes what you want the program to achieve rather than how it should run.
In other words, within the declarative paradigm, you define the results you want a program to accomplish without describing its control flow. Ultimately, it’s up to the programming language's implementation and the compiler to determine how to achieve the results. This places emphasis not on the execution process, but on the results and their ties to your overall goal. In other words, writing declarative code forces you to ask first what you want out of your program. Defining this helps you develop more expressive and explicit code.
Returning to our weather app example, the pseudocode might look something like this in the declarative paradigm:
Begin
Location submitted by user is location name or ZIP code.
Location is converted into geographic coordinates.
Weather data is retrieved for geographic coordinates.
Weather data is displayed for user.
End
As shown, the pseudocode is descriptive but lacks in detail. Only the result, displaying the weather data, matters to you without regard for the process.
Examples of declarative programming languages include:
- SQL
- Miranda
- Prolog
- Lisp
- Many markup languages (e.g., HTML)
Declarative vs imperative programming: 5 key differences
Let's expand on the differences between the two programming paradigms we're discussing, using the following table for comparisons.
Declarative vs imperative programming: Code example
We’ve discussed the key differences between imperative and declarative programming. Let's look at a simple code example.
For this example, we’ll use Python. As mentioned earlier, Python can be used in both imperative and declarative programming and is one of the most popular languages today for beginners and experts alike.
Imperative programming
# Calculate total in the list
total = 0
myList = [1,2,3,4,5]
# Create a for loop to add numbers in the list to the total
for x in myList:
total += x
print(total)
--->
15
In this example, we’ve created a variable named total
and set it to 0
. We've also created a list of numbers, myList
, that we want to add to the total.
Next, we've created a for loop to access each item in the list individually and add it to the total. Finally, we've used the print function to display our final answer (15).
This code follows a step-by-step process. In the first iteration, we add 1 to the initial total (0) to get the new total (1). Then the loop runs again, adding the next number in our list to 1 to get the new total (3). And so on. You've defined the process by creating a loop that iterates through the entire list to perform a task.
This process can become time-consuming and increasingly complex as you add features and code. Now let’s look at how we can achieve the same result using declarative programming.
Declarative programming
mylist = [1,2,3,4,5]
# set total to the sum of numbers in mylist
total = sum(mylist)
print(total)
--->
15
As you can see, the code structure in this example is more concise. Unlike the imperative programming example, we haven't outlined the steps. Instead of using a loop to iterate over our entire list, we've used the sum()
method, which works for us.
In other words, you can read the declarative Python code as finding the sum of all the numbers in our list. You only care about the result, not the process.
Get started with declarative and imperative programming today
Today we've covered the basics of imperative and declarative programming, along with their key differences. In general, you should have a somewhat easier time using declarative programming to achieve your desired results. Although imperative programming is easy to learn, managing code bases written using the imperative paradigm can become complex as you add more features and code. At the same time, you maintain complete control, allowing you to customize your program more.
As you continue your programming journey, you’ll want to learn the features of other paradigms under the umbrella of imperative programming, like procedural programming and object-oriented programming. Under declarative programming, additional paradigms include functional programming and logic programming.
In the meantime, if you’re interested in starting your declarative programming journey, check out the course An Introductory Guide to SQL. It covers creating, updating, and manipulating databases to attain the results you want, all in an interactive, hands-on environment.
If you prefer to start with imperative programming, we recommend the Python for Programmers learning path. The Python programming language is widely popular and can help you gain an edge in the job market.
Happy learning!
Continue learning about programming languages on Educative
- Functional programming vs OOP: Which paradigm to use
- Why learn Python? 5 advantages and disadvantages
- What's the best programming language to learn first?
Start a discussion
Which of the two do you prefer? Was this article helpful? Let us know in the comments below!
Posted on July 26, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.