0
0
Blockchain / Solidityprogramming~30 mins

Function declaration and syntax in Blockchain / Solidity - Mini Project: Build & Apply

Choose your learning style9 modes available
Function Declaration and Syntax in Blockchain Smart Contracts
📖 Scenario: You are creating a simple blockchain smart contract to store and retrieve a favorite number. This contract will help you understand how to declare and use functions in Solidity, the language used for Ethereum smart contracts.
🎯 Goal: Build a smart contract with a function to set a favorite number and another function to get that number.
📋 What You'll Learn
Create a state variable to store a number
Declare a function called setFavoriteNumber that takes a number as input and stores it
Declare a function called getFavoriteNumber that returns the stored number
Use correct Solidity function syntax including visibility and return types
💡 Why This Matters
🌍 Real World
Smart contracts on blockchains store and manage data securely. Functions let users interact with this data.
💼 Career
Understanding function declaration and syntax is essential for blockchain developers writing smart contracts.
Progress0 / 4 steps
1
Create a state variable
Create a public state variable called favoriteNumber of type uint to store the number.
Blockchain / Solidity
Need a hint?

Use uint public favoriteNumber; inside the contract to create the variable.

2
Declare the setter function
Add a public function called setFavoriteNumber that takes a uint parameter named _number and sets favoriteNumber to this value.
Blockchain / Solidity
Need a hint?

Define the function with function setFavoriteNumber(uint _number) public and assign favoriteNumber = _number;.

3
Declare the getter function
Add a public view function called getFavoriteNumber that returns a uint and returns the value of favoriteNumber.
Blockchain / Solidity
Need a hint?

Use function getFavoriteNumber() public view returns (uint) and return the variable.

4
Test the contract output
Print the value returned by getFavoriteNumber() after setting it to 42 using setFavoriteNumber(42). Use comments to show the expected output.
Blockchain / Solidity
Need a hint?

In Solidity, you cannot print directly. Use comments to show calling setFavoriteNumber(42) then getFavoriteNumber() returns 42.