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

Enhancing programming skills is very important no matter what language you have chosen. So, practice frequently with these simple java programs examples and excel in coding the complex logic.

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 odd numbers in a sum variable.

Java program to calculate sum of odd numbers

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