In: Computer Science
JAVA:
Display all even numbers between 1 and 20
--Optional write a program that reads in 20 numbers. A method with an int parameter should display whether the number is odd or even for the number passed
For this problem, we create a for loop that starts from 1 and goes till 20. Inside the loop, we check if the current number is divisible by 2, if yes then display it.
After that there is another similar for loop that calls the eveOdd() function with the current number. The function again checks for the divisibility by 2 and displays even/odd for that number.
CODE:
public class Main{
public static void main(String []args){
System.out.println("Even numbers between 1 and 20 are: ");
for(int i=1; i<=20; i++)
{
if(i%2==0) //checking if divisible by 2
System.out.print(i+" ");
}
System.out.println("\nEven-odd function called: ");
for(int i=1; i<=20; i++)
evenOdd(i); //calling the function for each number
}
public static void evenOdd(int num)
{
if(num%2==0) //checking if divisible by 2
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
}
OUTPUT: