What are Even Numbers? | Maths Explanation for Java Kids
Hello pupils, what are even numbers?
Answer:
Even numbers are numbers that are divisible by 2.
They include:
Considering how simple and straight-forward even numbers are, writing a Java code for even numbers
serves as a great way to introduce our Mathematics educational activities for young learners.
Well then, let's see how we can write a programming code to make our computer
list a set of even numbers in the Java language, between a given range of values.
Bear in mind, we use only a loop and a simple conditional statement for the Java code.
Create a new Java project;
call it Arithmetic.
Create a new java class file;
call it EvenNumbers.
Type out the adjoining Java code for listing even numbers.
How to run Java Codes
Run the Java code from the main function class by pressing
key f6 or the run symbol.
So! Java Fun Practice Exercise - List Even Numbers
As a fun practice exercise, feel free to try out your own boundary values, and see how the Java code lists the even numbers between those boundary values.
Java Code for Even Numbers class.
public class EvenNumbers {
private int start; // Our starting point
private final int stop; // where we will stop
private String result; // Store result here.
// Our constructor
public EvenNumbers(int first, int last) {
start = first;
stop = last;
result = "Even numbers between " + first + " and " + last + " are: \n";
}
public String prepResult() {
/*
* Loop from start to stop and rip out even numbers;
*/
while (start <= stop) {
if (start % 2 == 0) { // modulo(%) is explained below
result = result + start + "; ";
}
start = start + 1; // increase start by 1
}
return result;
}
}
Java Code for Even Numbers - Main Class.
public class Arithmetic {
public static void main(String[] args) {
System.out.println("Welcome to our demonstration sequels");
System.out.println("Hope you enjoy (and follow) the lessons.");
System.out.println("");
/* Use the Even Number class. */
String answer;
EvenNumbers even_data = new EvenNumbers(1, 100); // even numbers between 1 and 100
answer = even_data.prepResult();
System.out.println(answer);
System.out.println();
}
}