To generate the first 100 even numbers using while loop use these codes:
package assignment.q1;
public class AssignmentQ1 {
public static void main(String[] args) {
int i = 1;
while(i<=100)
{
if(i%2==0)
{
System.out.println(i);
}
i++;
}
}
}
Here's a step-by-step breakdown of the code:
1. The program is defined as a class called "AssignmentQ1" in a package called "assignment.q1".
package assignment.q1;
public class AssignmentQ1 {
2. The main method is declared with the "public static void" keywords. It takes an array of strings as an argument called "args".
public static void main(String[] args) {
3. The integer variable "i" is declared and initialized to 1.
int i = 1;
4. A while loop is used to iterate through the numbers from 1 to 100 (inclusive).
while(i<=100)
5. Within the loop, an if statement checks if the current value of "i" is divisible by 2 (i.e., if it is an even number).
if(i%2==0)
6. If "i" is even, then it is printed to the console using the "System.out.println()" method.
System.out.println(i);
7. Regardless of whether "i" is even or odd, the value of "i" is incremented by 1 at the end of each iteration of the loop.
i++;
8. Finally, the closing braces of the while loop, the if statement, and the main method are included.
}
}
Kindly leave a comment