Sum and Average of all Palindrome numbers in an Array (using Functions)

Write a program in Java to accept 10 different numbers in array and calculate the sum and average of all Palindrome numbers present in that array using function.

Instance variables/Data members:
int a [ ] : to store the 10 numbers
Rest of the variables can be assumed as required according to the logic of the program.

Instance Methods:
void accept ( ) : to accept 10 numbers in an array using an input statement.
boolean check (int x) : to check the argument is Palindrome number or not. If yes returns true otherwise returns false.
void display ( ) : to display all the Palindrome number and their position in that array. Finally display their sum and average with proper message.

Write a main ( ) to call the method using an object to perform the task.

import java.util.Scanner;
class Disha
{
    int a[] = new int[10];
    
    void accept()
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("ENTER 10 NUMBERS");
        for(int i=0; i<10; i++)
        {
            a[i]=sc.nextInt();
        }
    }
    
    boolean check(int x)
    {
        //reverse the number
        int temp=x, rev=0;
        while(temp!=0)
        {
            int dig=temp%10;
            rev=rev*10+dig;
            temp/=10;
        }
        if(x == rev)
            return true; //It is palindrome
        else
            return false; //It is not Palindrome
    }
    
    void display()
    {
        int sum=0, count=0;
        double avg;
        
        System.out.println("PALINDROME ELEMENTS \t POSITION");
        for(int i=0; i<10; i++)
        {
            //if the array element is palindrome
            if(check(a[i]))
            {
                System.out.println(a[i] + "\t\t\t" + (i+1));
                sum+=a[i]; //add element to sum
                count++;
            }
        }
        avg=sum/count;
        
        System.out.println("SUM OF ELEMENTS = " + sum);
        System.out.println("AVERAGE OF ELEMENTS = " + avg);
    }
    
    public static void main(String args[])
    {
        Disha obj = new Disha();
        obj.accept();
        obj.display();
    }
}

Leave a Comment

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