In this problem we have to print first 100 even numbers along with the serial numbers. There will be 50 even numbers from 1-100.
Approach :
Take your first step by opening IntelliJ to write the code. We will use for loop with if statement to tackle this problem. We will initialize a variable to keep the count of serial number.
Java JavaScript
Code :
package com.StepTowardsCoding;
public class even {
public static void main(String[] args) {
int count = 1;
for (int i = 1; i <= 100; i++) {
if (i % 2 == 0) {
System.out.println(count+". " + i);
count+=1;
}
}
}
}
Output :
1. 22. 4
3. 6
4. 8
5. 10
6. 12
7. 14
8. 16
9. 18
10. 20
11. 22
12. 24
13. 26
14. 28
15. 30
16. 32
17. 34
18. 36
19. 38
20. 40
21. 42
22. 44
23. 46
24. 48
25. 50
26. 52
27. 54
28. 56
29. 58
30. 60
31. 62
32. 64
33. 66
34. 68
35. 70
36. 72
37. 74
38. 76
39. 78
40. 80
41. 82
42. 84
43. 86
44. 88
45. 90
46. 92
47. 94
48. 96
49. 98
50. 100
Explanation :
I had initialized a variable count of type integer which will keep the count of Serial Number. After that I had created a for loop from 1 to 100 with +1 increment, 'i' is the variable used in the for loop. The value of 'i' is even or not is checked in the if statement by using the condition i%2 == 0. Modulus(%) is used to return a remainder. When 'i' is divided by 2 and the remainder is 0, which means 'i' is divisible by 2 and is even. The 'i' is printed along with count and count get increased by 1.
When the condition is false, it do nothing and starts the next execution.
0 Comments
Ask Your Queries in the comments