Java Program to print Even numbers till N

Description

Get input n and print n even numbers.
Input:
7
Output:
2 4 6 8 10 12 14

Solution

import java.util.*;
class NEven
 {
    public static void main(String args[])
    {
          int i,j,lim;
          System.out.println("Enter The Value Of N");
          Scanner sc=new Scanner(System.in);
          lim=sc.nextInt();
          System.out.println("The N Even Numbers: ");
          for(j=1,i=2;j<=lim;i=i+2,j++)
              {
                   System.out.println(""+i);
              }
    }
}

We are Teaching "Web Development using Python" through Online.

View Tutor Profile and Course Syllabus

Explanation

Instruction(s) inside the for block{} are executed repeatedly till  the second expression (j<=lim) is true.

Here i and j are initialized to 2 and i is incremented by 1 and j is incremented by 1. for each iteration, instructions inside the for block are executed unless j becomes greater than n. so value of i (2,4,6,8,.....) (n odd numbers) in each iteration will be printed using system.out.println. 
Ramesh P Natarajan

Author - Ramesh P Natarajan

Software Developer and Technology Trainer, very much passionate in the field of Software Application Development, Machine Learning and Search Engine Optimization.

Write to: [email protected]





Interesting Pattern Programs: for more Patterns

Input:
5
Output:
*
**
***
****
*****
****
***
**
*Solution
Input:
5
Output:
    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *Solution
Input:
5
Output:
*        *
**      **
***    ***
****  ****
**********Solution
Input:
5
Output:
*       *
**     **
***   ***
**** ****
*********Solution
Input:
5
Output:
*       *
**     **
***   ***
**** ****
*********
**** ****
***   ***
**     **
*       *Solution
Input:
5
Output:
*********
 *******
  *****
   ***
    *
   ***
  *****
 *******
*********Solution