0
0
Blockchain / Solidityprogramming~30 mins

Arrays (fixed and dynamic) in Blockchain / Solidity - Mini Project: Build & Apply

Choose your learning style9 modes available
Working with Fixed and Dynamic Arrays in Solidity
📖 Scenario: You are building a simple smart contract to manage a list of favorite numbers. Some numbers are fixed and cannot be changed, while others can be added dynamically by users.
🎯 Goal: Create a Solidity contract that uses both fixed-size and dynamic arrays to store numbers. You will initialize a fixed array, set a limit for adding numbers dynamically, add numbers to the dynamic array, and finally display all stored numbers.
📋 What You'll Learn
Create a fixed-size array called fixedNumbers with exactly 3 numbers: 10, 20, and 30
Create a dynamic array called dynamicNumbers to store unsigned integers
Create a variable called maxDynamicNumbers set to 5 to limit additions to the dynamic array
Write a function addNumber(uint number) that adds a number to dynamicNumbers only if it has less than maxDynamicNumbers elements
Write a function getAllNumbers() that returns both arrays combined as a single array
💡 Why This Matters
🌍 Real World
Smart contracts often need to store fixed and changing lists of data, like token balances or user inputs.
💼 Career
Understanding arrays in Solidity is essential for blockchain developers building decentralized applications.
Progress0 / 4 steps
1
Create a fixed-size array with 3 numbers
Create a fixed-size array called fixedNumbers of type uint[3] and initialize it with the numbers 10, 20, and 30 inside the contract.
Blockchain / Solidity
Need a hint?

Use uint[3] fixedNumbers = [10, 20, 30]; inside the contract to create the fixed array.

2
Add a dynamic array and a max limit variable
Add a dynamic array called dynamicNumbers of type uint[] and a variable called maxDynamicNumbers set to 5 inside the contract.
Blockchain / Solidity
Need a hint?

Use uint[] dynamicNumbers; for the dynamic array and uint maxDynamicNumbers = 5; for the limit.

3
Write a function to add numbers to the dynamic array with a limit
Write a public function called addNumber that takes a uint number as input. Inside the function, add the number to dynamicNumbers only if the length of dynamicNumbers is less than maxDynamicNumbers.
Blockchain / Solidity
Need a hint?

Use dynamicNumbers.length to check the size and dynamicNumbers.push(number); to add.

4
Create a function to return all numbers combined
Write a public view function called getAllNumbers that returns a uint[] memory array containing all numbers from fixedNumbers followed by all numbers from dynamicNumbers. Combine both arrays inside the function.
Blockchain / Solidity
Need a hint?

Create a new array with size equal to the sum of both arrays, copy elements from each, then return it.