0% found this document useful (0 votes)
18 views6 pages

Comprog Midterm Reviewer1

The document provides an overview of Dart programming fundamentals, covering variable declaration, collections (Lists and Maps), nested data structures, control flow structures, null safety, error handling, and best practices. It includes examples and common operations for each topic, emphasizing the use of dynamic types, null safety features, and efficient data structures. Additionally, it highlights key concepts and recommended practices for effective Dart programming.

Uploaded by

sprinklesncakkey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views6 pages

Comprog Midterm Reviewer1

The document provides an overview of Dart programming fundamentals, covering variable declaration, collections (Lists and Maps), nested data structures, control flow structures, null safety, error handling, and best practices. It includes examples and common operations for each topic, emphasizing the use of dynamic types, null safety features, and efficient data structures. Additionally, it highlights key concepts and recommended practices for effective Dart programming.

Uploaded by

sprinklesncakkey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

• In Dart, what keyword allows you to declare a variable capable of holding different data

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();.

• What would be the result of running this code in Dart?

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?

Use try-catch blocks, with finally if needed for cleanup.

Dart Programming Fundamentals

1. Variables and Data Types


- Variable Declaration
- `var`: Type inference based on initial value
- `dynamic`: Can change type during runtime
- `final`: Can be set only once
- `const`: Compile-time constant

var x = 5; // Type inferred as int


dynamic y = 'hello'; // Can change type
final z = 10; // Cannot be changed
const pi = 3.14; // Compile-time constant

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')`

3. Nested Data Structures


Nested Lists
// 2D List/Matrix
List<List<int>> matrix = [
[1, 2, 3],
[4, 5, 6]
];
// Access: matrix[row][column]
Nested Maps
Map<String, Map<String, dynamic>> student = {
'John': {
'age': 20,
'grades': {'math': 90, 'science': 85}
}
};

4. Control Flow Structures


Loops
- For Loop
for (var i = 0; i < 5; i++) {
print(i);
}

- 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

String? nullableName; // Can be null


String name = nullableName ?? 'Default'; // Default if null

6. Error Handling
try {
// Code that might throw error
} catch (e) {
// Handle error
} finally {
// Always executed
}

7. Key Concepts to Remember


1. Type System
- Dart is statically typed
- Type inference is available
- All types are objects

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

8. Common Operations to Practice

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');
}
}

You might also like