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 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 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.
| Paradigm | Key Features |
|---|---|
| Declarative | Describes the problem and expected result; no variables or assignment operators; focuses on "what" rather than "how". |
| Imperative | Describes steps to solve the problem; uses variables, loops, and conditionals; focuses on "how" to achieve the result. |
| Aspect | Declarative | Imperative |
|---|---|---|
| Focus | What the result should be. | How to compute the result step-by-step. |
| Control Flow | Implicit (handled by the system). | Explicit (loops, conditionals). |
| State Management | No mutable state or variables. | Uses variables and assignment operators. |
| Examples | SQL, HTML, CSS. | C, Java, Python (in imperative style). |
| Direction | From person to machine (describe intent). | From machine to person (command steps). |
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.
| 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. |
| Type | Example |
|---|---|
| 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. |
1. What is the main focus of declarative programming?
Programming paradigms are essential in computer science. (a) Give one example of each paradigm in practice:
1) Declarative Programming
Using SQL to query a database: SELECT * FROM users WHERE age > 18; (Describes what data is needed without how to fetch it.)
2) Imperative Programming
Using a loop in Python to sum numbers: total = 0; for i in range(1, 11): total += i; (Step-by-step instructions.)
3) Key Difference
Declarative focuses on the "what," while imperative focuses on the "how."