Kotlin coding test course, Sum of Numbers

Coding tests play an important role in modern hiring processes. In the preparation process, solving algorithm problems is a very significant part. In this course, I will detail the process of solving an algorithm problem that calculates the sum of given numbers using Kotlin.

Problem Description

There are N given integers. Write a program that takes the N integers as input and prints their sum.

Input Format:
The first line contains an integer N (1 ≤ N ≤ 1000).
The second line contains N integers separated by spaces. Each integer is between -1000 and 1000.

Output Format:
Print the sum of the N integers provided as input.

Example Problem

Input:
5
1 2 3 4 5
Output:
15

Approach to the Problem

This problem is a very basic one, where we store the given integers in an array and then calculate their sum. Since Kotlin allows us to easily handle lists and various collections, we can use it to solve the problem.

The general approach is as follows:

  1. Read the two lines of data provided as input.
  2. Read the integer N from the first line.
  3. Read N integers from the second line and store them in a list.
  4. Sum all values in the list to find the total.
  5. Print the sum.

Kotlin Implementation

Now, based on the method above, let’s implement it in Kotlin. Below is the implemented code:

        
        import java.util.Scanner

        fun main() {
            val scanner = Scanner(System.`in`)
            
            // Read N from the first line
            val N = scanner.nextInt()
            var sum = 0
            
            // Read N numbers from the second line
            for (i in 0 until N) {
                sum += scanner.nextInt()
            }
            
            // Print the sum
            println(sum)
        }
        
    

Code Explanation

The above code functions in the following order:

  • Uses Scanner to read input: Scanner helps to receive input.
  • Reads N: Reads the integer N from the first line.
  • Uses a for loop to read and add numbers: Through N iterations, it collects each integer and adds it to sum.
  • Outputs the result: Prints the final sum.

Code Testing

You can try various inputs to test the written code. For example:

        
        Input:
        3
        10 -5 2
        
    

When given the above input, the program will display the following output:

        
        Output:
        7
        
    

Conclusion

In this course, we learned how to solve a simple problem of calculating the sum of numbers using Kotlin. By effectively utilizing basic algorithms and Kotlin’s syntax, problems can be easily solved.

Such types of problems are often presented in coding tests. Practice processing various data to improve your coding skills.

In the next session, we will address more complex problems, so stay tuned!