A continuation of The Building Blocks of Every Programming Language – Part 1
In the last post we went into variables, mathematical operations, and conditionals. Now things are going to get really interesting as we go into loops and functions.
Loops let the programmer iterate over any variable. You can even put a conditional inside a loop, and do even more awesome things. Suppose you wanted to find how many numbers are divisible by 7 from 1 to 1000. Doing so by hand would be terrible, but it can be accomplished in just a few lines of code. I’m using Python as the programming language to implement this solution because it is easy to read.
counter = 0 for number in range (1,1001): if number % 7 == 0: counter = counter + 1 print counter
Where loops get really advanced is when you start including loops within loops. My VBA professor called this “power programming” because implementing it in VBA allows the programmer to navigate the entire spreadsheet, cell by cell.
Functions (also called subroutines)
Functions allow you to break code up into chunks that can be called easily for multiple flexible problems. From the above example, if we wanted to find all of the numbers divisible by 3 or 7, we could change the code easily. But then what if we were asked to subtract the numbers divisible by 7 from the numbers divisible by 3? We would have to rewrite it again.
Instead, it would be easier to create two functions: one for finding numbers divisible by 3, and another for finding numbers divisible by 7. Just like in mathematical functions, we can also provide inputs. So, if we wanted to find all the numbers from 1 to 10000 instead of 1 to 1000, we can easily have the range be a variable.
def divBy3(limit): counter = 0 for number in range (0, limit): if number % 3 == 0: counter = counter + 1 return counter print divBy3(10000)
We can even go one step farther and create a more general function with two variables, one for the range, and another for the number whose multiples we want to find.
def divByInt(myInt, limit): counter = 0 for number in range (0, limit): if number % myInt == 0: counter = counter + 1 return counter print divByInt(3, 10000)
Now we can solve the problem of subtracting the number of multiples of 7 from the number of multiples of 3 very easily.
print divByInt(3, 10000) – divByInt(7, 10000)