111 Flashcards

(143 cards)

1
Q

What is a pointer

A

variable that contains the address of another - signified by *
used for passing variables to functions by ref
size is always system’s memory address size

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do you get the memory address of var?

A

&var

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

A string in C is…

A

an array of characters terminating with \0
indicated by %s

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

what do you use to indicate a a) string, b) decimal?

A

a) %s b) %d

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you compare 2 strings in C?

A

using strcmp() - returns -1/0/1 (less than/equal to/greater than) based on ASCII codes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How do we dynamically allocate space in memory (C)?

A

using malloc(int) to allocate and free(var) to deallocate

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What’s an API?

A

software interface between your program + something else - set of operations defined for interacting w/ a system in a controlled way
to use need to #include <headerfile.h></headerfile.h>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is a file?

A

ideally persistent storage of a collection of data, either text or binary + can be accessed serially or by random access

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

EOF means??

A

end of file

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How to read/write/open to a text file?

A

getchar() to return next input char + putchar(int) to put char on standard output
a
FILE fopen(char name, char mode) - modes being r/a/w

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How do you find where you are in the file in C?

A

long ftell(FILE *stream) - find out how many bytes from the start we are

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Pros of single file projects?

A
  • only 1 file to parse for compiler
  • programmer only needs to scroll through one place
  • copying/distributing project is just 1 source file + no dependencies - easyyy
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Cons of single-file projects?

A
  • not scalable
  • scrolling becomes unmanageable
  • difficult for teams to co-edit 1 file
  • harder to package up functions for reuse - danger of hidden side effects
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is a #include statement + the difference between “” and <> in them?

A

include basically pastes the code from the file it references in w/ your code

”” for in same file and <> for in system files

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is forward declaration/referencing?

A

defining the function type name and types of variables to help compiler and IDE when parsing functions from header files

also needed if function used before declared in the file

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What does gcc -c do?

A

create objects/part compiled files (saves from file.c to file.o)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How do you turn an object into a library?

A

gcc -c file.c - make file.c an object
ar rcs libx.a file.o - make file.o a library

where libraries should always be called lib”name”.a

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Why do we need dynamic data structures? (cons of static structs.)

A

costly (time + money) to shift data around in static structures - inefficient
need to know size to declare
may run out of space or take up unnecessary space

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How to add to dynamic data structure?

A

allocate space for a node from the heap (use malloc())
find where to add the item to the structure
adjust pointers accordingly

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is version control?

A

principled approach to tracking your code base
records differences between versions w/ no.s + timestamps too when you commit

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is the pre-processor useful for?

A

defining constants (#define)
defining macros (#define)
including files (#include)
conditional compilation (#if/#ifndef)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

How does the macro #define MIN(X,Y) (X) < (Y) ? (X) : (Y) work?

A

means where you see MIN(int,int) you substitute it with the comparison which will return whichever integer is smaller

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

how is conditional compilation helpful?

A

used to compile for different types of processor
can use #ifndef to protect header files from multiple inclusion errors

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

How do you do a binary shift in C?

A

&laquo_space;= left shift,&raquo_space; = right shift

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
How does compilation work for a C file? e.g. gcc -o main main.c
preprocessor (takes the source - main.c) -> C compiler (main.o) -> linker (main aka exectuable)
26
What are functional languages?
declarative languages w/ no explicit state e.g. Haskell + Erlang
27
What are declarative languages?
describe the logic of the program w/ minimal explicit control of the flow of execution e.g. SQL, HTML, Regex
28
What are object oriented languages?
imperative w/ implicit encapsulation of data + functions e.g. C++, Java, C#, JavaScript + Python
29
How does procedural programming vs OOP treat code + data?
procedural - treat as separate concepts (data modularity only occurs in structs) OOP -
30
What is modularity?
it allows us to divide code to inc. reliability (reducing interaction between code) and make code more scalable! it relies on standards (an API)
31
What does it mean that objects provide encapsulation?
- data + code cannot be separated - data is defined through attributes - behaviour is defined through methods
32
What is a class?
specification that defines objects - add attributes by defining variables inside the class - add methods by declaring functions with ClassName::function NEED ; after closing } at end of class
33
How do you create an object?
simply use the class name as a variable type object = instance of a class
34
What does modularity rely on?
encapsulation - module must contain its inner workings, protect them + only expose functionality through its interfaces
35
Why is access control important?
private attributes help keep other programmers directly reading/writing to your attributes public methods helps promote modularity w/o exposing more functionality than desired remember need protected for inheritance!
36
What are methods vital to classes?
accessors (getters) - pub method to get priv attribute value mutators (setters) - pub method that changes value of priv attribute constructors - automatically called when you create an object to help initialise destructors
37
What does a destructor do?
method that is invoked automatically whenever an object is to be destroyed occurs if... - var relating to that object goes out of scope - object is explicitly deleted
38
Benefits of access control + encapsulation:
- programmers can't create invalid/inconsistent variable values (accidentally or maliciously) - promotes simpler, safer code - programmer writing a class can now define + enforce its API
39
How do you cast a type to a variable in C++?
casting changes the variable type - like parsing (type) var
40
How is failure a debugging strategy?
compile often + test frequently to debug features one at a time
41
Describe code inspection as a debugging strategy?
read through the code + be thorough dry run before executing (relies on experience) if no obvious issues move onto a more systematic approach cheapest approach!!
42
How do runtime debuggers aid debugging?
allows you to visualise what the program is doing can see each line executed in real time + watch values change as it runs inc. breakpoints, single stepping, variable inspection + stack frames
43
How does reproducibility help debugging?
can create a reproducible test case + document everything you do NOTE: some bugs are transient but they WILL come back
44
Describe rubber duck debugging:
explain the problem + code to yourself out loud also can help avoid unconscious bias by talking to another developer
45
What does writing scalable code rely on?
- integrating high quality 3rd party classes into code - writing reusable code
46
What is a library?
a collection of prewritten, precompiled code e.g. set of functions in procedural or set of classes in OO , + are C++ libraries
47
How do you create a library?
- separate function + class declaration into header files - separate function/method implementation into .cpp files - do NOT inc. main() - compile code using -c to get object files - then group files into static library using ar rcs -o lib.a object.o - to compile w/ library add lib name between gcc and -o
48
What does inc.?
cin - inputs cout - outputs cerr - print error clog - logging
49
What is a namespace?
provides space where we can define/declare identifiers (e.g. variables, methods + classes) C++ standard library uses std namespace
50
What do namespaces have to do w/ scope?
namespace defines a scope allows you to differentiate functions, classes + variables w/ the same name available in different libraries by writing namespace:: thing
51
What does inc.?
string variable type (hides functionality of C char []) allows concatenation using + rfind() substr() append() length()
52
What does passing by value vs by reference do?
value = function takes value of the passed var + copies it into new independent variable ref = creates an alias for the same variable so compiler treats it + the passed variable as equivalent (indicated by &var)
53
What are the rules regarding references?
references NEVER permit reassignment - they're immutable references MUST be intialised (not null)
54
What types can be null in C++?
ONLY pointers
55
What is a virtual machine?
software emulation of a physical computer than runs programs in an isolated environment enables platform independence as run on software not hardware JAVA, C#, Python, Kotlin, JS = VM-based languages
56
What is the design goal of Java + what are its benefits?
simplicity + reusability before being a programming language, used for embedded systems + as a web language is reliable, good performance + platform independent
57
What is bytecode?
java bytecode = intermediate language bytecode has very simple instruc. (think like assembly) java is compiled into bytecode which the JVM then interprets into whatever the hardware understands
58
How does Java compare to C++?
Java's syntax is based on C++/C but slower given it's an intermediate language
59
What are the pros + cons of C++?
+ scalable + type safe (strong type checking) + encapsulation + efficient (uses less RAM + storage) - !platform independent so difficult to share libraries - doesn't check pointers - security risks w/ input of pointers - though some things are simple, some are very complex
60
What does the volatile type do?
stops usual memory optimisation by telling it to not cache the variable value but to retrieve from memory as it may change
61
Define composition -
classes may hold attributes of class type
62
How does referencing work in java?
100% pass by value
63
What is a primitive type? What is a reference type?
aka value types = data itself is being accessed/modified/passed into a function, e.g. int, char, float, etc. use references to objects, reference is being accessed/modified not data itself e.g. ObjectName
64
What does the this keyword do?
returns an object reference to the object instance which the current method is executing in can be used to differentiate between object attributes and parameter's w/ same name
65
What happens to java objects when they have no references?
get deleted
66
What is API documentation?
documentation of classes so other programmers can learn how to use them JavaDoc = java standard
67
What are some standards in javaDoc and how can it automatically generate written documentation?
begins w/ /** and ends **/ with * on each line between @param/@return followed by explanation use javadoc -d doc name.java to generate web pages that can be found in index.html
68
What is swing?
standard java package for GUIs (javax.swing) - very large + flexible - heavily OO - platform independent! - implements graphical component as java classes
69
What is a JFrame?
represents window in host OS (matches the style), inc. title bar + icons for minimise, resize, close, etc. can be initialised w/ or w/o a title automatically set to HIDE_ON_CLOSE + invisible
70
What is a static variable/method?
called on a whole class (all the objects, not just an instance)
71
What is a final variable?
cannot have its value changed after it has been initialised - like a constant
72
What holds a component in swing?
JPanel = holds a list of components add new components via componentName.setContentPane(panelName); components could be JLabel, JButton, JTextField, etc.
73
What is a layout manager? (Give examples)
provided by Swing to dynamically layout GUI components for you efficient and help keep application flexible + platform independent but limits control e.g. FlowLayout, GridLayout + BorderLayout
74
What does FlowLayout do?
arranges components to best fit panel size (left-right, top-bottom) - dynamically changes so simple to use - lack of control other than specifying left/right/centre centring
75
How do you set a layout manager?
instantiate a manager - e.g. FlowLayout layout = new FlowLayout; then panel.setLayout(layout);
76
What does GridLayout do?
fits components in a fixed size matrix (specify rows + column as param. in layout instantiation) - good for repeating sets of components - little control
77
What does BorderLayout do?
provide relative positioning of up to 5 components in north, south, east, west, center positions - a little more control - but only 1 component per region
78
What is the best way to use layout managers while maintaining control?
give each panel its own layout manager (can specify positions manually but timely + not flexible)
79
Define event-based programming:
application registers interest in certain events where the environment informs the the application when they occur uses listeners assigned to specific components that call actionPerformed(ActionEvent e) in response to events
80
How does it work if setting a listener to multiple components?
all components must match the type of listener (e.g. only buttons for an ActionListener) can use e.getSource() to see which component triggered the event
81
What is a merge conflict?
when someone else has updated the file on the git server as you have edited locally when this occurs, any files in conflict are updated w/ BOTH copies of lines of code that differ
82
What does git pull do?
receive updates from others + merge them into your local repo if the server version is more recent than your local version, will force you to pull before you can push
83
What does git status do?
shows untracked files + changes in tracked files to help figure out what needs to be committed
84
What does git push origin branch do?
shares commits back to the server so changes are visible to others origin = where you cloned repo from branch = what to push
85
What does git commit do?
saves changes to your copy of the repo (get copy via clone command) can add -m to label the update w/ a message
86
What is a personal access token?
used in place of a password for private github projects limits access to resources, selects a limited role + provides an expiry date - more secure
87
What is issue tracking (git)?
allows you to manage a list of requests of changes to your software useful for tracking bugs, synchronising workflow + feature requests
88
What is a repository branch?
like a named sub-copy of the repo that diverges at a given commit may merge back to main later where main is the definitive true version of your project code
89
Why use a separate branch in a git repo?
developers normally create a branch to hold their changes when adding a new feature then merge once feature is complete + approved
90
What are some git commands for branches?
git branch - lists branches in repo git branch branch-name - creates new branch git checkout branch-name - switches to that branch git push origin branch-name - pushes branch to server git merge branch-name - merges branch into current branch
91
What is repository fork?
deep copy of a repository - independent clone of the repo can be merged into the repo using merge requests - allows developers to experiment w/ changes w/o affecting original project - fork created on developer’s own account/organisation + can host new branches, commits, etc. like a normal repo
92
What is a merge request?
code is from a non-collaborator so needs review + control before it is merged into repo so request used typically helpful in open-source projects - anyone w/ a fork can request a fork branch to be merged - repo collaborators can then review the changes + communicate w/ the person - collaborators accept/reject request
93
What is continuous integration?
software development practice where developers regularly integrate their code changes into a central repository and each integration is verified by an automated build + automated tests - helps detect + fix integration issues early - ensures code quality + readability
94
What is continuous development?
next step in CI/CD pipeline - automates deployment process + reduce manual intervention for faster + more reliable software delivery
95
What are the CI workflow steps?
- developer pushes changes to version control system - CI server detects changes + triggers automated build and test process - results reported back to developer
96
What is inheritance?
provides mechanism to promote reuse + extensibility code written by 1 programmer + delivered as a class can then be extended by another to suit the needs of the task at hand base/super/parent class = class being extended subclass = new class - typically can have multiple subclasses per super class but only 1 super class per subclass (other than multiple inheritance languages like Python/C++)
97
Benefits of inheritance:
- allows class attributes + methods to be accessed/invoked on the new class w/o explicitly defining them - new class can also have further capabilities added w/o affecting original class (specialise for reuse)
98
How do you write inheritance in java vs C++?
java = public class Subclass extends SuperClass C++ = class Subclass : public SuperClass (public accessor makes all public methods/attributes public in new subclass too)
99
What does super() do in java?
calls constructor of that subclass' super class - needs to be 1st line of subclass constructor w/ param when subclass uses super() + so does its parent (+ maybe their parent, etc.) = constructor chaining : ParentName (param) to constructor declaration - does same in C++
100
How is inheritance transitive?
subclasses can become super classes of other classes and they will inherit from the subclasses’ super class too
101
What is an inheritance hierarchy?
tree structure used to map out inheritance relationships as you go up the hierarchy, we get more generalist + abstract, e.g. mammal as you go down, we get more specialist + specific, e.g. humpback whale
102
What is an abstract class?
class designed to be extended (inherited) not actually used for objects gives compile time error if you try to instantiate an object of it e.g. public abstract class ClassName
103
What is an abstract method?
placeholder method only allowed within an abstract class that subclasses override to use ensures all subclasses implement that method though unnecessary to write an implementation at that level of abstraction
104
What is the difference between polymorphism + method overriding?
polymorphism is a subclass assigned its parent class as a reference but acting differently method overriding is just a subclass acting different to its parent
105
Define polymorphism:
to take many forms e.g. that a subclass has all behaviour of their superclass and thus can be treat as a type of their superclass!
106
What is special with parent class object references?
can refer to subclasses as they at least have same methods + variables full backwards compatability!!
107
How does casting apply in inheritance?
can cast between types of object references IF the underlying object is the same class/subclass you're casting to only object reference changes NOT instance!!
108
What is an interface?
named specification of 0 or more methods but only contains desc. of method not actual implementation/functionality, e.g. ActionListener + actionPerformed() classes can implement multiple interfaces to bypass limitations of single inheritance languages' inheritance based polymorphism
109
Can polymorphism apply to interfaces?
YES, class will have capabilities defined in interface so can treat class as a type of the interface/s it implements
110
How to create your own interface?
public interface InterfaceName { } where rest follows normal class procedure then class uses interface by putting in declaration - class ClassName implements InterfaceName {}
111
Why are custom interfaces helpful?
allow you to define what other programmers must do in order to interface w/ your code so your code can support working w/ objects that haven’t even been written yet
112
How does casting relate to the inheritance hierarchy?
java implicitly casts object references as necessary going up the hierarchy (to parent) can only cast down explicitly though this is dangerous!
113
What is method overriding?
used to change behaviour by replacing a method in the superclass by redefining within subclass w/ reference casting method called will always be the most specific (lowest in the hierarchy) applicable to that object instance regardless of reference casting
114
What is method overloading?
defining multiple methods w/ the same name but diff. parameter lists to create diff. functionalities as java methods are identified by class, name + param list (name + param list = method signature)
115
How do you write a foreach loop in java?
for(type varName : arrName) - iterate foreach var of type in array more readable + don't need counter (saves memory)
116
What do diff. type java arrays initialise to at each index?
string + object arrays = null NOTE - object arrays hold a reference to the object not the actual object int array = 0
117
How do you write a 2D array in java?
int[][] arr = { {1, 2, 3, 4}, {5, 6, 7, 8}}; OR int[][] arr = new int [2][4];
118
What is a collection?
data struct. that provides general, reusable implementations of common data structs not inherently part of the language but implemented as classes
119
What is meant by a collections API?
java collections are implemented through inheritance hierarchy so all data structs. implementation have the same API
120
What is an ArrayList?
like an extensible dynamic array where items are maintained in a sequence, enumerate + indexed by location implemented internally as a simple array where if it gets full a new one is created + data is copied over good general purpose data struct.
121
What is a HashMap?
unordered collection of key value pairs useful for fast lookups (approaching O(1) for most methods)
122
What are generics?
classes can be parameterised like a function by using <> in place of () param. represents a type that needs to be defined when an object of that class is created e.g. public class LinkedList , LinkedList staff = new LinkedList
123
What is recursion?
function calling itself alternate to looping (any iterative algorithm can be written as recursive) lends itself to any program where task can be represented as a finite nested model of itself
124
How to avoid infinite recursion?
ensure there's a terminating case ensure the recursion is monotonic across a state space (makes problem smaller) ensure problem def. leads to terminating case
125
What happens when a function is called vs a recursive function?
stack frame (PC + param) pushed, function executed, frame popped, return value pushed, control returned recursion = 1 stack frame for each call pushed + 1 copy of every local var + param on stack
126
What is a problem w/ recursion?
- have larger DRAM footprint than iterative equivalents - take longer to execute due to overheads associated w/ method invocation, memory allocation, etc.
127
What are the types of recursion?
head - 1st statement of method is recursive middle/multi = 1<= arbitrary statements in a method are recursive tail - final statement of method is recursive (more efficient as compiler can rewrite stack - given local vars aren't needed - to prevent stack explosion)
128
What are the features of Python?
open-source cross platform language easy + intuitive understandable as plain English suited for everyday tasks (short dev. times)
129
How do you execute Python?
code in .py text file run - python3 file.py
130
What is Python syntax like?
no main(), no ;, no {} (instead :) indentation is IMPORTANT vars all lowercase w/ _ vars created at 1st use (must be assignment) + typing is dynamic boolean operators are simply and, or + not for only works as for i in x: where x is an array or in range(val)/in enumerate(struct) - where enumerators are more pythonic than range as range goes through struct to get count then loops but enumerate does it all in one for loops can also have else statements switch case written match instead of switch functions declared w/ def keyword + doesn't have return type try statements have an always executed finally section + catch is called except
131
What about OOP in Python?
mixes procedural + OO (multi-paradigm) camel case just for classes constructor = def __init__ (): self keyword works like this but needs to be written as 1st param. to be used (but don't need to pass param in yourself) - needed to access any attributes
132
How does access + staticity work in Python?
attributes defined outside a method are shared (like static variables in Java/C++) everything is public in python so attributes visible outside the class!! functions declared inside classes are like static methods in C++/Java
133
How do the principles of OOP apply in Python?
multiple inheritance - class Light(Wave, Particle) polymorphism diff. due to dynamic typing - uses duck typing (if it can act as that thing it can be it) writing an attribute beginning w/ _ means it's intended as priv. thought not enforced still has super()
134
What is exception handling?
exception is an object (not necessarily an error) that we can create can raise(Python)/throw execptions exception handler called when code is in a try block + error occurs jumps to except(Python)/catch section w/ exception for param. (or in python exception "as reason")
135
How do data types in Python work + what are some examples?
contemporary language so includes complex types natively as objects w/ built-in methods e.g. lists, tuples, sets + dictionaries which can be invoked w/ .append(), .extend()., .pop(), .insert() + .sort()
136
What are the pros/cons of python having included complex types?
+ convenient (don’t need to implement yourself) + can lead to short, elegant solutions + can lead to powerful programming paradigms (e.g. functional) - harder to understand performance (underlying operations) - generic implementations rarely efficient for all tasks - data dependent - can be harder to control run-time behaviour
137
Explain the diff. Python complex types:
lists = ordered, mutable, allows dupes - useful for sequences of data tuples = immutable (cannot be changed, only vars within change) list sets = unordered, mutable, no dupes - useful for testing, as immutable cannot add sets only do union membership + eliminating dupes dictionaries = unordered, mutable, mapped by key-value pairs
138
What is packing in Python?
the ability to return/assign multiple values to 1 var using data structures signified by commas can use zip(val, val) to pack values e.g. x = 'El', 18 and name, age = x can also do name, = x to only unpack the 1st value
139
What is an iterable data type?
returns an iterable object or iterator iterators can be initialised a tuple_iter = iter(tuple) where next(tuple_iter) increments
140
What are some special functions in Python?
lambda() = small anonymous func that takes any no. of param + 1 expression filter() = returns bool + iterable w/ items that satisfy a condition map() = takes func + applies to each item in struct. reduce() = takes func + performs it on each element to reduce to 1 value
141
What is a special rule about Python readability?
lines is max 79 chars so break around binary + arithmetic operators (typically after)
142
What is a context manager? What is a generator?
context manager automatically closes a resource when you're done w/ it assign by with open(resource opening) as name generator = iterator that incrementally yields the values one at a time used to avoid creating intermediate data structs
143
What are features of good coding style?
- proper indentation + bracing - meaningful variable names - properly written variable names (camelCase or underscores depending on language) - proper spacing between operators - each statement on its own line