Java Program to print sum of odd numbers between 1 to n using while loop

Java Program to print sum of odd numbers between 1 to n using while loop

Any number when divided by 2 gives a remainder other than zero, which is an odd number. In our java program, we are using while loop to iterate the given numbers range. And using the if statement to find the odd number and sum of odd numbers.

Steps:

  1. Here we are using a “Scanner” class to take input for the value n from the user.
  2. In the below Program, we are starting iteration from 1 and checking its divisibility by 2 in the if block.
  3. If the condition is satisfied for the odd number, we are adding only that number to a variable “sum” and then increment the number by 1.
  4. For eg . 5%2 =1, conditions satisfied for the odd number. Now 5 is qualified to be added to the sum variable. (sum = sum +5).

Print sum of all odd numbers between 1 to n in Java While loop

import java.util.*;
public class Main
{
	public static void main(String args[])
	{
		Scanner sc = new Scanner(System.in);
		int start = 1;
		System.out.println("Enter the Number to find Odd number sum : ");
		int end = sc.nextInt();
		int sum = 0;
		while(start<=end) {
			if(start%2 != 0) {
			sum = sum + start;
			}
			start++;
		}
		System.out.println("Sum of all the Odd numbers are : " +sum+ ".");
		sc.close();
	}
}

Output

Enter the Number to find Odd number sum : 
15
Sum of all the Odd numbers are : 64.