Dremendo Tag Line

Input number and check perfect number or not using while loop in Java

while Loop - Question 8

In this question, we will see how to input a number and check if it is a perfect number or not in Java programming using while loop. To know more about while loop click on the while loop lesson.

Q8) Write a program in Java to input a number and check if it is a perfect number or not using while loop.

A Perfect number is a number, whose sum of the factors excluding the given number itself is equal to the given number.

Example: Sum of factors of 6 excluding 6 is 1+2+3 which is equal to 6, so 6 is a perfect number.

Program

import java.util.Scanner;

public class Q8
{
    public static void main(String args[])
    {
        int i=1,n,sf=0;
        Scanner sc=new Scanner(System.in);

        System.out.print("Enter a number ");
        n=sc.nextInt();

        while(i<n)
        {
            if(n%i==0)
            {
                sf=sf+i; 		// sum of factors
            }
            i=i+1;
        }

        if(sf==n)
        {
            System.out.println("Perfect Number");
        }
        else
        {
            System.out.println("Not Perfect Number");
        }
    }
}

Output

Enter a number 28
Perfect Number
video-poster