Answer:
The java program to print all even numbers from 1 to 100 is given below.
import java.util.*;
public class Program
{
// integer array of size 100
static int[] num = new int[100];
public static void main(String[] args) {
// array initialized using for loop with values from 1 to 100
for(int j=0; j<100; j++)
{
num[j] = j+1;
}
System.out.println("Even numbers from 1 to 100 are ");
// enhanced for loop
for(int n : num)
{
// testing each element of the array
// only even numbers will be displayed
if( (n%2) == 0)
System.out.print(n + " ");
}
}
}
OUTPUT
Even numbers from 1 to 100 are
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
Step-by-step explanation:
The program works as described.
1. An integer array, num, of size 100 is declared.
2. Inside for loop which executes 100 times, array is initialized with numbers from 1 to 100.
3. An enchanced for loop differs from normal for loop such that it doesn't has initialization and increment or decrement conditions.
4. The syntax for an enchanced for loop is shown below.
for( datatype variable_name : array_name )
{ }
In the above syntax, the datatype of the variable_name should be the same as that of the array_name.
The array used in program is shown below.
for(int n : num)
5. Inside enhanced for loop, if statement is included to test each element of array, num, for even or odd number.
if( (n%2) == 0)
6. If the number is even, it is displayed followed by a space.
System.out.print(n + " ");
7. The method println() differs from print() such that new line is inserted after the message is displayed.
8. This program can also be used to display odd numbers by changing the condition inside if statement.