Array-promo

Question

Program to determine whether a given number is a Harshad number.

				
					Program to determine whether a given number is a Harshad number.
(A number is said to be the Harshad number if it is divisible by the sum of its digit.)
				
			

Share code with your friends

Share on whatsapp
Share on facebook
Share on twitter
Share on telegram

Code

				
					import java.util.Scanner;
public class HarshadNumberInArray
{  
   
    public static void main(String[] args)
    {  
        /* Initialize array */  
        int [] arr;
       
        int n=0,i=0,sum=0,rem=0,temp=0;
        Scanner sc = new Scanner(System.in);    
        
        System.out.println("Enter a number of elements in the array");   
        n = sc.nextInt(); 
        arr=new int[n];
        System.out.println("Enter numbers in array");
        
        for(i=0;i< n;i++)
        {
           arr[i]=sc.nextInt();
        }
        
       /* printing Harshad elements in an array */
        System.out.println("Harshad Elements in an array");
        for(i=0;i< n;i++)
        {
            /*Make a copy of arr[i] and store it in variable temp*/  
            temp = arr[i];  
            sum=0;
            /*Calculates sum of digits*/  
            while(temp> 0)
            {  
                rem = temp%10;  
                sum = sum + rem;  
                temp = temp/10;  
            }  
          
            //Checks whether number is divisible by sum of digits  
            if((arr[i]%sum) == 0)  
            {    
                System.out.println(arr[i]+ "    ");  
            }  
        }     
    }  
}
				
			

Coding Store

10-minute Stress-Buster Games

Leave a Reply

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