top of page
• Rahul Kumar

# Sum of Even Numbers till N

Given a number N, print sum of all even numbers from 1 to N.

Integer N
Required Sum
6
12
##### Solution :

```/*

Pre-requisite to solve this problem:
In this question, we have to find sum of all even numbers till n. To take sum of all the even numbers, we have to take a variable and initialize it to zero. Let us name this variable as sum.
Following code is used to add 2 to sum variable and update it to the same sum variable:
sum = sum + 2

Hint to solve this problem: We will have to loop on even numbers only and add the even numbers to the same sum variable, described above.
*/

import java.util.Scanner;
public class Solution {

public static void main(String[] args) {

/* Your class should be named Solution.
* Read input as specified in the question.
* Print output as specified in the question.
*/
Scanner input = new Scanner(System.in);

int n = input.nextInt();
int i = 2;
int sum = 0;

while (i <= n){
sum = sum+i;
i = i + 2;
}
System.out.println(sum);

}

}```

584 views

## Recent Posts

See All

Print the following pattern Pattern for N = 4 1 23 345 4567 Input Format : N (Total no. of rows) Output Format : Pattern in N lines Sample Input 1 : 3 Sample Output 1 : 1 23 345 Solution: import java.

bottom of page