Question 7

a) The program accepts a number with four digits. If the number is with four digits returns true if the products of digits at even places is divisible by sum of digits at odd places

n = 1234
2 * 4 / 1 + 3      
8 / 4    TRUE                  

n= 2157
1 * 7 / 2 + 5        
7 / 7  TRUE   
           
n = 123
wrong input                    

n = 1342
3*2 /1+4
6 /5  FALSE
Some of the members of the class is given below
Class name   OddEven
Data members/instance variables:
n     : to store number with 4 digit
Member functions/methods:
OddEven()  : constructor that assigns 2157 to n
OddEven(int nn)  : parameterized constructor
void accept() : accepts  number with four digits   
int reverse(int n)  : returns a reversed number
int prodEven()  : returns the products of the even digits of the number
int sumOdd () :returns the sum of the odd digits of the number
void check()  : displays true  if the product of even digits  is divisible by the sum of odd digits  rodOdd()/sumEven() == 0 
Define the class OddEven giving the details of functions. Define the main function to create an object and call the function accordingly to enable the tasks

import java.util.Scanner; 
public class OddEven
{
    int n;
    public OddEven()
    {
        n= 2157;
    }
    public OddEven(int nn)
    {
        n= nn;
    }
    public void accept()
    {
            Scanner sc = new Scanner(System.in);
            System.out.println("\nEnter the numbe1 ");
            n=sc.nextInt();    
    }
    int reverse(int n) 
    {    
        int rev = 0; 
        while (n != 0) { 
            rev = (rev * 10) + (n % 10); 
            n /= 10; 
        } 
        return rev; 
    } 

    int prodOdd() 
    { 
        int n1 = reverse(n); 
        int pOdd = 1,  c = 1; 
        while (n1 != 0) { 
        // If c is even number then it means 
        // digit extracted is at even place 
        if (c % 2 != 0) 
            pOdd *= n1 % 10; 
        n1 /= 10; 
        c++; 
        } 
    return pOdd;
    }
  
    int sumEven ()
    { 
        int n1 = reverse(n); 
        int sEven = 0, c = 1; 
        while (n1 != 0) { 
        // If c is even number then it means 
        // digit extracted is at even place 
        if (c % 2 == 0) 
            sEven += n % 10; 
        n1 /= 10; 
        c++; 
        } 
    return sEven;
    }
    void calculate()
    {
        if(prodOdd()/sumEven() == 0)
            System.out.println( n+"  True");
        else
            System.out.println(n+"  False");
        }
    public static void main()
    {
        OddEven OE = new OddEven();
        OddEven OE1 = new OddEven();        
        OE.calculate();
        OE1.accept();
        OE1.calculate();
    }
}
This entry was posted in Term 2. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *