Computer Science, asked by Anantmaybe, 19 days ago

WAP to input a number and print only even factors in java using while​

Answers

Answered by anindyaadhikari13
6

SOLUTION:

The given problem is solved using language - Java.

import java.util.Scanner;

public class Main{

   public static void main(String args[]){

       Scanner sc=new Scanner(System.in);

       int i=2,n;

       System.out.print("Enter a number: ");

       n=sc.nextInt();

       sc.close();

       if(n%2!=0)

           System.out.println("The number you entered is odd. So it has no factors.");

       else{

           System.out.println("The even factors of the number are as follows..");

           while(i<=n){

               if(n%i==0)

                   System.out.print(i+" ");

               i+=2;

           }

       }

   }

}

EXPLANATION:

  • Line 1: Imports Scanner class so as to take input.
  • Line 2: Class declaration.
  • Line 3: Main method declaration.
  • Line 4: Object of scanner class is created for taking input.
  • Line 5: Variables declared.
  • Line 6-7: Number is taken as input.
  • Line 8: Scanner class is closed.
  • Line 9-10: Check if the number is odd or not. If the number is odd, it will have no even factor.
  • Line 11-18: If the number is even then the else block runs. A loop is created that iterates till the value of 'i' is less than the entered number. After every iteration, we check if the number is a factor or not. If true, the number is displayed on the screen. After that, the number is incremented by 2 since we don't need to calculate odd factors.
  • Line 19: End of main method.
  • Line 20: End of class.

See attachment for output.

Attachments:
Answered by kamalrajatjoshi94
0

Answer:

Program:-

import java.util.*;

public class Program

{

public static void main(String args[])

{

Scanner in=new Scanner(System.in);

int n,i=1;

System.out.println("Enter the number");

n=in.nextInt();

System.out.println("Factors of "+n +" are:");

while(i<=n)

{

if(n%i==0)

{

if(i%2==0)

System.out.print(i+" ");

}

i++;

}

}

}

Attachments:
Similar questions