Odd number

The Opposite of even numbers. Odd numbers have a difference of 3 unit or number. In other words, if the number is not completely divisible by 2 then it is an odd number.

Logic

This program is much similar to this one: Java program to print all odd numbers from 1 to N. The only difference here is that instead of printing them we have to add all the odd numbers inside the loop. We will add all the odd numbers in one temporary variable “sum” and after the completion of the loop, we have to print that temporary variable.

See also: Check whether number is even or odd

Program

import java.util.Scanner;

public class OddSum {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        // Take input from user.
        System.out.print("Print sum of odd numbers till : ");
        int n = scanner.nextInt();

        int sum = 0;

        for(int i = 1; i <= n; i++) {

            // Check for odd or not.
            if((i % 2) != 0) {

                sum += i;

            }
        }

        System.out.println("\nSum of odd numbers from 1 to " + n + " is : " + sum);
    }

}

Output

Print sum of odd numbers till : 50
Sum of odd numbers from 1 to 50 is : 625