Increment and decrement in solidity

Hello guys, in this article, I will be showing us how to increment and decrement in solidity. First step is to declare the solidity compiler version followed by contract with name Michael.

pragma solidity ^0.5.0;
contract Michael{

}

Next step is to declare variable count with variable type uint and then set the visibility to public.

pragma solidity ^0.5.0;
contract Michael{

uint public count;

}

Brilliant, you are getting it.

Now let declare function called increase, set visibility to public

function increase() public {

}

Put this inside the function.

count +=1;

It simply means that the state variable count will be increased by 1 anytime the function increase is called.

There is another method which is method 2 to achieve thesame result as above code.

count = count +1;

Note: you cannot use the two methods together, you have to choose one.

See the full code below.

pragma solidity ^0.5.0;
contract Michael{

uint public count;

function increase() public {
    count +=1;

}

}

Remix - Ethereum IDE - Opera 02-Oct-22 6_01_05 AM.png

We are done with increase function, Next is to crease function called decrease and set it to public.

function decrease() public {

}

Since we want to decrease count by 1, the code that will be inside the decrease function will be.

count -= 1;

The above function will decrease the value of count variable by 1. Another way of writing it is

count = count -1;

Note: only pick on of the methods, do not use the two together.

function decrease() public {
count -= 1;
}

Here is our full code.

pragma solidity ^0.5.0;
contract Michael{

uint public count;

function increase() public {
    count +=1;

}

function decrease() public {
count -= 1;
}

}

Let compile and deploy. To compile, press control + s , look for deploy button and deploy to remix testnet.

Immediately you will see count, increase and decrease.

If you click on count, the result will be zero. If you click on increase, the value of count will increase by one and vise-versa.

Remix - Ethereum IDE - Opera 02-Oct-22 6_12_37 AM.png

Note: you can set count to a default value like this

uint public count =100;