Programming Paradigms Midterm 1
What are characteristics of a low-level programming language?
- Closer to computer (wire) - Provide little to no abstraction from hardware (think registers, %rax, %rbx, etc). - Difficult to write, understand, debug, and maintain. - Extremely powerful. - Not portable, because it's often machine-specific. - Typically do not require compilers or interpreters; machine code runs directly on the processor (needs assembler).
**Compiled** language characteristics:
- Generally faster bc the machine code is directly executed by the CPU without additional translation during runtime. - Less portable - Debugging is harder, error messages more complex/imprecise - Slower initial execution due to the need for compilation, but faster runtime - Errors are detected at compile time - Produce a separate executable file (e.g., .exe or .out).
What are characteristics of a high-level programming language?
- Provides a high level of abstraction from hardware. - Easier to write, understand, and debug. - Generally slower because of additional layers of abstraction and the need for translation (compilation or interpretation). - Highly portable. Code can often run on different machines with little or no modification.
**Interpreted** language characteristics:
- The source code is executed line-by-line or statement-by-statement by an interpreter during runtime. - Slower (more overhead), but with faster initial execution than compiled languages (no compilation time) - Highly portable - Easier to debug (they'll crash at the specific lines that cause problems) -
What do programming paradigms affect in software development?
- how developers design and organize their code. - how programmers approach and structure their solutions.
Advantages of Declarative Programming
Conciseness and Readability: Programs are often more compact and easier to understand.• Modularity: Encourages modular design and reusable components.• Optimization: Allows for easier optimization by leaving implementation details to the interpreter compiler
Lexical analysis
Converts the raw source code (text) into tokens(smallest units of meaning
Declarative Programming Paradigms
Declarative programming paradigms focus on describing what the program should accomplish without specifying how to achieve it through detailed instructions or commands. Focus on What, not How. OCAML. immutability
What makes a pure function?
Deterministic: Given the same input, it always produces the same output. No Side Effects: It does not modify any external state, variables,data structures, or perform I/O operations
Java supports multiple inheritance, T/F
FALSE. This design choice avoids complexities such as the "diamond problem," where ambiguity arises when a class inherits from two classes that have a common ancestor. However, Java allows a class to implement multiple interfaces, enabling a form of multiple inheritance for types
Java, C, and C++ both impose an explicit recursion limit, T/F
False, Java, C, and C++ don't impose an explicit recursion limit. However, the depth of recursion is typically limited by the system's stack size.
in java and C++, method overloading is resolved at runtime, while method overriding is resolved at compile time, T/F
False, reverse it! method overloading is resolved at compile time based on the method signature, while method overriding is resolved at runtime based on the object's actual type. For python, method overriding is determined at runtime
For Compiled languages, errors are detected at runtime. True/False
False, they're detected at compile time.
C/C++/Java all rely on RecursionError when recursion depth exceeds the stack size, while Python raises a StackOverflowError, T/F
False- scratch that, reverse it! C/C++/Java all rely on StackOverflowError when recursion depth exceeds the stack size, while Python raises a RecursionError
In C, global or static variables are full of garbage values, like local variables. T/F
False. For global or static variables in C, the default value is 0 (or NULL for pointers).
C++ has a default access modifier, T/F
False. In C++, the default access modifier for class members is private, whereas in Java, the default is package-private.
What does an declarative paradigm focus on?
Focuses what to achieve, not how to achieve it... building programs that expresses logic of computation without talking about its control flow.
Header guards
Header files have an include guard or a #pragma once directive to ensure that they are not inserted multiple times into a single .cpp file.
Declarative Paradigm characteristics:
High-level abstraction: Focuses on the desired output. Avoids explicit control flow
What are some ideal uses for a compiled language?
Ideal for system-level programming, performance-critical applications, and standalone software
Code Optimizer
Improves the intermediate code to enhance performance, efficiency, and reduce resource usage
What does an imperative paradigm focus on?
It gives explicit instructions to a computer on **how** to execute a task
Intermediate code generation
It is possible to generate target program as a result of syntax and semantic analysis.. so this is a bit of a baby step
Steps of compilation?
Lexical Analysis• Syntax Analysis (Parsing)• Semantic Analysis• Intermediate Code Generation• Optimization• Code Generation• Grammars, Parse Trees• Code Emission
Dynamic Typing
The type of a variable is determined at runtime. Type checking happens when the program is executed. (Python)
Compilation
Transform source code written in a high-level language into machine code or an intermediate language.
Code Generation
Translates the optimized intermediate code into machine code or an intermediate representation
Procedural programming is often found in C, T/F
True!
T/F: In C++, modules are often represented by header files and implementation files (similar to C).
True! C++ also supports namespaces to organize the module's content.
In SQL, functions and procedures are explicitly distinguished, T/F
True! in other languages such as Java, C and C++, the terminology primarily revolves around functions
Python does not support traditional method overloading, T/F
True.
C++ supports multiple inheritance.
True. But, they use "virtual" meaning only one version of a function can be made and used.
Python has a built-in recursion depth limit to avoid infinite recursion and stack overflows, T/F
True. Python has a built-in recursion depth limit to avoid infinite recursion and stack overflows. You can change the recursion limit in Python using sys.setrecursionlimit().
Python does not have traditional preprocessor directives, T/F
True. Python relies on its dynamic nature and modular programming for similar functionalities.. like imports.
Interpreted languages provide a separate executable file, T/F
True. They do not produce a standalone executable.
Compiled languages produce a separate executable file, T/F
True. They produce a separate executable file (e.g., .exe or .out).
Weak Typing
Variables can be implicitly converted between types, which may lead to unexpected results or errors. (C)
Inline Functions
a feature in programming (notably in C and C++) where the compiler replaces the inline function call with its code.
What is a Programming Paradigm?
a fundamental style or approach to programming that defines how problems are structured, solved, and expressed in code.
What is Imperative Programming?
a paradigm where the programmer explicitly defines the sequence of operations that change the program's state. It focuses on ***how*** tasks are performed.
What is a programming language?
a programming language is a set of instructions that enables humans to communicate with computers—using a series of symbols that serve as a bridge that allows humans to turn our ideas into instructions computers can understand.
What is Functional Programming?
a programming paradigm that treats computation as the evaluation of mathematical functions and avoids changing state and mutable data.
What is a module?
a self-contained unit of code that can be imported and reused in other programs or files.
What is a Paradigm?
a typical example or pattern of something; a model
How does the Recursion process unfold?
1. Space Allocation: Memory on the stack is reserved for the function's arguments and local variables. 2.Argument Copying: The function's arguments are duplicated into this allocated space. 3.Function Call: Control shifts to the function's code execution. 4.Function Execution: The function performs its computations according to its defined logic. 5.Result Storage: The function's computed result is stored in a designated return value. 6.Stack Rewind: The stack is reverted to its prior state, deallocating the function's allocated space. 7.Return to Caller: Control returns to the exact location in the program from which the function was originally invoked
What is the STL (C++ tools) comprised of?
1.Containers 2.Iterators 3.Algorithms
association
A general relationship between two or more classes where objects interact but are loosely connected.-- One object can exist independently of another.• There is no ownership between the objects.
maven and gradle
A popular build automation tool that also handles dependencies, package management, and project structure.
Procedural Programming
A programming paradigm based on the concept of procedure calls (functions or routines). instructions -> procedures step by step. Think basic CS 103 stuff! Opposite of OOP.
aggregation
A special type of association where one class contains another, but both objects can exist independently.• Represented as a "has-a" relationship.
composition
A stronger form of aggregation where one class owns another, and the owned object cannot exist independently.
Default Initialization
A value given to a field or variable if no value is specified by the programmer. Not all languages have this! C, for example, will fill a primitive variable with garbage values when declared until intialized.
What are abstract classes?
Abstract classes are classes that cannot be instantiated directly and are meant to be inherited by subclasses, often with abstract methods that MUST be implemented.
Private access modifier
Accessible only within the same class
Package-Private access modifier (Default):
Accessible only within the same package
Protected access modifier
Accessible within the same package and by subclasses
Compile-time polymporphism (Static polymorphism)
Achieved by method overloading or operator overloading. Decided at compile time
Run-time Polymorphism (Dynamic Polymorphism):
Achieved by method overriding.• Decided at runtime (e.g., using inheritance and interfaces).
Syntax Analysis (Parsing)
Analyzes the structure of the tokens to determine if the syntax follows the language's grammar.
What are examples of a low-level programming language?
Assembly Language, Machine Language (binary).
Automatic Memory Management vs Manual Memory Management
Automatic: handles the allocation and deallocation of memory automatically, typically through garbage collection. Manual: the programmer is responsible for explicitly allocating and deallocating memory.
What are some performance optimizations?
Avoiding Unnecessary Object Creation, Use of Lazy Initialization, Minimize Inheritance Depth, Efficient Memory Management, Favor Polymorphism and Interfaces over Inheritance
Importance of Imperative Programming
Backbone of system programming (e.g., Unix written in C).• Popular for performance-critical applications.• Precise control over hardware and memory.• Performance benefits due to low-level abstractions.• Straightforward for procedural tasks.
What are some examples of a compiled language?
C, C++, Rust, Go
Public Access Modifier
Can be accessed from any class.
Semantic Analysis
Checks if the program has meaningfulness and correctness (i.e., whether it follows the semantic rules).
Inline Function disadvantages
Code Bloat:• - Large inline functions may significantly increase the size of the binary because the function's code is duplicated at each call site. - May lead to inefficient use of the CPU cache.• No Guaranteed Inlining:• The inline keyword is a suggestion, not a command. The compiler ultimately decides whether to inline the function. Recursive Inline Functions:• Recursive functions cannot be fully inlined because the recursion depth is not known at compile time.• Debugging Difficulty:• Inline functions may make debugging harder, as their logic is expanded directly into the calling function.
What are some ideal uses for an interpreted language?
Commonly used in scripting, rapid prototyping, and dynamic web development.
Limitations of Procedural Programming
Limited Scalability:• - Challenging to manage large, complex systems due to lack of inherent object encapsulation.• Poor Data Management:• - Data and functions are separate, leading to challenges in maintaining data integrity.• - No direct support for encapsulation or abstraction.• Tight Coupling Between Procedures:• - Changes in one procedure can require updates across multiple parts of the code.• Lack of Flexibility for Real-World Modeling:• - Difficult to map procedural code to real-world problems compared to object-oriented programming (OOP).• Code Redundancy for Advanced Features:• - Absence of features like inheritance and polymorphism increases redundancy in advanced use cases.
In Python, will this code work? What is the output? (Strong Typing) x = 10 y = "20" z = x + y
No, it gives an error.
Strong Typing
Once a variable is assigned a type, it cannot be implicitly converted to another type without explicit conversion. Type errors are often caught early. (Python, Java)
Code Emission
Outputs the final machine code (or bytecode for interpreters) into an executable or object file.
Why do we like inline functions?
Performance Improvement:• Eliminates function call overhead for small functions.• Ideal for functions that are called frequently (e.g., getters, setters, or simple mathematical operations).• Code Readability:• Functions encapsulate logic, making code easier to read and maintain.• Inline avoids the penalty of abstraction.• Compiler Optimizations:• Enables the compiler to perform additional optimizations, such as constant folding and inlining loops.
What do Python access modifiers look like?
Public: age (no prefix)• Protected: _age (single underscore)• Private: __age (double underscore) Python applies name mangling for private, where the attribute name gets transformed (e.g., __name becomes_Pet__name) to make it less likely to be accessed or overridden accidentally.
What are some examples of a high-level programming language?
Python, JAVA, C++, Perl, BASIC, COBOL, Pascal, Ruby
What are some interpreted languages?
Python, Ruby, JavaScript.
How is a lambda function used in Python, C++, and Java?
Python: lambda x: x ** 2 C++: [ capture_clause ] (parameters) -> returnType { function_body } Java: (x, y) -> x + y;
Characteristics of an Imperative Paradigm
Sequence: Operations are performed in a specific order. Iteration: Loops to repeat tasks. State: Maintains state through variables and memory
Key Characteristics of Imperative Programming
Sequential execution: Instructions are executed in the order they appear. State changes: Variables and memory locations are explicitly manipulated. Control structures: Conditional statements (if, else), loops (for, while).
Disadvantages of Imperative Programming
Side Effects: Frequent variable updates can lead to bugs.• Scalability Issues: Increased difficulty in managing larger programs.• State Management: Complexity with shared or global state. Low-Level Abstraction: Focus on "how" rather than "what."• Reduced Reusability: Less modular and harder to reuse code.• Steep Learning Curve: Harder to understand interactions in large systems. Verbose Code: Requires more effort to write and maintain.• Error Propagation: Errors spread through multiple states and commands.
Benefits of Procedural Programming
Simplicity and Ease of Use:• - Intuitive structure makes it easier to learn and implement.• - Suitable for smaller, well-defined tasks.• Code Reusability:• - Functions can be reused across the program, reducing redundancy.• - Encourages modularity.• Structured Programming:• - Encourages clear program structure through logical flows.• - Aids in breaking down problems into smaller, manageable tasks.• Efficient for Specific Use Cases:• - Well-suited for tasks requiring straightforward workflows, such as mathematical computations.• Wide Language Support:• - Supported by many foundational programming languages (e.g., C)
SOLID design principles
Single Responsibility Principle - classes need 1 responsibility Open/Closed Principle - open for extension/closed for mod Liskov Substitution Principle - I should be able to sub the subclass for the base class Interface Segregation Principle -no client should be forced to depend on methods it does not use Dependency Inversion Principle - high-level modules should notdepend on low-level modules
In C, what this the output of this code? Is it an error? (Weak Typing) let x = 10; let y = "20"; let z = x + y; console.log(z) let a = "5" * 2; console.log(a)
The result is: 1020 10
Static typing
The type of a variable is determined at compile time. Type checking is done before the program is run. Types are declared by programmer explicitly. (Java)
"Imperative Paradigms," AKA...
algorithmic programming
A lambda function is.....
an anonymous function (a function without a name) generally used for short-lived functions, often passed as arguments to higher-order functions, such as map(), filter(), or sort().
What is Garbage Collection?
an automatic memory management process in programming. It identifies and reclaims memory that is no longer in use, making it available for future allocations.
What not to put in a header file?
built-in type definitions at namespace or global scope• non-inline function definitions• non-const variable definitions• aggregate definitions• unnamed namespaces• using directives
Creational Patterns Singleton
ensures a class has only one instance and provides a single access point to it, maintaining consistency across a program
First class function vs high-order function
first-class: functions are treated like any other variable high-order: function that takes another function as an argument or returns a function. ... tl;dr, first-class is a function as a variable, and high-order is a function allowing functions as args
STL (Standard Template Library)
in C++ offers a collection of programming tools designed for implementing algorithms and data structures such as vectors, lists, and queues. Reliable and heavily tested.
PreProcessor Directive
instructions given to the compiler to preprocess the information before actual compilation starts. Stuff like macros, guard macros for headers
static binding
occurs at compile time. The method to be invoked is determined during the compilation, and the method call is linked directly to its definition. Associated with non-overridden methods, i.e.,when the method is already known at compile time
dynamic binding
occurs at runtime. The method to be invoked is determined when the program is running, and it depends on the actual object type rather than the reference type. Associated with overridden methods (dynamic polymorphism)
C/C++ Macro
preprocessor directive that allows the definition of constant values or expressions that are substituted in place of their names before the compilation process begins. #define PI 3.14
Creational Patterns Factory
provides an interface for creating objects without specifying their exact class. It helps encapsulate object creation logic and makes the code more flexible and maintainable.
Semantics (meaning)
refers to the meaning or behavior of the program and its statements. It defines what the program does when executed, i.e., the effect of the syntactically correct code.
Design patterns, and the three types
reusable solutions to common software design problems. Creational, structural, behavioral
Syntax (structure)
the set of rules that defines the structure or format of valid statements in a programming language. It specifies how symbols, keywords, and operators can be arranged to create valid code.
Python's Duck Typing
where the suitability of an object is determined by the presence of certain methods and properties, rather than the object's type.
