Comprog Midterm Reviewer1
Comprog Midterm Reviewer1
types?
Use the dynamic keyword. It allows the variable to hold values of any data type.
• How do you declare an empty list in Dart?
You can declare an empty list with List<dynamic> list = []; or simply var list = [];.
• Describe the symbol used in Dart to access elements within a Map.
Use square brackets [] with the key inside to access elements, e.g., map[key].
• What result does the expression print(5 ~/ 2) produce in Dart?
The expression uses integer division, so it outputs 2.
• In Dart, how would you declare a constant integer variable with the value 10?
Use const int myConst = 10;.
• If you create a list with [1, 2, 3], add an element 4 to it, and check its length, what would
the length be?
If you start with [1, 2, 3], add 4, the length becomes 4.
• Explain the purpose of using the ? symbol when declaring a variable in Dart.
It allows the variable to hold a null value, making it nullable, as in int? x.
• What happens if you try to change a final variable after it has been assigned a value?
A final variable cannot be reassigned after being initialized. Attempting to do so will
cause a compilation error.
• What kind of error occurs if you declare var x = 5 and later try to assign a string to x?
Dart infers x to be an integer. Assigning a string later would cause a type error.
• Why might you choose to use a Map instead of a List in Dart?
Use a Map when you need key-value pairs, allowing for more complex relationships
between elements.
• How would you iterate over all key-value pairs in a Dart Map?
Use for (var entry in map.entries) to get each key-value pair.
• Describe how you would add multiple elements to a Dart List in one operation.
Use addAll(), e.g., list.addAll([4, 5, 6]);.
• How can you check if a specific key exists within a Map in Dart?
Use the containsKey() method, e.g., map.containsKey(key);.
• What is the best way to create a nested list with 3 rows and 4 columns in Dart?
Use List.generate(3, (_) => List.filled(4, 0));
• If you have a nested list, how would you access the second element of the third sub-list?
nestedList[2][1].
• Identify the error in the following code: Map<String, int> scores = {'John': 85,
'Mary': '90', 'Bob': 78};
'90' should be an integer, not a string.
• In nested loops, what happens with the outer loop when the inner loop completes all its
iterations?
The outer loop progresses to its next iteration once the inner loop completes.
• Given a nested loop where the outer loop iterates twice and the inner loop iterates three
times, list the output pattern if each loop's variable is printed.
For two outer and three inner iterations, you'd see pairs like (0,0), (0,1), (0,2), (1,0),
(1,1), (1,2).
• In a nested Map structure, what is the effect of using an incorrect key type?
Dart will throw a runtime error if you try to access a Map with a key of the wrong
type.
• If you assign a list to a new variable, then add an element to the new variable, what will
happen to the original list?
Both the new and original lists will reflect the addition if the new variable is just a
reference to the same list.
• What loop structure would be most effective for iterating through each key-value pair in a
Map?
A for-in loop over map.entries.
• When choosing between nested Lists and nested Maps in Dart, what factors should you
consider?
Use nested Lists for simple, grid-like data and Maps for data with specific keys or
hierarchical relationships.
• What’s a recommended practice for handling null values within Maps?
Consider using the null-aware operator ?. or putIfAbsent to safely access values.
• Which control structure would be the most suitable for validating user input that requires
different conditions?
A switch statement or if-else chain can be effective for multiple conditions.
• If you needed to implement a basic caching system, what data structure would you
choose?
Use a Map, as it allows quick access to values by keys.
• Describe how you could implement a queue using a Dart List.
Use add() to enqueue and removeAt(0) to dequeue.
• To perform matrix multiplication in Dart, what kind of loop structure would you use?
Use nested for loops to access each element by row and column.
• How can you convert the values of a Map to a List in Dart?
Use map.values.toList();.
This will output {'a': 1, 'b': 2, 'c': 3} as 'c' is added with a value of 3.
• How would you remove all elements from a List that meet a specific condition?
Use removeWhere((element) => condition);.
• In Dart, what is the correct approach to combine the contents of two Maps?
Use the spread operator, e.g., {...map1, ...map2};
• Given a list [1, 2, 3], if you want to create a new list where each element is doubled,
how would you do that?
Use list.map((e) => e * 2).toList();
• What is a safe way to access values in a nested Map structure in Dart?
Use cascading ? (null-aware) operators, e.g., map['key1']?['key2'].
• If you have a list of numbers, and you want to print only the even numbers, how would
you accomplish this?
Use list.where((e) => e % 2 == 0).forEach(print);
• Which loop structure would be most efficient for transforming each element in a List?
Use map() to apply a function to each element, creating a new list.
• In Dart, what’s the recommended method for handling exceptions?
2. Collections
Lists
- Declaration
List<int> numbers = [1, 2, 3];
var names = ['John', 'Jane'];
- Common Operations
- `add()`: Add single element
- `addAll()`: Add multiple elements
- `removeAt()`: Remove at index
- `remove()`: Remove specific element
- `length`: Get size
- `contains()`: Check existence
Maps
- Declaration
Map<String, int> scores = {
'John': 90,
'Jane': 95
};
- Common Operations
- Access: `map['key']`
- Check key: `containsKey()`
- Add/Update: `map['key'] = value`
- Remove: `remove('key')`
- For-in Loop
for (var item in list) {
print(item);
}
- forEach
list.forEach((item) => print(item));
Conditionals
if (condition) {
// code
} else if (otherCondition) {
// code
} else {
// code
}
5. Null Safety
- Null Safety Operators
- `?`: Nullable type
- `!`: Null assertion
- `??`: Null coalescing
- `?.`: Safe navigation
6. Error Handling
try {
// Code that might throw error
} catch (e) {
// Handle error
} finally {
// Always executed
}
2. Collection Efficiency
- Lists for ordered sequences
- Maps for key-value pairs
- Choose based on access patterns
3. Best Practices
- Use null safety features
- Handle errors properly
- Follow modular programming principles
- Use appropriate data structures
1. List Transformations
// Map transformation
var numbers = [1, 2, 3];
var doubled = numbers.map((x) => x * 2).toList();
// Filter
var evens = numbers.where((x) => x.isEven).toList();
2. Map Operations
// Merging maps
var map1 = {'a': 1};
var map2 = {'b': 2};
var merged = Map.from(map1)..addAll(map2);
// Safe access
var value = map['key']?['nested'];
3. Loop Patterns
// Nested loops
for (var i = 0; i < 3; i++) {
for (var j = 0; j < 3; j++) {
print('$i$j');
}
}