Java Program to Find Sum of all Odd Numbers between 0 to N

  • Write a program in Java to find the sum of all odd numbers between 0 to N using loop.
Algorithm to find sum of all odd numbers between 1 to N
  • Take N as input from user and store it in an integer variable.
  • Using for loop, iterate from 0 to N.
  • For every number i, check whether it is an odd number or not. if(i%2 == 1) then i is odd number else even.
  • Add all even numbers in a sum variable.

Java program to calculate sum of odd numbers

package com.tcc.java.programs;

import java.util.*;

public class OddNumberSum {
    public static void main(String args[]) {
        int N, i, sum = 0;

        Scanner in = new Scanner(System.in);
        System.out.println("Enter a number");
        N = in.nextInt();

        for(i = 0; i <= N; i++){
            if((i%2) == 1){
                sum += i;
            }
        }
    
        System.out.print("Sum of all odd numbers between 0 to " 
            + N + " = " + sum);
    }
}
Output
Enter a number
10
Sum of all odd numbers between 0 to 10 = 25

Recommended Posts
Java Program to Print Prime Numbers between 1 to 100
Java Program to Print Armstrong Numbers Between 1 to N
Java Program to Check Odd or Even Numbers
Java Program to Calculate Arithmetic Mean of N Numbers
Java Program to Find Largest of Three Numbers
Java Program to Make a Simple Calculator using Switch Statement
Java Program to Find LCM and GCD of Two Numbers
Java Program to Find All Factors of a Number
Java Program to Check a Number is Prime Number or Not
Java Program to Find Sum of Digits of a Number
Java Program to Find Factorial of a Number Using Recursion
All Java Programs