/* List Even Numbers Java Example This List Even Numbers Java Example shows how to find and list even numbers between 1 and any given number.*/publicclassListEvenNumbers {publicstaticvoidmain(String[] args) {//define limitint limit =50;System.out.println("Printing Even numbers between 1 and "+ limit);for(int i=1; i <= limit; i++){// if the number is divisible by 2 then it is evenif( i %2==0){System.out.print(i +" "); } } }}/*Output of List Even Numbers Java Example would bePrinting Even numbers between 1 and 502 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 */
2) Program to find the sum of natural numbers from 1 to 1000.
// Program to find the sum of natural numbers from 1 to 1000.classNumber {publicstaticvoidmain(String[] args) {int sum =0;for (int i =1; i <=1000; ++i) { sum += i; // sum = sum + i }System.out.println("Sum = "+ sum); }}
When you run the program, the output will be:
Sum = 500500
Here, the variable sum is initialized to 0. Then, in each iteration of for loop, variable sum is assigned sum + i and the value of i is increased until i is greater than 1000. For better visualization,
1st iteration: sum = 0+1 = 1
2nd iteration: sum = 1+2 = 3
3rd iteration: sum = 3+3 = 6
4th iteration: sum = 6+4 = 10
... .. ...
999th iteration: sum = 498501 + 999 = 499500
1000th iteration: sum = 499500 + 1000 = 500500
/* Java Pyramid 2 Example This Java Pyramid example shows how to generate pyramid or triangle like given below using for loop. ***** **** *** ** **/publicclassJavaPyramid2 {publicstaticvoidmain(String[] args) {for(int i=5; i>0 ;i--){for(int j=0; j < i; j++){System.out.print("*"); }//generate a new lineSystem.out.println(""); } }}/*Output of the example would be****************/