Write a program to find sum of all odd numbers between 1 to n


The program first imports the java.util.Scanner package to allow user input. It then declares a class called Sum_Odd_Number and a main method, which is the entry point of the program. Within the main method, the program prompts the user to enter a limit number and stores the input in the variable l. It then initializes a variable sum to zero.

Next, the program runs a for loop from 1 to l, checking each number to see if it is odd by checking if the remainder of the number divided by 2 is equal to 1 (this is equivalent to checking if the number is not divisible by 2, which is the definition of odd numbers). If the number is odd, it adds the number to the sum variable.

Finally, the program prints out the sum of all odd numbers from 1 to l. Overall, this program is a simple example of how to use a for loop and conditional statement to calculate the sum of odd numbers.

Source Code

import java.util.Scanner;
class Sum_Odd_Number
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		System.out.print("Enter The Number of Limit : ");
		int l =input.nextInt();
		int sum = 0;
		for(int s=1;s<=l;s++)
		{
			if(s%2==1)
				sum = sum + s;
 
		}
		System.out.println("Sum of Odd Numbers :"+sum);
	}
}

Output

Enter The Number of Limit : 20
Sum of Odd Numbers :100

Example Programs