java

Write a Program to Print Odd Numbers From 1 to N

In this tutorial, we are going to see how to print odd numbers from 1 to N in Java.

In the following example, we print the odd numbers from 1 to N, the value of N we set here is 100, so the program will print the odd numbers between 1 and 100.

If an integer is not divisible by 2 (value%2 != 0), then it is an odd number. This same logic that we use here to find the odd numbers. We start from 1 to N and check each value if it is not divisible by 2, if it is, we will print it.
 

 

Program to Print Odd Numbers From 1 to N
public class Main {
	public static void main(String args[]) {
		int n = 100;
		System.out.println("The odd numbers from 1 to "+n+" are: ");
		for (int i = 1; i <= n; i++) {
			if (i % 2 != 0) {
				System.out.println(i);
			}
		}
	}
}

 
Output:

The odd numbers from 1 to 100 are: 
1
3
5
7
9
11
13
15
17
19
21
23
25
27
29
31
33
35
37
39
41
43
45
47
49
51
53
55
57
59
61
63
65
67
69
71
73
75
77
79
81
83
85
87
89
91
93
95
97
99
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *