Java Programming : Sum of even numbers

Example

Input
5
Output
6

Required to know

Use of Variables, Use of different operators like assignment or arithmetic operators, Use of methods like System. out. print(), and use for loop, and Use of Data types

Steps

This program calculates the sum of all odd numbers between 1 and a user input number n. Here's how it works:

  • The program first asks the user to input a number, which is stored in the variable n.

  • The program initializes a variable called sum to 0, which will be used to keep track of the sum of odd numbers.

  • The program then uses a for loop to iterate through the numbers from 1 to n.

  • During each iteration, the program checks whether the current number is odd by using the modulo operator % and checking if the result is equal to 1. If the number is odd, it adds it to the sum variable.

  • After the loop completes, the program prints the value of sum, which represents the sum of all odd numbers between 1 and n.

Program

import java.util.Scanner; 
public class Mavenproject1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in); 
        int n = sc.nextInt(); 
        int i;
        int sum = 0; 
        for(i = 1; i<=n; i++){
            if(i%2==0){
                sum = sum + i; 
            }
        }
        System.out.print(sum + " "); 
    }
}