Categories
3. Variables, Operators, Arrays and mapping

Difference between Transbase and UniData,UniVerse

1. Transbase :
It is a resource-optimized, high-performance, universally applicable RDBMS, developed and maintained by Transaction Software GmbH, Munich. It is a relational database management system that supports all important functions of the SQL standard. The database of Transbase is extensible via additional functions and custom data types also provide parallel execution of queries via dynamic multithreading technology.

2. UniData, UniVerse :
It is a MultiValue database and application server with SQL mapping layer and meta database capabilities. UniData makes for easier database design, eliminating the constraints of SQL normalization. UniVerse is a component of the MultiValue application platform, Its advantages is fast, flexible data server for developing enterprise apps. UniVerse-based applications maximizing processing throughput of available resources, dynamically allocate available resources.

Difference between Transbase and UniData, UniVerse :

S.NO.TransbaseUniData, UniVerse
1.It was developed by Transaction Software GmbH and initially released in 1987.It was developed by Rocket Software and initially released in 1985.
2.FreeBSD, Linux, macOS, Solaris, Windows, are the server operating systems of Transbase.AIX, HP-UX, Linux, Solaris, Windows are server operating systems of UniData, UniVerse.
3.Its primary database model is Relational DBMS.Its primary database model is Multivalue DBMS.
4.It supports CC#C++JavaJavaScriptKotlin, Objective-C, PHP and Python programming languages.It supports .Net, Basic, C and Java programming languages.
5.ADO.NET, JDBC, ODBC, Proprietary native API are the APIs and other access methods of Transbase.Proprietary protocol, RESTful HTTP API, Java API, JDBC, ODBC, OLE DB, SOAP-based API are the APIs and other access methods of UniData, UniVerse.
6.It has Data Schema.It has schema-free Data Schema.
7.It has implementation language C and C++.It has implementation language C.
8.Transbase has Transaction concepts.ACID (Atomicity, Consistency, Isolation, and Durability) is the transaction concept in UniData, UniVerse.
9.Replication method of Transbase is Master-Slave Replication.Replication method of UniData, UniVerse is also Master-Slave Replication.
10.It holds Immediate Consistency concept.It does not hold Consistency concept.
11.It holds Foreign keys.It does not hold Foreign keys.
Categories
3. Variables, Operators, Arrays and mapping

Difference between Data Privacy and Data Protection

1. Data Privacy :
Data Privacy refers to the proper handling of data means how a organization or user is determining whether or what data to be shared with third parties. Data privacy is important as it keeps some data secret from others/third parties. So we can say data privacy is all about authorized access. It is also called as Information privacy.

Example –
In Bank, A lot of customers have their account for monetary transactions. So the bank needs to keeps customers data private, so that customers identity stays safe and protected as much as possible by minimizing any external risks and also it helps in maintaining the reputation standard of banks.

2. Data Protection :
Data Protection refers to the process of keeping safe to important information. In simple it refers protecting data against unauthorized access which leads to no corruption, no compromise, no loss and no security issues of data. Data protection is allowed to all forms of data whether it is personal or data or organizational data.

Example –
A bank has lot of customers, so the bank needs to protect all types of data including self bank records as well as customer information from unauthorized accesses to keep everything safe and to ensure everything is under the control of bank administration.

The terms Data Privacy and Data Security are used interchangeably and seems to be same. But actually they are not same. In reality they can have different meanings depending upon its actual process and use. But it is sure they are very closely interconnected and one complements the other during the entire process. So, now let’s know how Data Privacy is different from Data Protection from the below table.



Difference between Data Privacy and Data Protection :

S.No.Data PrivacyData Protection
01.Data Privacy refers maintaining secrecy or keeping control on data access.Data Protection is the process of protecting data from external risks such corruption, loss etc.
02.It is all about authorized access means it defines who has authorized access to data.It is all about unauthorized access means if anyone has not access to data then it keeps the data safe from that unauthorized access.
03.Data Privacy is a legal process/situation which helps in establishing standards and norms about accessibility.Data Protection is a technical control system which keeps data protected from technical issues.
04.Data Privacy is the regulations or policies.Data protection is the procedures and mechanism.
05.It can be said as a security from sales means holding the data from shared and sold.It can be said as s security from hacks means keeping the information away from hackers.
06.Data Privacy controls are mainly exits at the end user level. The users knows which data is shared with whom and which data they can access.Data Protection is mainly controlled by the organization or company end. They tech all the required measures to protect their data from being exposed to illegal activities.
07.Data privacy teams are made of experts with law making, policies and some engineering experts.Data protection teams are made of experts from technical background, security background etc.
Categories
3. Variables, Operators, Arrays and mapping

Solidity – Functions

A function is basically a group of code that can be reused anywhere in the program, which generally saves the excessive use of memory and decreases the runtime of the program. Creating a function reduces the need of writing the same code over and over again. With the help of functions, a program can be divided into many small pieces of code for better understanding and managing.

Declaring a Function

In Solidity a function is generally defined by using the function keyword, followed by the name of the function which is unique and does not match with any of the reserved keywords. A function can also have a list of parameters containing the name and data type of the parameter. The return value of a function is optional but in solidity, the return type of the function is defined at the time of declaration.

function function_name(parameter_list) scope returns(return_type) {
       // block of code
}
// Solidity program to demonstrate 
// function declaration
pragma solidity ^0.5.0;
  
// Creating a contract
contract Test {
  
   // Defining function to calculate sum of 2 numbers
   function add() public view returns(uint){
      uint num1 = 10; 
      uint num2 = 16;
      uint sum = num1 + num2;
      return sum;
   }
}
Declaring a Function

Output :

In the above example, you must have seen the usage of “view”. View in a function ensures that they will not modify the state of the function. The following statements if present in the function will modify the state of the function and the compiler will throw a warning.

  • Modifying state variables.
  • Emitting events.
  • Creating other contracts.
  • Using self-destruct.
  • Sending Ether via calls.
  • Calling any function which is not marked pure or view.
  • Using inline assembly containing certain opcodes.
  • Using low-level calls.

Function Calling

A function is called when the user wants to execute that function. In Solidity the function is simply invoked by writing the name of the function where it has to be called. Different parameters can be passed to function while calling, multiple parameters can be passed to a function by separating with a comma.

// Solidity program to demonstrate
// function calling
pragma solidity ^0.5.0;

// Creating a contract
contract Test {

// Defining a public view function to demonstrate
// calling of sqrt function
function add() public view returns(uint){
	uint num1 = 10;
	uint num2 = 16;
	uint sum = num1 + num2;
	return sqrt(sum); // calling function
}

//Defining public view sqrt function
function sqrt(uint num) public view returns(uint){
	num = num ** 2;
	return num;
}
}
Function Calling

Output :

Return Statements

A return statement is an optional statement provided by solidity. It is the last statement of the function, used to return the values from the functions. In Solidity, more than one value can be returned from a function. To return values from the function, the data types of the return values should be defined at function declaration.

// Solidity program to demonstrate
// return statements
pragma solidity ^0.5.0;

// Creating a contract
contract Test {

// Defining a public view function to
// demonstrate return statement
function return_example() public view returns(uint, uint, uint, string memory){
	uint num1 = 10;
	uint num2 = 16;
	uint sum = num1 + num2;
	uint prod = num1 * num2;
	uint diff = num2 - num1;
	string memory msg = "Multiple return values";
	return (sum, prod, diff, msg);
}
}

Output :

Return Statement
Categories
3. Variables, Operators, Arrays and mapping

Solidity – Types

Solidity is a statically typed language, which implies that the type of each of the variables should be specified. Data types allow the compiler to check the correct usage of the variables. The declared types have some default values called Zero-State, for example for bool the default value is False. Likewise other statically typed languages Solidity has Value types and Reference types which are defined below:

Value Types

Value type variables store their own data. These are the basic data types provided by solidity. These types of variables are always passed by value. The variables are copied wherever they are used in function arguments or assignment. Value type data types in solidity are listed below: 

  • Boolean: This data type accepts only two values True or False.
  • Integer: This data type is used to store integer values, int and uint are used to declare signed and unsigned integers respectively.
  • Fixed Point Numbers: These data types are not fully supported in solidity yet, as per the Solidity documentation. They can be declared as fixed and unfixed for signed and unsigned fixed-point numbers of varying sizes respectively.
  • Address: Address hold a 20-byte value which represents the size of an  Ethereum address. An address can be used to get balance or to transfer a balance by balance and transfer method respectively.
  • Bytes and Strings: Bytes are used to store a fixed-sized character set while the string is used to store the character set equal to or more than a byte. The length of bytes is from 1 to 32, while the string has a dynamic length. Byte has an advantage that it uses less gas, so better to use when we know the length of data.
  • Enums: It is used to create user-defined data types, used to assign a name to an integral constant which makes the contract more readable, maintainable, and less prone to errors. Options of enums can be represented by unsigned integer values starting from 0.

Example: In the below example, the contract Types initializes the values of different types of Values Types.

// Solidity program to demonstrate
// value types
pragma solidity ^ 0.5.0;

// Creating a contract
contract Types {

	// Initializing Bool variable
	bool public boolean = false;
	
	// Initializing Integer variable
	int32 public int_var = -60313;

	// Initializing String variable
	string public str = "GeeksforGeeks";

	// Initializing Byte variable
	bytes1 public b = "a";
	
	// Defining an enumerator
	enum my_enum { geeks_, _for, _geeks }

	// Defining a function to return
	// values stored in an enumerator
	function Enum() public pure returns(
	my_enum) {
		return my_enum._geeks;
	}
}

Output :

Value Types Output

Reference Types

Reference type variables store the location of the data. They don’t share the data directly. With the help of reference type, two different variables can refer to the same location where any change in one variable can affect the other one. Reference type in solidity are listed below: 

  • Arrays: An array is a group of variables of the same data type in which variable has a particular location known as an index. By using the index location, the desired variable can be accessed. The array size can be fix or dynamic.
  • Struct: Solidity allows users to create and define their own type in the form of structures. The structure is a group of different types even though it’s not possible to contain a member of its own type. The structure is a reference type variable which can contain both value type and reference type
  • Mapping: Mapping is a most used reference type, that stores the data in a key-value pair where a key can be any value types. It is like a hash table or dictionary as in any other programming language, where data can be retrieved by key.

Example: In the below example, the contract Types initializes the values of various Reference Types.

// Solidity program to demonstrate
// Reference Types
pragma solidity ^0.4.18;

// Creating a contract
contract mapping_example {

	// Defining an array
	uint[5] public array
	= [uint(1), 2, 3, 4, 5] ;
	
	// Defining a Structure
	struct student {
		string name;
		string subject;
		uint8 marks;
	}

	// Creating a structure object
	student public std1;

	// Defining a function to return
	// values of the elements of the structure
	function structure() public view returns(
	string memory, string memory, uint){
		std1.name = "John";
		std1.subject = "Chemistry";
		std1.marks = 88;
		return (
		std1.name, std1.subject, std1.marks);
	}
	
	// Creating a mapping
	mapping (address => student) result;
	address[] student_result;
}

Output :

Reference Types Output
Categories
3. Variables, Operators, Arrays and mapping

Solidity – Break and Continue Statements

In any programming language, Control statements are used to change the execution of the program. Solidity allows us to handle loops and switch statements. These statements are usually used when we have to terminate the loop without reaching the bottom or we have to skip some part of the block of code and start the new iteration. Solidity provides the following control statements to handle the program execution.

Break Statement

This statement is used when we have to terminate the loop or switch statements or some block of code in which it is present. After the break statement, the control is passed to the statements present after the break. In nested loops, break statement terminates only those loops which has break statement.

Example: In the below example, the contract Types is defined consisting of a dynamic array, an unsigned integer variable, and a function containing the while loop to demonstrate the working of the break statement.

// Solidity program to demonstrate
// use of Break statement
pragma solidity ^0.5.0;

// Creating a contract
contract Types {
	
	// Declaring a dynamic array
	uint[] data;
	
	// Declaring the state variable
	uint8 j = 0;

	// Defining the function to
	// demonstrate use of Break
	// statement
	function loop(
	) public returns(uint[] memory){
	while(j < 5) {
		j++;
		if(j==3){
			break;
		}
		data.push(j);
	}
	return data;
	}
}

Output : 

Break Statement Output

Continue Statement

This statement is used when we have to skip the remaining block of code and start the next iteration of the loop immediately. After executing the continue statement, the control is transferred to the loop check condition, and if the condition is true the next iteration starts.

Example: In the below example, contract Types is defined consisting of a dynamic array, an unsigned integer variable, and a function containing the while loop to demonstrate the working of the continue statement.

// Solidity program to demonstrate
// use of Continue statement
pragma solidity ^0.5.0;

// Creating a contract
contract Types {
	
	// Declaring a dynamic array
	uint[] data;
	
	// Declaring a state variable
	uint8 j = 0;

	// Defining a function to
	// demonstrate the use of
	// Continue statement
	function loop(
	) public returns(uint[] memory){
	while(j < 5) {
		j++;
		if(j==3){
			continue;
		}
		data.push(j);
	}
	return data;
	}
}

Output : 

Continue Statement Output
Categories
3. Variables, Operators, Arrays and mapping

Dynamic Arrays and its Operations in Solidity

The Dynamic arrays are the arrays that are allocated memory at the runtime and the memory is allocated from the heap. 

Syntax:

// declaration of dynamic array

 int[] private arr;   

How They Are Different From Fixed Size Arrays?

The fixed-size array has a fixed memory size whereas, in dynamic arrays, the size can be randomly updated during the run time which may be considered efficient with respect to the memory complexity of the code. 

Problem: How to create a dynamic array in solidity and perform its associated operations?

Solution: In this article, we will create dynamic arrays in solidity language and will perform the following operations on it:

  1. Add data in an array
  2. Get data of an array
  3. Get length of an array
  4. Get sum of elements of an array
  5. Search a particular element in an array

What is Solidity?

Solidity is a high-level language. The structure of smart contracts in solidity is very similar to the structure of classes in object-oriented languages. The solidity file has an extension .sol.

What are Smart Contracts?

Solidity’s code is encapsulated in contracts which means a contract in Solidity is a collection of code (its functions) and data (its state) that resides at a specific address on the Ethereum blockchain. A contract is a fundamental block of building an application on Ethereum.

Step 1: Open Remix-IDE.

Step 2: Select File Explorer from the left side icons and select Solidity in the environment. Click on the New option below the Solidity environment. Enter the file name as dynamicArray.sol and Click on the OK button.

Step 3: Enter the following Solidity Code. Select the same solidity version as in your code.

// Solidity program to demonstrate
// the above approach
pragma solidity ^0.6.8;
contract DynamicArray{
	
// Declaring state variable
int[] private arr;
	
// Function to add data
// in dynamic array
function addData(int num) public
{
arr.push(num);
}
	
// Function to get data of
// dynamic array
function getData() public view returns(int[] memory)
{
return arr;
}
	
// Function to return length
// of dynamic array
function getLength() public view returns (uint)
{
return arr.length;
}

// Function to return sum of
// elements of dynamic array
function getSum() public view returns(int)
{
uint i;
int sum = 0;
	
for(i = 0; i < arr.length; i++)
	sum = sum + arr[i];
return sum;
}
	
// Function to search an
// element in dynamic array
function search(int num) public view returns(bool)
{
uint i;
	
for(i = 0; i < arr.length; i++)
{
	if(arr[i] == num)
	{
	return true;
	}
}
	
if(i >= arr.length)
	return false;
}
}

Step 4: Compile the file dynamicArray.sol from the Solidity Compiler tab.

Step 5: Deploy the smart contract from the Deploy and Run Transaction tab.

Step 6: Perform various operations on the array under the deployed contracts section.

Categories
3. Variables, Operators, Arrays and mapping

What is Hashing in Solidity?

A cryptographic hash function is an algorithm that takes an arbitrary amount of data as input and produces the enciphered text of fixed size. Even a slight change in the input gives a completely different output.

Solidity provides the following cryptographic functions:

FunctionProperties
keccak256(bytes memory) returns (bytes32)Computes the Keccak-256 hash of the input
sha256(bytes memory) returns (bytes32)Computes the SHA-256 hash of the input
ripemd160(bytes memory) returns (bytes20) Compute RIPEMD-160 hash of the input
sha256(bytes memory) returns (bytes32) Computes the SHA-256 hash of the input
ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) returns (address)Recover the address associated with the public key from 
Elliptic curve signature used for cryptography or return 
Zero if an error occurs. The parameters correspond to ECDSA 
Signature values.

Ethereum uses Keccak for hashing which is similar but not the same as SHA_256. For proof of work, it uses a custom scheme called ethash which is designed to be ASIC-resistant.

Example: In the below example, a smart contract is created to take a string as input and give an 8 digit hash as an output.

// pragma version
pragma solidity ^0.6.6;

// Creating a contract
contract helloGeeks
{
	// We want hash to be of 8 digits
	// hence we store 10^8 which is
	// used to extract first 8 digits
	// later by Modulus
	uint hashDigits = 8;
	
	// Equivalent to 10^8 = 8
	uint hashModulus = 10 ** hashDigits;

	// Function to generate the hash value
	function _generateRandom(string memory _str)
		public view returns (uint)
	{
		// "packing" the string into bytes and
		// then applying the hash function.
		// This is then typecasted into uint.
		uint random =
			uint(keccak256(abi.encodePacked(_str)));
			
		// Returning the generated hash value
		return random % hashModulus;
	}

}

Input:

GeeksForGeeks

Output:

Hash value
Categories
3. Variables, Operators, Arrays and mapping

Solidity – Enums and Structs

Enums are the way of creating user-defined data types, it is usually used to provide names for integral constants which makes the contract better for maintenance and reading. Enums restrict the variable with one of few predefined values, these values of the enumerated list are called as enums. Options of are represented with integer values starting from zero, a default value can also be given for the enum. By using enums it is possible to reduce the bugs in the code.

Syntax:

enum <enumerator_name> { 
            element 1, elemenent 2,....,element n
} 

Example: In the below example, the contract Types consist of an enumerator week_days,and functions are defined to set and get the value of a variable of type enumerator.

  • Solidity
// Solidity program to demonstrate
// how to use 'enumerator'
pragma solidity ^0.5.0;

// Creating a contract
contract Types {

	// Creating an enumerator
	enum week_days
	{
	Monday,
	Tuesday,
	Wednesday,
	Thursday,
	Friday,
	Saturday,
	Sunday
	}

	// Declaring variables of
	// type enumerator
	week_days week;	
	
	week_days choice;

	// Setting a default value
	week_days constant default_value
	= week_days.Sunday;
	
	// Defining a function to
	// set value of choice
	function set_value() public {
	choice = week_days.Thursday;
	}

	// Defining a function to
	// return value of choice
	function get_choice(
	) public view returns (week_days) {
	return choice;
	}
		
	// Defining function to
	// return default value
	function getdefaultvalue(
	) public pure returns(week_days) {
		return default_value;
	}
}

Output : 

Enums

Struct

Solidity allows user to create their own data type in the form of structure. The struct contains a group of elements with a different data type. Generally, it is used to represent a record. To define a structure struct keyword is used, which creates a new data type. 

Syntax:

struct <structure_name> {  
   <data type> variable_1;  
   <data type> variable_2; 
}

For accessing any element of the structure dot operator is used, which separates the struct variable and the element we wish to access. To define the variable of structure data type structure name is used.

Example: In the below example, the contract Test consists of a structure Book, and functions are defined to set and get values of the elements of the structure.

// Solidity program to demonstrate
// how to use 'structures'
pragma solidity ^0.5.0;

// Creating a contract
contract test {

// Declaring a structure
struct Book {
	string name;
	string writter;
	uint id;
	bool available;
}

// Declaring a structure object
Book book1;

// Assigning values to the fields
// for the structure object book2
Book book2
	= Book("Building Ethereum DApps",
			"Roberto Infante ",
			2, false);

// Defining a function to set values
// for the fields for structure book1
function set_book_detail() public {
	book1 = Book("Introducing Ethereum and Solidity",
				"Chris Dannen",
					1, true);
}


// Defining function to print
// book2 details
function book_info(
)public view returns (
	string memory, string memory, uint, bool) {
			
		return(book2.name, book2.writter,
			book2.id, book2.available);
	}
	
// Defining function to print
// book1 details
function get_details(
) public view returns (string memory, uint) {
	return (book1.name, book1.id);
}
}

Output : 
 

Structs
Categories
3. Variables, Operators, Arrays and mapping

Solidity – Mappings

Mapping in Solidity acts like a hash table or dictionary in any other language. These are used to store the data in the form of key-value pairs, a key can be any of the built-in data types but reference types are not allowed while the value can be of any type. Mappings are mostly used to associate the unique Ethereum address with the associated value type.

Syntax:

mapping(key => value) <access specifier> <name>;

Creating a Mapping

Mapping is defined as any other variable type, which accepts a key type and a value type.

Example: In the below example, the contract mapping_example a structure is defined and mapping is created.

// Solidity program to
// demonstrate mapping
pragma solidity ^0.4.18;

// Defining contract
contract mapping_example {
	
	//Defining structure
	struct student
	{
		// Declaring different
		// structure elements
		string name;
		string subject;
		uint8 marks;
	}
	
	// Creating a mapping
	mapping (
	address => student) result;
	address[] public student_result;	
}

Output : 

Creating a Mapping

Adding values to mapping

As the mapping is created let’s try to add some values to the mapping for better understanding.

Example: In the below example, the contract mapping_example defines a structure, mapping is created and values are added to the mapping.

// Solidity program to
// demonstrate adding
// values to mapping
pragma solidity ^0.4.18;

// Creating contract
contract mapping_example {
	
	//Defining structure
	struct student {

		//Declaring different
		// structure elements
		string name;
		string subject;
		uint8 marks;
	}

	// Creating mapping
	mapping (
	address => student) result;
	address[] public student_result;
	
	// Function adding values to
	// the mapping
	function adding_values() public {
		var student
		= result[0xDEE7796E89C82C36BAdd1375076f39D69FafE252];

		student.name = "John";
		student.subject = "Chemistry";
		student.marks = 88;
		student_result.push(
		0xDEE7796E89C82C36BAdd1375076f39D69FafE252) -1;

	}
	
}

Output : 
 

Adding Values to mapping

Getting values

We have added values to the mapping, to retrieve the values we have to create a function that returns the values added to the mapping.

Example: In the below example, the contract mapping_example defines a structure, mapping is created, values are added to the mapping, and values are retrieved from the mapping.

// Solidity program to
// demonstrate retrieve
// values from the mapping

pragma solidity ^0.4.18;

contract mapping_example {
	
	// Defining Structure
	struct student {

		// Declaring different data types
		string name;
		string subject;
		uint8 marks;
	}
	
	// Creating mapping
	mapping (
	address => student) result;
	address[] student_result;
	
	// Function adding values to the mapping
	function adding_values() public {
		var student
		= result[0xDEE7796E89C82C36BAdd1375076f39D69FafE252];

		student.name = "John";
		student.subject = "Chemistry";
		student.marks = 88;
		student_result.push(
		0xDEE7796E89C82C36BAdd1375076f39D69FafE252) -1;

	}
	
	// Function to retrieve
	// values from a mapping
	function get_student_result(
	) view public returns (address[]) {
		return student_result;
	}
}

Output : 
 

Getting Values

Counting Mappings

Mappings can be counted so that we can know how many values are stored in mapping.

Example: In the below example, the contract mapping_example defines a structure, mapping is created, values are added to the mapping, and values are retrieved from the mapping.
 

// Solidity program to
// count number of
// values in a mapping
pragma solidity ^0.4.18;

contract mapping_example {
	
	// Defining structure
	struct student {

		// Declaring different
		// structure elements
		string name;
		string subject;
		uint8 marks;
	}
	
	// Creating mapping
	mapping (address => student) result;
	address[] student_result;
	
	//Function adding values to the mapping
	function adding_values() public {
		var student
		= result[0xDEE7796E89C82C36BAdd1375076f39D69FafE252];

		student.name = "John";
		student.subject = "Chemistry";
		student.marks = 88;
		student_result.push(
		0xDEE7796E89C82C36BAdd1375076f39D69FafE252) -1;

	}
	
	// Function to retrieve
	// values from the mapping
	function get_student_result(
	) view public returns (address[]) {
		return student_result;
	}

	// Function to count number
	// of values in a mapping
	function count_students(
	) view public returns (uint) {
		return student_result.length;
	}
}

Output : 
 

Counting Mappings
Categories
3. Variables, Operators, Arrays and mapping

Solidity – Arrays

Arrays are data structures that store the fixed collection of elements of the same data types in which each and every element has a specific location called index. Instead of creating numerous individual variables of the same type, we just declare one array of the required size and store the elements in the array and can be accessed using the index. In Solidity, an array can be of fixed size or dynamic size. Arrays have a continuous memory location, where the lowest index corresponds to the first element while the highest represents the last

Creating an Array

To declare an array in Solidity, the data type of the elements and the number of elements should be specified. The size of the array must be a positive integer and data type should be a valid Solidity type.

Syntax:

<data type> <array name>[size] = <initialization>

Fixed-size Arrays

The size of the array should be predefined. The total number of elements should not exceed the size of the array. If the size of the array is not specified then the array of enough size is created which is enough to hold the initialization.

Example: In the below example, the contract Types are created to demonstrate how to declare and initialize fixed-size arrays.

// Solidity program to demonstrate
// creating a fixed-size array
pragma solidity ^0.5.0;

// Creating a contract
contract Types {

	// Declaring state variables
	// of type array
	uint[6] data1;	
	
	// Defining function to add
	// values to an array
	function array_example() public returns (
	int[5] memory, uint[6] memory){
			
		int[5] memory data
		= [int(50), -63, 77, -28, 90];
		data1
		= [uint(10), 20, 30, 40, 50, 60];
			
		return (data, data1);
}
}

Output : 

Fixed Size Array

Dynamic Array: 

The size of the array is not predefined when it is declared. As the elements are added the size of array changes and at the runtime, the size of the array will be determined.

Example: In the below example, the contract Types are created to demonstrate how to create and initialize dynamic arrays.

// Solidity program to demonstrate
// creating a dynamic array
pragma solidity ^0.5.0;

// Creating a contract
contract Types {
	
	// Declaring state variable
	// of type array. One is fixed-size
	// and the other is dynamic array
	uint[] data
	= [10, 20, 30, 40, 50];
	int[] data1;
	
	// Defining function to
	// assign values to dynamic array
	function dynamic_array() public returns(
	uint[] memory, int[] memory){
	
		data1
		= [int(-60), 70, -80, 90, -100, -120, 140];
		return (data, data1);
	}
}

Output : 

Dynamic Array

Array Operations

1. Accessing Array Elements: The elements of the array are accessed by using the index. If you want to access ith element then you have to access (i-1)th index.

ExampleIn the below example, the contract Types first initializes an array[data] and then retrieves the value at specific index 2.

// Solidity program to demonstrate
// accessing elements of an array
pragma solidity ^0.5.0;

// Creating a contract
contract Types {

	// Declaring an array
	uint[6] data;	
	
	// Defining function to
	// assign values to array
	function array_example(
	) public payable returns (uint[6] memory){
			
		data
		= [uint(10), 20, 30, 40, 50, 60];
		return data;
}
	
// Defining function to access
// values from the array
// from a specific index
function array_element(
) public payable returns (uint){
		uint x = data[2];
		return x;
}
}

Output : 

Accessing Array Elements

2. Length of Array: Length of the array is used to check the number of elements present in an array. The size of the memory array is fixed when they are declared, while in case the dynamic array is defined at runtime so for manipulation length is required.

ExampleIn the below example, the contract Types first initializes an array[data] and then the length of the array is calculated.

// Solidity program to demonstrate
// how to find length of an array
pragma solidity ^0.5.0;

// Creating a contract
contract Types {

	// Declaring an array
	uint[6] data;	
		
	// Defining a function to
	// assign values to an array
	function array_example(
	) public payable returns (uint[6] memory){
		data = [uint(10), 20, 30, 40, 50, 60];
		return data;
}

// Defining a function to
// find the length of the array
function array_length(
) public returns(uint) {
		uint x = data.length;
		return x;
	}
}

Output : 

Length of Array

3. Push: Push is used when a new element is to be added in a dynamic array. The new element is always added at the last position of the array.

ExampleIn the below example, the contract Types first initializes an array[data],and then more values are pushed into the array.

// Solidity program to demonstrate
// Push operation
pragma solidity ^0.5.0;

// Creating a contract
contract Types {

	// Defining the array
	uint[] data = [10, 20, 30, 40, 50];
	
	// Defining the function to push
	// values to the array
	function array_push(
	) public returns(uint[] memory){
	
		data.push(60);
		data.push(70);
		data.push(80);
	
		return data;
	}
}

Output : 
 

Push operation

4. Pop: Pop is used when the last element of the array is to be removed in any dynamic array.

ExampleIn the below example, the contract Types first initializes an array[data],and then values are removed from the array using the pop function.

// Solidity program to demonstrate
// Pop operation
pragma solidity ^0.5.0;
	
// Creating a contract
contract Types {

	// Defining an array
	uint[] data
	= [10, 20, 30, 40, 50];
	
	// Defining a function to
	// pop values from the array
	function array_pop(
	) public returns(uint[] memory){
		data.pop();
		return data;
	}
}

Output : 

Pop Operation