4.15 Exercise: Sum of multiples of 3 and 5
Here's another simple but great exercise that trains your programming brain. So I want you to create this function called sum, we give it a limit and this function will return the sum of all multiples of 3 and 5 of 0 up to that limit. Here is an example. What are the multiples of 3 and 5, between 0 and 10. Well, the multiples of 3 are 3, 6 and 9 and the multiples of 5 are 5 and 10, so I'm including that number that passed as the limit. Now, if you add up these numbers, the result will be 33, and that's the problem with this function. We save the changes, and we get 33 on the console. So pause the video to finish the exercise and when you're done, come back and continue watching the correction. Here we have to start with a for loop, let i, equal to 0, as long as i is less than or equal to the limit, we want to increment i, now we want to check if i is a multiple of 3 or 5. So if i modulo 3 is equal to 0, or if i modulo 5 is equal to 0, we must now take i and add it to our sum. So here we have to declare a variable, sum, set it to 0. And if i is a multiple of 3 or 5, we have to add i to the sum. And finally, we return sum. Here I added these line breaks to separate the initialization of the actual logic from the return value. If we didn't have these breaks, this code would look a bit squashed, and therefore a bit difficult to read and understand. So, as a best practice, it's always good to break up the last line, the return statement. So we start by initializing sum to 0, and now we work on sum to add something to it. That's it for this little demo on the sum of multiples of 3 and 5, let's meet again for a very next demo.