Write a Java Program that takes an integer and tests whether it is divisible by 2, 4 and 5. Apply divisibility rules that say:
a. a number is divisible by 2 if the number is ending in an even digit 0,2,4,6,8.
b. a number is divisible by 4 if last 2 digits of the number are divisible by 4.
c. a number is divisible by 5 if the number is ending in 0 or 5
Answers
The given problem is solved using language - Java.
import java.util.Scanner;
public class Java{
public static void main(String s[]){
Scanner sc=new Scanner(System.in);
System.out.print("Enter a number: ");
int n=sc.nextInt();
System.out.println("Is the number divisible by 2? - "+(n%2==0));
System.out.println("Is the number divisible by 4? - "+(n%4==0));
System.out.println("Is the number divisible by 5? - "+(n%5==0));
}
}
- Accept the number from the user.
- Check if divisible by 2, 5 and 10 using modulo operator and display the result.
See the attachment for output.
Answer:
Program:-
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
int n,ch,a=0;
System.out.println("Enter a number");
n=in.nextInt();
System.out.println("Enter 1 to check the divisibilty of the number with 2");
System.out.println("Enter 2 to check the divisibilty of the number with 4");
System.out.println("Enter 3 to check the divisibilty of the number with 5");
System.out.println("Enter your choice");
ch=in.nextInt();
switch(ch)
{
case 1:
a=n%10;
if(a==0||a==2||a==4||a==6||a==8)
System.out.println(n+" is divisible by 2");
else
System.out.println(n+" is not divisible by 2");
break;
case 2:
a=n%100;//for last 2 digits
if(a%4==0)
System.out.println(n+" is divisible by 4");
else
System.out.println(n+" is not divisible by 4");
break;
case 3:
a=n%10;
if(a==5||a==0)//Divisibilty rule of 5
System.out.println(n+" is divisible by 5");
else
System.out.println(n+" is divisible by 2");
break;
default:
System.out.println("Invalid choice");
}
}
}
Logic:-
- I simply applied divisibility rule of the given numbers as per your information.
- A proper message is displayed so it is clear to a user.
- In these questions use switch case as it has multiple branching.
- 4 outputs are attached for different cases.