KotlinJava

← Prev

Index

Next →

Kotlin
Java

# Functions and Algorithms

Functions are so important that we’re going to continue getting more practice with them. We’ll also discuss the connection between functions and algorithms, the conceptual heart of computer science.

Throughout this lesson we’ll return to bits of code that we previous implemented as snippets and reimplement them as methods. We’ll also use this as a chance to reinforce some important programming patterns that we’ve already been using.

## Array SearchArray Search

Next, let’s revisit the code we wrote for array search, rewrite it is a method, and then test it using some sample inputs.

// Array Search

## Array Is All LargerArray Is All Larger

Our next practice problem has a tricky loop setup. Let’s review that together, and then you can attempt the problem itself.

// Array Is All Larger Setup
Created By: Geoffrey Challen
/ Version: 2022.2.0

Write a method `arrayIsAllLarger` that, given two `Int` arrays, returns `true` if all the values in the first array are larger than or equal to all the values in the same position in the second array. If the first array is longer than the second array, or the second array is longer than the first array, then the extra values can be ignored. If either array is empty, return `false`.

For example, given `{1, 2, 4}` and `{0, 1, 7}`, you should return `false`, since `7` is greater than `4`. Given `{1, 2, 4}` and `{0, 1}` you should return `true`, since the first two values of the first array are greater than the first two values of the second array. Given `{1, 2, 4}` and `{0, 1, 3, 8}`, you should return `true`, since the first three values of the first array are greater than the first three values of the second array. Given `{1, 2}` and `{1, 2}`, you should return `true`, since all values in the two arrays are equal.

## Array SumArray Sum

Now, let’s revisit the code we wrote for array sum, rewrite it is a method, and then test it using some sample inputs.

// Array Sum

As a bit of homework support, let’s talk through how to approach this lesson’s homework problem, since it has another interesting loop setup. We’ll also demonstrate how we can modify the values of arrays that are passed to methods.

Create a method named `catchupGrading` that accepts an array of `Double` values and implements the following catch-up grading policy. Given a score on Quiz N, if a student does better on the next quiz (Quiz N + 1), then you should replace their score on Quiz N with the average of their score on Quiz N and their score on Quiz N + 1. Otherwise, their score on Quiz N is unchanged. Return the number of times that the student does strictly better on the next quiz than they did on the previous one.
Scores are stored in the array in order. So, given an array with the scores `{100.0, 80.0, 90.0}`, you would modify the array to contain `{100.0, 85.0, 90.0}`, and return 1.