CSCI 4200 Exam 1
What is a preprocessor? Give an example.
-Preprocessor macros (instructions) are commonly used to specify that code from another file is to be included -A preprocessor processes a program immediately before the program is compiled to expand embedded preprocessor macros -An example: C preprocessor- expands #include, #define, and similar macros Examples in C: • #include "myLib.h"- Preprocessor copies the contents of myLib.hinto the program at the position of the #include • #define max(A, B) ((A) > (B) ? (A) : (B)) - Preprocessor replaces a call to max with its respective body - E.g. the call max(5, 9) will be replaced with((5) > (9) ? (5) : (9))
How are the instructions executed on Von Neumann computers?
Fetch-decode-execute-cycle: 1. initialize the program counter 2. repeat forever 3. fetch the instruction pointed by the counter 4. increment the counter 5. decode the instruction 6. execute the instruction 7. end repeat
The TIOBE Programming Community Index
-an indicator of the popularity of programming languages -is not about the best programming language or the language in which most lines of code have been written -updated once a month -ratings are based on the number of skilled engineers world-wide, courses and third party vendors -can be used to check whether your programming skills are still up to date or to make a strategic decision about what programming language should be adopted when starting to build a new software system
Phases of compilation process
-translates high-level program (source language) into machine code (machine learning) -used in large commercial applications -slow transition, fast execution Components: -Lexical analyzer: converts characters in the source program into lexical units -Syntax analyzer: transforms lexical units into parse trees which represent the syntactic structure or the grammar of program -Intermediate code generator: generates a code, e.g., assembly code, between the source code and the machine language - Semantics analyzer: Focuses on the meaning of a structure. E.g., it checks for type errors -Optimizer: Improves the program by making it either smaller, faster or both -Code generator: Translates the optimized code into machine language -Symbol Table: A database containing user-defined names and corresponding types and attributes Additional terminology: -Linking and loading: the process of collecting system program units (e.g.,for input and output) and linking them to a user program (accomplished by a systems program called a linker) -Load module (executable image): the user and system code together
Common data types, and definition and structure of each data type.
Almost all programming languages provide a set of primitive data types (those not defined in terms of other data types) Integer: -most integer types are directly supported by the hardware -many different integer types in a language Java's signed integers: -byte (8bits) -short (16 bits) -int (32 bits) -long (64 bits) Long integer values from Python are not supported by the hardware. They can be specified as literals (2345678546543L) Floating Point: -Model real numbers, but only as approximations -For example, the number π cannot be correctly represented in floating-point notation, neither can 0.1 -The decimal 0.1 is 0.0001100110011 . . . in binary, which is 0.0999755859375 in floating point! -Neither of these numbers can be precisely represented in any finite amount of computer memory • An example in Python: # float_accuracy.py # Demonstrate the inaccuracy of float operations num1 = 0.1num2 = 0.2 print("num1 is", num1) print("num2 is", num2) sum = num1 + num2 print("Total of the two numbers is", sum) if sum == 0.3: print(sum, "is equal to 0.3") else: print(sum, "is not equal to 0.3"
What is binding and different binding times? Give examples.
Binding: an association between an entity and an attribute, such as between a variable and its type or value, or between a symbol and an operation Binding Time: the time at which a binding takes place Different Binding Times: • Language design time -- bind operator symbols to corresponding operations • Language implementation time-- bind floating point type to a representation • Compile time -- bind a variable to a type in C or Java • Load time -- bind a C or C++ static variable to a memory cell • Runtime -- bind a non static local variable to a memory cell
Difference between compilation, linking, loading and executing
Compiling: convert the source code to object code or machine code Linking: convert object code to executable code by linking multiple units of object codes together Loading: load the executable code into memory for execution Executing: retrieve the instructions from the memory and execute them In summary, compilation turns source code into object code, linking combines object files into an executable, loading places the executable in memory, and execution involves running the program's instructions on the CPU. These steps are essential for transforming source code into a running program.
How do computer architecture and program design methodologies influence the design of a programming language?
Computer Architecture -languages are developed around the prevalent computer architecture, known as the Von Neumann (Stored Program) architecture -The Von Neumann bottleneck is when program instructions often can be executed much faster than the speed of the connection; the connection speed thus results is a bottleneck (it is the primary limiting factor in the speed of computers) -imperative languages, most dominant, are designed around Von Neumann computer (data and programs stored in memory, memory is sperate from CPU, instructions and data are piped from memory to CPU) -basis for imperative language Programming Methodologies Influences -1950s and early 1960s: simple applications; worry about machine efficiency -late 1960s: people efficiency became important; readability, better control structures (structured programming, top-down design and step-wise refinement) -late 1970s: procedure-oriented to data-oriented (data abstraction) -middle 1980s: object-oriented programming (data abstraction + inheritance + polymorphism)
Definition and significance of data type. Give examples.
Data Type: defines a collection of data objects and a set of predefined operations of those objects - int is a data type in Java - It is a collection of all the whole numbers represented on a computer - Can perform operations such as +, -, *, /,etc. on these numbers •User-defined types - Provided improved readability through the use of meaningful names for types - Helped with modifiability • A class, Student, representing student objects • In Java, an enumerated data type, Day, to represent the days of a week: enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY,THURSDAY, FRIDAY, SATURDAY; } Some Uses of the Type System of a Programming Language: - Error detection • Type checking - Assistance it provides for program modularization • Cross-module type checking that ensures the consistency of the interfaces among modules - Program document information about its data • Provides clues about the program's behavior Examples: Integer (int) - 'int age = 25' Float or Double - 'float pi = 3.14159...' Boolean (bool) - 'bool is True = true'
Definition of descriptor, its structure and its use. Give examples of descriptors corresponding to different data types.
Descriptor: collection of the attributes of a variable Think of variables in terms of descriptors A descriptor is an area of memory that stores the attributes of a variable - Static Attributes: descriptors are built and used during compile time, usually, as a part of symbol table - Dynamic Attributes: part or all of the descriptor must be maintained during execution • In all cases, descriptors are used for type checking and code generation
Difference between imperative and declarative programming languages
Imperative Languages: -focus on describing how a program operates -use statements to change a program's state and express logic through the order of statements -central features are variables, assignment statements, and iteration -includes: object-oriented languages, scripting languages, visual languages (Java, Perl, JavaScript, C++,...) Declarative Languages: -focus on what (desired outcome of computation) the program should accomplish without specifying how the program should achieve the result -do not specify the order of execution of statements -includes: logical programming languages (Prolog), functional programming languages (LISP, Scheme, ML,...), and database languages (SQL) In summary, the primary difference between imperative and declarative programming lies in how they express the logic of a program. Imperative languages focus on specifying the step-by-step instructions for performing a task and managing mutable state, whereas declarative languages emphasize stating what should be achieved or the desired relationships between data elements.
Differences between different categories (e.g., functional, logic, etc.) of programming languages
Imperative: -focus on changing the program's state step by step -emphasize control flow structures (loops and conditional statements) -often rely on mutable variables (values change over time) -examples include: C, C++, Java, and Python (to an extent) Functional: -focuses on expressing computations as the evaluation of mathematical functions -use higher-order functions and recursion for control flow (instead of loops) -use of immutable data structures (data values can't change after being created) -examples include: Lisp, Scala, and JavaScript (supports functional programming features) Logic: -programs are sets of logical rules an constraints. You specify what should be true rather than how to achieve it. -declarative, meaning you declare the relationships and constraints between entities -Examples include: Proglog and Mercury Object-Oriented: -focuses on organizing code into objects, which encapsulates data an behavior -provides a way to abstract real-world entities into objects, each with attributes and functions -allows for the creation of new classes by inheriting attributes and functions from existing ones -Examples include: Java, C++, Python, Ruby In summary, these programming paradigms differ in their approach to organizing and structuring code, handling control flow, and managing data and state. (This section is not from the textbook, had to look up)
Reasons for Studying Concepts of Programming Languages
Increases ability to express ideas - using expressive power of a language Improved background for choosing appropriate languages -being able to select a language more appropriate for a project Increased ability to learn new languages -an indicator of the popularity of programming languages Better understanding of significance of implementation -leads to the ability to use a language more intelligently, as it was designed to be used. - understanding the choices among programming language constructs and the consequences of those choices - allows us to visualize how a computer executes various language constructs. Better use of languages that are already known Overall advancement of computing
Difference between primitive and structured data types.
Primitive Data Types: those not defined in terms of other data types -some primitive data types are merely reflections of the hardware -others require only a little non-hardware support for their implementation -Examples: integers, floating point numbers, characters, booleans, and pointers (store single values) Structured Data Types: composite data types that are composed of multiple values, possibly of different types, grouped together -are usually user-defined and allow you to create complex data structures by combining primitive data types -Examples: arrays, lists, dictionaries (maps), structures (records), classes, and objects (store multiple values and may include an combination)
Examples of each programming language evaluation criteria/Characteristics which contribute to each language evaluation criteria
Readability -overall simplicity -orthogonality (A relatively small set of primitive constructs can be combined in a relatively small number of ways to build the control and data structures of the language) -data types (Adequate data types and facilities for defining data types and data structures (E.g., Boolean true vs. Integer 1 in timeout =1 and timeout = true)) -syntax design (specials words (while, for, class) and methods of forming compound statements) Writability -simplicity and orthogonality (A small number of primitive constructs, and a small set of rules for combining them) -expressivity (Language has relatively convenient(rather than cumbersome) ways of specifying computations. E.g.,• in C, the notation count++ is more convenient and shorter than count = count + 1) Reliability -type checking (testing for type errors by the compiler or during execution, compile time type checking less expensive, therefore more desirable, the earlier errors are detected, the less expensive to repair) -exception handling (intercept run-time errors and take corrective measures -aliasing (presence of two or more distinct referencing methods for the same memory location) -readability and writability (both influence reliability, A language that does not support "natural" ways of expressing an algorithm will require the use of "unnatural" approaches, and hence reduced reliability. (E.g., use of separate variables to express a record structure.) The easier a program is to write, the more likely it is to be correct.)
Difference between readability and writability and an example
Readability- the ease with which programs can be read and understood An example of poor readability is: def calc(a,b): r=a+b if r>10: return True else: return False (The lack of consistent formatting, non-descriptive variable names, and unnecessary complexity makes the readability poor) An example of improved readability is: def calculate_sum_and_check_gt_10(number1, number2): sum_of_numbers = number1 + number2 is_greater_than_10 = sum_of_numbers > 10 return is_greater_than_10 (Names are descriptive and indentation is consistent making it easier to follow) Writability- the ease with which a language can be used to create programs An example of low writability is: def factorial(n): result = 1 i = 1 while i <= n: result = result * i i = i + 1 return result (The code is functional but not very writable. Using a while loop and explicit variable manipulation can make it more error-prone) An example of high writability is: from math import factorial result = factorial(n) (It's more writable because it allows you to use the existing libraries and built-in functions. Allows developers to work more productively) In summary, readability is about making code easy to understand and maintain, while writability is about making code easy to write and work with efficiently.
Criteria used to evaluate programming languages
Readability- the ease with which programs can be read and understood -must be considered in the context of the problem domain -ease of maintenance Writability- the ease with which a language can be use to create programs -must be considered in the context of the target problem domain of the language Reliability- able to develop crash proof code in that language -a program is reliable if it preforms to its specifications under all conditions -strong type systems encourage reliability of code -conformance to specifications Cost- the ultimate total cost
Explain different language implementation methods and state thedifferences
Reliability vs Cost of Execution -Example: Java demands all references to array elements to be checked for proper indexing, which leads to increased execution costs Readability vs Writability -Example: APL provides many powerful operators (and a large number of new symbols), allowing complex computations to be written in a compact program but at the cost of poor readability Writability (flexibility) vs Reliability -Example: C++ pointers are powerful and very flexible but are unreliable The task of choosing constructs and features when designing a programming language requires many compromises and trade-offs.
List and differentiate different Programming Domains
Scientific applications -large numbers of floating point computations; use of arrays -Fortran Business applications -produce reports, use decimal numbers and characters -COBOL Artificial Intelligence -symbols rather than numbers manipulated; use of linked lists -LISP Systems programming -need efficiency because of continuous use -C Web software -electric collection of languages: markup (HTML), scripting (PHP), general-purpose (Java)
Definition and examples of signed and unsigned integer types.
Signed: is represented in a computer by a string of bits, with one of the bits (typically the leftmost) representing the sign -allow both positive and negative numbers to be represented Example: -43 base 10 encoded in an eight-bit byte is 10101011 while 43 base 10 is 00101011. ➢ Left-most bit represents the sign ➢ Remaining seven bits represent the magnitude ➢ 43 base10 means 43 in base 10 Unsigned: represent only non-negative values. They allocate all bits for the magnitude of the number, with no bit used for the sign In summary, the choice between signed and unsigned integer types depends on the specific requirements of your program and the range of values you need to represent. Signed integers are more versatile, while unsigned integers are useful when you need to represent non-negative values with a larger range.
Difference between static binding and dynamic binding. Give examples.
Static Binding: • A binding is static if it first occurs before run time and remains unchanged throughout program execution. Dynamic Binding: • A binding is dynamic if it first occurs during execution or can change during execution of the program Example: Consider the following C++ assignment statement: int count = 0; count = count + 5; Some of the bindings and their binding times for the parts of this assignment statement are as follows: • The set of possible values of int is bound at compiler design time. • The type of count is bound at compile time. count = count + 5; • The meaning of the operator symbol + is bound at compile time, when the types of its operands have been determined. • The internal representation of the literal 5 is bound at compiler design time. • The value of count is bound at execution time with this statement. A complete understanding of the binding times for the attributes of program entities is a prerequisite for understanding the semantics of a programming language.
When is type checking done in a programming language?
Type checking is simply testing for type errors in a given program, either by the compiler or during program execution. Type checking is an important factor in language reliability. Because run-time type checking is expensive, compile-time type checking is more desirable. Furthermore, the earlier errors in programs are detected, the less expensive it is to make the required repairs. So type checking can either be done at run-time or compile-time.
Definition and structure of variables
Variable: is an abstraction of a memory cell or collection of cells -programmers often think of variables as names for memory locations, but there is more to it Variables can be characterized as a sextuple of attributes: 1. Name: an identifier associated with a variable. 2. Address: the machine memory address with which the variable is associated. This address can vary during the execution of a program. 3. Type: determines the range of values the variable can store and the set of operations that are defined for values of the type. 4. Value: the contents of the memory cell or cells associated with the variable. 5. Lifetime: the time during which the variable is bound to a specific memory location. 6. Scope: the range of statements in which the variable is visible.