w3resource

Kotlin Program: Check number divisibility by 7


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


Pre-Knowledge (Before you start!)

  • Basic Kotlin Syntax.
  • Kotlin Functions.
  • Variables in Kotlin.
  • Modulo Operator.
  • Conditional Statements.
  • String Interpolation.
  • Printing Output.

Hints (Try before looking at the solution!)

  • Define the main() Function.
  • Declare a Number Variable.
  • Display the Number.
  • Check Divisibility.
  • Test with Different Numbers.
  • Common Errors to Avoid:
    • Forgetting the modulo operator.
    • Misplacing logic in if-else statements.
    • Using assignment instead of comparison.

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.

Go to:


PREV : Check a number positive, negative, or zero.
NEXT : Check vowel or consonant.

Kotlin Editor:


Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.