write a program in java using for loop to print all the odd and even number upto 30 terms
Answers
Answer:
the following example we are displaying the even numbers from 1 to n, the value of n we have set here is 100 so basically this program will print the even numbers between 1 to 100.
If an integer number(never a fraction number) is exactly divisible by 2 which means it yields no remainder when divided by 2 then it is an even number. This same logic we are using here to find the even numbers. We are looping through 1 to n and checking each value whether it is evenly divisible by 2 or not, if it is then we are displaying it. To understand this program you should have the basic knowledge of for loop in Java and if statement.
class JavaExample {
public static void main(String args[]) {
int n = 100;
System.out.print("Even Numbers from 1 to "+n+" are: ");
for (int i = 1; i <= n; i++) {
//if number%2 == 0 it means its an even number
if (i % 2 == 0) {
System.out.print(i + " ");
}
}
}
}
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
Related Java Examples
1. Java Program to print odd numbers from 1 to 100
2. Java program to check even or odd number
3. Java program to check if a given number is perfect square
4. Java Program to find GCD of two numbers
Explanation:
public class KboatEvenOdd
{
public static void main(String args[]) {
System.out.println("Odd numbers: ");
for (int i = 1; i <= 60; i += 2) {
System.out.print(i + " ");
}
System.out.println();
System.out.println("Even numbers: ");
for (int i = 2; i <= 60; i += 2) {
System.out.print(i + " ");
}
}
}