Write a Java program using while - loop to enter any integer and display how many digits in that number are perfectly divisible by 7 if the number entered is positive else find how many of the digits are divisible by 5. Find the sum of those digits.
Answers
Question:-
- Write a Java program using while - loop to enter any integer and display how many digits in that number are perfectly divisible by 7 if the number entered is positive else find how many of the digits are divisible by 5. Find the sum of those digits.
Answer:-
package Coder;
import java.util.*;
public class Digit {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
int n = sc.nextInt();
int c = 0;
if (n > 0) // To check if entered number is positive or not
{
System.out.println("Entered number is positive");
while (n != 0)
{
int d = n % 10;
if (d % 7 == 0)
c++;
n/=10;
}
System.out.println("\nNumber of digits exactly divisible by 7=" + c);
}
else
{
System.out.println("Entered number is negative");
while (n != 0)
{
int d = n % 10;
if (d % 5 == 0)
c+=d;
n/=10;
}
System.out.println("\nSum of digits exactly divisible by 5=" + c);
}
}
}
Variable Description:-
n:- Input variable to input a number
d:- Local variable to extract the digits
c:- To count the number of digits and to find the sum of digits
•Output attached
Question:
- Write a Java program using while loop to enter any integer and display how many digits in that number are perfectly divisible by 7 if the number is positive else find how many of the digits are divisible by 5 and the sum of those digits.
Program:
This is an easy question. Read this post to get your answer.
Here comes the program. (27 lines of code).
import java.util.*;
public class NumberOp
{
public static void main(String[] args)
{
int n, d, c=0, s=0, r;
Scanner sc=new Scanner(System.in);
System.out.print("Enter a number: ");
n=sc.nextInt();
d=(n<0)?5:7;
for(;n!=0;n/=10)
{
r=n%10;
if(r%d==0)
{
c++;
s+=r;
}
}
System.out.println((d==5)?"Negative.":"Positive.");
System.out.println("Number of digits divisible by "+d+" are "+c);
if(d==5)
System.out.println("Sum of digits is: "+s);
sc.close();
}
}
Logic:
Take a number as input, check if the number is negative or positive. According to the condition, divide the number by either 5 or 7. Count the number of digits divisible by the number 5 or 7. Store them in a variable. Find the sum of those number divisible by 5 and store them in another variable. Now, display the result.
Output is attached.