This code adds 40 at the end of the array and updates the size.
Execution Table
Step
Operation
Array Before
Action
Array After
Size Before
Size After
1
Start
[10, 20, 30]
Check space (dynamic array assumed)
[10, 20, 30]
3
3
2
Insert element 40 at end
[10, 20, 30]
Append 40
[10, 20, 30, 40]
3
4
3
Update size
[10, 20, 30, 40]
size = size + 1
[10, 20, 30, 40]
4
4
4
Print array
[10, 20, 30, 40]
Output array
[10, 20, 30, 40]
4
4
💡 Insertion done, size updated, array now has 4 elements.
Variable Tracker
Variable
Start
After Step 1
After Step 2
After Step 3
Final
arr
[10, 20, 30]
[10, 20, 30]
[10, 20, 30, 40]
[10, 20, 30, 40]
[10, 20, 30, 40]
size
3
3
4
4
4
new_element
40
40
40
40
40
Key Moments - 3 Insights
Why do we update the size after insertion and not before?
Because the size variable represents the number of elements currently in the array. We only increase it after successfully adding the new element, as shown in step 3 of the execution_table.
What happens if the array is full and we try to insert?
In dynamic arrays (like Python lists), the array resizes automatically before insertion (step 1). In fixed-size arrays, insertion would fail or require manual resizing.
Why do we append the element at the end and not at the start?
Appending at the end keeps existing elements in order and is efficient. Inserting at the start would require shifting all elements, which is slower.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the size of the array after step 2?
A3
B2
C4
D0
💡 Hint
Check the 'Size After' column for step 2 in the execution_table.
At which step does the array actually get the new element 40?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look at the 'Action' and 'Array After' columns in the execution_table.
If we forget to update the size after insertion, what will be the size shown after step 4?
A5
B3
C4
D0
💡 Hint
Refer to the 'size' variable changes in variable_tracker and the importance of step 3.
Concept Snapshot
Array Insertion at End:
- Add new element at last index
- Check space (resize if needed)
- Append element
- Update size variable
- Efficient for dynamic arrays
Full Transcript
This visual trace shows how to insert an element at the end of an array. We start with an array and its size. We check if there is space to add a new element. In dynamic arrays like Python lists, space is managed automatically. We then append the new element at the end and update the size variable to reflect the new number of elements. The final array shows the new element added at the end, and the size is increased by one.