Oqu Easy

Programming Paradigms: Declarative and Imperative

Programming paradigms are fundamental styles of computer programming. Two key paradigms are declarative and imperative programming, which differ in how they approach problem-solving and code structure.

Declarative Programming

Declarative programming focuses on describing what the program should accomplish, rather than how to accomplish it. It specifies the desired result without detailing the steps to achieve it.

Imperative Programming

Imperative programming focuses on describing how a program operates by providing a sequence of commands for the computer to perform. It details the steps needed to achieve the desired result.

Features of Programming Paradigms

Paradigm Key Features
DeclarativeDescribes the problem and expected result; no variables or assignment operators; focuses on "what" rather than "how".
ImperativeDescribes steps to solve the problem; uses variables, loops, and conditionals; focuses on "how" to achieve the result.

Comparison of Declarative and Imperative Programming

Aspect Declarative Imperative
FocusWhat the result should be.How to compute the result step-by-step.
Control FlowImplicit (handled by the system).Explicit (loops, conditionals).
State ManagementNo mutable state or variables.Uses variables and assignment operators.
ExamplesSQL, HTML, CSS.C, Java, Python (in imperative style).
DirectionFrom person to machine (describe intent).From machine to person (command steps).

Analogies

Declarative programming is like asking your friend to paint a landscape. You don't care how they draw it; it depends on them.

Imperative programming is like your friend listening to Bob Ross, who provides step-by-step instructions to paint a landscape.

Pros and Cons of Declarative and Imperative Programming

Paradigm Advantages Disadvantages
Declarative Simpler code; easier to read and maintain; automatic optimization by the system. Less control over execution; potential performance overhead; harder to debug low-level issues.
Imperative Fine-grained control; efficient for performance-critical tasks; straightforward debugging. More verbose code; prone to errors in state management; harder to parallelize.

Examples

TypeExample
Imperative Statement"Go to the store." (Command to perform an action.)
Declarative Statement"The cat is brown." (States a fact without specifying how.)
Programming Example (Sorting)Declarative: Describe the sorted list. Imperative: Step-by-step swap elements.

Visual understanding

Declarative vs Imperative Programming
Declarative vs Imperative Programming

Programming Paradigms Knowledge Check

1. What is the main focus of declarative programming?

PAST PAPER QUESTIONS

Programming paradigms are essential in computer science. (a) Give one example of each paradigm in practice:

1) Declarative Programming

2) Imperative Programming

3) Key Difference