IF Statements and Loops in Solidity

In this article, I am going to be showing you the basic concept of conditionals also known as IF statements, with an example and how you can write them in Solidity.

Conditionals in Solidity allows you to execute code based on the pre-defined criteria. Conditionals in Solidity follows the same concept of conditionals in other languages like JavaScript. The general concept of conditionals is:

If the condition is met, execute the task.

If not then, do something else.

Now, Let's create a function to check if a number is even or not in solidity using conditionals.

Conditionals 1.PNG In this Function, we first declare the name of the function after the function keyword.

  • Next, we pass in the parameter and the data type which is uint. This means that the function will only accept an unsigned integer as the value.

  • The function is declared public with the public keyword and returns a boolean as its result.

  • We use a modulo operator, which checks the remainder after division. from the function, if the remainder is equal to zero, then it is even. If not it is odd.

This is basically the idea behind conditionals in Solidity. Let us see how conditionals can be created inside loops. We will create a function that counts a set of odd numbers.

Conditionals 2.PNG

In the code above, we first store an Array of numbers in the numbers Array.

  • Then in the countoddNumbers function, we loop through the array of Numbers to check for odd Numbers. It checks if the number is odd from the isNumberOdd function.

  • In the IF statement, if the number is odd, then we increment the count by 1.(The operator ++ does this). If the number is not odd, then we skip the number. Once the loop is finished then it will return the total numbers of the odd numbers that are in the array of numbers.

This is Day8 of my learning journey to becoming a Blockchain developer. You can follow me on Twitter to follow my learning Journey into Blockchain development.