Let’s Learn How To Code — Part 001

Cody Engel
9 min readMay 29, 2017

--

Welcome back future programmers, if this is your first time seeing this series I strongly encourage you to check out Let’s Learn How To Code — Part 000 to make sure you’ve properly been introduced to this series. We also created our very first program in that article so it’s somewhat important to read. For everyone else, in this lesson we’re going to create a very basic calculator which takes two numbers and displays the results of them when they are: added, subtracted, multiplied, divided, as well as the modulus. If you are unfamiliar with modulus then don’t worry, I’ll go into further detail in this article once we get to that part.

Thanks for the picture Caspar Rubin over on Unsplash

Let’s Get Started

To start things off, go ahead and create a new package named part_001 as well as a new Kotlin File named app. If you are unsure how to do this, please go back to part 000 and review the article. Now that you’ve created your new file let’s go ahead and start out with the following skeleton code.

fun main(args : Array<String>) {

val userInput = Scanner(System.`in`)

// Prompt the user for the first number, as an integer.

// Prompt the user for the second number, as an integer.

// calculate the following:
// first number + second number

// first number - second number

// first number * second number

// first number / second number

// first number % second number

}

As you can see we have everything document in order of what we want our program to do. I’ve also supplied our userInput variable to make things a bit easier. As you can see from the documentation we will first prompt the user for the first number which will be an integer. In programming you have several different types of numbers, the main ones are going to be integer, long, float, and double. If you only need to work with whole numbers that are no larger than ~ 2 billion then integer is the way to go. If you need something similar to an integer but require a larger number, then long is what you are looking for. If you want to do stuff with decimals but aren’t too concerned about the accuracy then float is perfect, in most cases this is about all you would need. However just like how you can use long when you need a bigger integer the same can be done for float, in this case you would use a double. For this program we are only going to be concerned with using an integer. For another explanation on these number types here’s an excellent answer on StackOverflow.

So our next step in making this program work is to fill in the logic for prompting the user for the first number.

fun main(args : Array<String>) {

val userInput = Scanner(System.`in`)

// Prompt the user for the first number, as an integer.
System.out.print("Enter the first number: ")
val firstNumber = userInput.nextLine().toInt()

// Prompt the user for the second number, as an integer.

// calculate the following:
// first number + second number

// first number - second number

// first number * second number

// first number / second number

// first number % second number

}

This should look fairly similar to our first program we wrote with the exception of the very last part of the second line toInt() is something new, so what exactly is it doing?

I suppose the first thing I should explain is what the . is and briefly what it means. In almost every modern programming language you have something called functions or methods, they are essentially the same thing and it usually boils down to which language you are working in. In Kotlin they are called functions, so I will refer to them as that. You may be familiar with functions from a math class, they are referred to as f(x) and they tell you to do some operation on the value passed in between the parenthesis. For our toInt() function it doesn’t have any arguments and so the assumption is that it will operate on whatever object has that function. At this point I realize I’m probably going a little too in-depth so I’ll digress.

Make sure you enable “Show quick documentation on mouse move”.

So the . allows you to run a function, but what does the function actually do? According to the documentation toInt() parses a string as an Int and returns the result. Throws NumberFormatException if string is not a valid representation of a number. Okay cool, so it will take our input from the keyboard (the string) and it will return an integer representation of that providing it is an integer. If you type in non-numbers into this program it will end up crashing, and for the purpose of this program we are okay with that. In the future I will show you how to handle exceptions to prevent your application crashing.

If you hover over the function you should see this documentation pop-up.

Alright cool, so now it’s time to ask our user for the second number. This is going to be nearly identical to what we’ve already done so I’ll leave that part up to you. The next part I want to talk about is how to actually perform these mathematical operations on our integers as well as how to display them to the user. So let’s add our two numbers together, our program should now look something like this.

fun main(args : Array<String>) {

val userInput = Scanner(System.`in`)

// Prompt the user for the first number, as an integer.
System.out.print("Enter the first number: ")
val firstNumber = userInput.nextLine().toInt()

// Prompt the user for the second number, as an integer.
System.out.print("Enter the second number: ")
val secondNumber = userInput.nextLine().toInt()

// calculate the following:
// first number + second number
System.out.println("$firstNumber + $secondNumber = ${firstNumber + secondNumber}")

// first number - second number

// first number * second number

// first number / second number

// first number % second number

}

Kotlin makes this very concise for us, in another language such as Java or C++ you would have a very verbose solution which can be a little easier for learning but it doesn’t make programming very fun. Strings in Kotlin are very powerful. You can provide a normal static string such as val kotlinIsFun = "Kotlin is fun!" which will always display that exact message. You can also provide variables inside of the string by providing a $ followed by the variable name. So we could also have something like this.

val thoughtsOnKotlin = "terrible"
val kotlinIs = "Kotlin is $thoughtsOnKotlin"

So now if you change the value of thoughtsOnKotlin the output of kotlinIs would also change. Okay so that should explain what "$firstNumber + $secondNumber = " is doing. If your first number is 3 and your second number is 2 then you’ll see 3 + 2 = displayed as output. However I said that Strings in Kotlin are very powerful so wouldn’t it be nice if you could perform your math within the string? Well you can, by providing the string ${...} where the dots denotes your logic. Essentially what you are doing is providing the string a lambda which is just an inline function. For the purpose of this article just realize that you can perform logic inside of a string using this format. In the future we’ll do stuff with lambdas but that’s a little advanced for where we are at in our journey.

So when we include ${firstNumber + secondNumber} we are saying within this block treat this as if it wasn’t inside a string and do this operation on our firstNumber and secondNumber variables. So the full output should be 3 + 2 = 5, pretty neat, huh? Also, keep in mind that anything within the curly braces does not require a dollar sign, if that doesn’t make sense right now that’s fine, it should make sense one day when you have an aha! moment.

Alright so go ahead and fill in the rest of the comments and then run your program a few times to see what outputs you get. The first four should be familiar to you, but the the last one, the one with the % may seem a little strange. Also, if your program doesn’t run, don’t worry, the solution will provided at the end of this article.

So for this output you’ll notice that 3 % 3 = 0, which makes sense, I mean we have nothing else to base it off of, right? So let’s press the run button again and give it some different input to see which value we get.

Okay so now 15 % 8 = 7, which is actually the same result as 15 — 8, and that’s also the same thing we saw for the previous run. So is modulus % just the same as subtraction? Well in a way it is close, it’s actually going to return the remainder when you divide two numbers together. So if the result is 0 then you know the first number is divisible by the second number. Let’s run the program one more time.

So we can see 27 % 4 = 3 which is exactly what our remainder would be if the we divide the numbers together. You see, 27 / 4 = 6 which means 4 will go into 27 a total of 6 times and since this is division of an integer the decimal is being dropped off (if you use a float you would notice the decimal would be intact). So then if we do 27 — 24 = 3 we can see that our remainder is 3 which is the result we get.

So when does this actually matter? Honestly, I haven’t used modulus too often in the real world, but it’s good to know about. The reason being is this single operation which is given to you for free just took me three paragraphs to explain. Sure I can find the remainder without modulus but it require I first divide the numbers followed by multiplying them by that result and then subtracting that result from the original number. Confused? Don’t feel bad, the point I’m trying to make is that by knowing about this operator you can now solve problems which require modulus very easily.

This is what my final program looks like. Yours may look different, that’s okay as long as the output is similar.

So the final program should look something like that. If you found yourself struggling through this article please let me know in the comments section, my goal is to help you learn how to program in Kotlin and if you had trouble there is a good chance that’s my fault. Likewise, if you enjoyed this article then please click the heart, it lets me know that I’m doing something right and it also lets your friends know that you found something cool.

Until next time, try to play around with what you currently know and create your own program. I’d recommend just creating a new Kotlin file under part_001 and instead of naming it app name it something like playground_app or really anything else, as long as it has the main function inside of it you should be able to run it.

Once you are ready, feel free to check out Part 002 where we start working with control flows.

--

--