In this blog post, we will explore three different methods to display even numbers from 1 to 100 in Java: using a for loop, a nested-if statement, and a while loop. Along we’ll discover various variation and some useful tips which will help you to learn program easily.
What is Even Number in Java?
An even number is an integer that is divisible by 2 without leaving a remainder. In other words, when an even number is divided by 2, the result is a whole number. Even numbers are characterized by the property that they end in 0, 2, 4, 6, or 8.
Examples of even numbers
2, 4, 6, 8, 10, 12, 14, 16, …
Also, learn about Largest of Three Numbers in Java, Now!
How to Find Even Numbers From1 to 100 in Java
Below are some of the methods to display even numbers from 1 to 100 in Java:
- Using Java for Loop
- Using nested-if Statement
- Using while Loop
Using Java for Loop
This Java program uses a `for` loop to iterate through numbers from 1 to 100.
// Display Even Numbers From 1 to 100 in Java public class DisplayEvenNoEx { public static void main(String args[]) { int num=100; System.out.print("List of even numbers from 1 to "+num+": "); for (int i=1; i<=num; i++) { if (i%2==0) { System.out.print(i + " "); } } } }
Explanation of the Code:
1. `public class DisplayEvenNoEx`: This line defines a class named `DisplayEvenNoEx`.
2. `public static void main(String args[])`: This is the main method, which serves as the entry point of the program. Although it accepts an array of strings as input (‘args’), it is not used in this program.
3. `int num = 100;`: This line initializes a variable `num` with the value 100. This variable represents the upper limit of the range for which even numbers will be displayed.
4. `System.out.print(“List of even numbers from 1 to ” + num + “: “);`: This line prints a message indicating that the following output will be a list of even numbers from 1 to the value of `num`.
5. `for (int i = 1; i <= num; i++)`: This is a for loop that iterates from 1 to the value of `num`.
6. `if (i % 2 == 0)`: This line checks if the current value of `i` (the loop variable) is even. The condition `i % 2 == 0` evaluates to `true` if `i` is evenly divisible by 2.
7. `System.out.print(i + ” “);`: If the condition in the `if` statement is `true`, it means `i` is an even number. The program then prints the value of `i` followed by a space, which will build up the list of even numbers.
8. The closing braces (`}`) are used to indicate the end of the `for` loop and the `main` method.
It checks whether each number is even using the modulo operation (`i % 2 == 0`), and if it’s even, it prints the number as part of a list of even numbers from 1 to 100. The program outputs a message, followed by a list of even numbers separated by spaces.
Advantages:
– Clear and concise code.
– Explicit control over loop iterations.
– Easily adaptable to other counting patterns.
Check out Javascript for Loop, Now!
Output:
List of even numbers from 1 to 100: 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100
Using nested-if Statement
Nested-if statements provide a way to implement multiple levels of decision-making within your code. Here’s how you can use a nested-if statement to identify and display even numbers:
// Display Even Numbers From 1 to 100 in Java public class DisplayEvenNoEx { public static void main(String[] args) { System.out.println("List of even numbers: "); displayEvenNum(1, 100); } // funtion to find even numbers private static void displayEvenNum(int num, int end) { if(num>end) return; if(num%2==0) { //prints the even numbers System.out.print(num +" "); //calling the method and increments the number by 2 if the number is even displayEvenNum(num + 2, end); } else { //increments the number by 1 if the number is odd displayEvenNum(num + 1, end); } } }
Explanation of the Code:
1. The code begins with the declaration of a class named `DisplayEvenNoEx`.
2. Inside the class, there’s a `main` method, which serves as the entry point for the program. It prints the introductory message “List of even numbers: ” and then calls the `displayEvenNum` function.
3. The `displayEvenNum` function is a recursive function that aims to display even numbers within a given range. It takes two parameters: `num` (current number) and `end` (ending number, which is 100 in this case).
4. The function starts by checking whether `num` has exceeded the `end`. If it has, the function returns, effectively terminating the recursive calls.
5. If `num` is not greater than `end`, it proceeds to the next condition. It checks whether the current number (`num`) is even by using the condition `num % 2 == 0`. If the condition is true, it means the number is even.
6. If the number is even, it’s printed using `System.out.print(num + ” “)`.
7. Then, the function makes a recursive call to itself, passing `num + 2` as the new value of `num`. This effectively skips the next odd number and ensures that the function only deals with even numbers.
8. If the number is odd (condition in step 5 is false), the function still makes a recursive call to itself, but this time with `num + 1`, effectively skipping to the next number.
9. The recursion continues until `num` exceeds the specified `end` value.
It employs the fact that even numbers are always followed by odd numbers and takes advantage of this pattern to efficiently list even numbers without unnecessary checks.
Advantages:
– Flexibility to perform additional checks within the loop.
– Useful when more complex conditions are required.
Output:
List of even numbers: 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100
Using while Loop
While loops execute a block of code repeatedly as long as a given condition is true. Displaying even numbers using a while loop can be done as follows:
// Display Even Numbers From 1 to 100 in Java public class DisplayEvenNoEx { public static void main(String[] args) { int num, i; num = 100; i=2; System.out.print("List of even numbers: "); //while loop while(i<=num) { //prints the even number System.out.print(i +" "); //increments the variable i by 2 i=i+2; } } }
Explanation of the code:
1. `public class DisplayEvenNoEx`: This line defines the class named `DisplayEvenNoEx`.
2. `public static void main(String[] args)`: This is the main method, the entry point of the program, where the execution begins.
3. `int num, i;`: Two integer variables, `num` and `i`, are declared to be used in the program. `num` will hold the upper limit (100) of the range of numbers to consider, and `i` will be the iterating variable.
4. `num = 100;`: Here, the value of `num` is set to 100, which is the upper limit of the range.
5. `i = 2;`: The initial value of `i` is set to 2, which is the first even number in the range.
6. `System.out.print(“List of even numbers: “);`: This line prints the initial message that will be displayed before the list of even numbers.
7. `while (i <= num)`: This is the start of a `while` loop. The loop will continue as long as `i` is less than or equal to `num` (100).
8. `System.out.print(i + ” “);`: Within the loop, this line prints the value of `i`, which represents the current even number.
9. `i = i + 2;`: After printing the current even number, the value of `i` is incremented by 2 to move to the next even number.
10. The loop continues until `i` exceeds the value of `num` (100), at which point the loop stops.
Advantages:
– Dynamic condition control during loop execution.
– Suitable for scenarios with uncertain iteration count.
Output:
List of even numbers: 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100
Understand the Concept of Smallest of Three Numbers in Java, Here!
Tips and Variations:
By learning these tips and variations, you can provide a more comprehensive and engaging exploration of the topic, catering to readers with varying levels of programming experience and interests.
Tips:
Here is a list of a few tips to write an effective Java program:
1. Using Modulo Operator Efficiently: Instead of incrementing by 2, you can use the modulo operator (%) to check if a number is even. For example, `if (i % 2 == 0)` will directly determine if `i` is even.
2. Optimizing Loop Range: Since you want to display even numbers from 1 to 100, you can optimize the loop by starting from 2 (the first even number) and increasing by 2 until you reach or just exceed 100. This avoids unnecessary iterations.
3. Reverse Order: Experiment with reversing the loop to display even numbers in descending order, starting from 100 and going down to 2.
4. User Input: Modify the program to take user input for the upper limit (`num`) to make it more dynamic.
Variations:
1. Display Odd Numbers: Modify the code to display odd numbers within the range and compare the approaches to even numbers.
2. Custom Range: Allow users to input a custom range of numbers and display even numbers within that range.
3. Using Java Streams: If you’re comfortable with advanced Java features, explore how Java Streams can be used to generate and display even numbers.
4. Do-While Loop: Implement the even number display using a do-while loop and compare its behavior with the while loop.
5. Skip First Even Number: Modify the program to display even numbers from 3 to 100, skipping the first even number (2).
6. Functional Approach: Utilize Java 8’s functional programming features to achieve the same task in a different way.
7. Multi-threading: Explore parallel processing using multi-threading to display even numbers, considering both performance and challenges.
8. Visualization: Create a graphical representation of even numbers using a simple GUI or console graphics.
9. Error Handling: Implement proper error handling to handle cases where an invalid input is provided for the upper limit.
In conclusion, understanding and effectively implementing ways to display even numbers from 1 to 100 in Java is a fundamental programming skill. Through the exploration of three methods – the for loop, nested-if statement, and while loop – you’ve gained insight into diverse approaches. With these tools in hand, you have a better capability to tackle similar tasks and make informed decisions in your coding journey.
We hope that you found our blog on ‘Display Even Numbers 1 to 100 in Java’ helps you to understand various methods to display even number in Java. You can also visit our Newtum website for more information on various courses and blogs about PHP, C Programming for kids, Java, and more. Happy coding with Newtum!