Kotlin Program: Check number divisibility by 7

Kotlin Control Flow: Exercise-2 with Solution

Write a Kotlin program to check if a given number is divisible by 7.

Sample Solution:

Kotlin Code:

fun main()
{
val number = 14
//val number = 17
println("Number is \$number")
if (number % 7 == 0)
{
println("The number is divisible by 7.")
}
else
{
println("The number is not divisible by 7.")
}
}

Sample Output:

Number is 14
The number is divisible by 7.

Number is 17
The number is not divisible by 7

Explanation:

In the above exercise,

• The user is prompted to input a number using println() and readLine().
• The input is read as a String and converted to an Int using toIntOrNull().
• If the conversion is successful and the number is not null, the program checks if it is divisible by 7 using the modulo operator %:
• If the number modulo 7 equals 0, it means the number is divisible by 7, and the corresponding message is printed.
• If the number modulo 7 does not equal 0, it means the number is not divisible by 7, and the corresponding message is printed.
• If the input is invalid (null), an error message is displayed.

Kotlin Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿