Write a program to array elements to print sum of Odd Numbers


This Java program allows the user to enter an array of integers and calculates the sum of all the odd numbers in the array. Here is how the program works:

  • The program first creates a Scanner object to read user input.
  • The user is prompted to enter the limit of the array.
  • The program creates an integer array of size l, where l is the limit entered by the user.
  • The program then uses a for loop to iterate through the array and prompt the user to enter each element of the array.
  • After the array is filled with user input, another for-each loop is used to iterate through the array.
  • For each element of the array, if the element is odd (i.e., if the remainder when the element is divided by 2 is 1), its value is added to a variable called sum.
  • Finally, the program prints out the value of sum, which is the sum of all the odd numbers in the array.

Source Code

import java.util.Scanner;
class Array_Sum_OddNum
{
	public static void main(String[] args)
	{   
		Scanner input =new Scanner(System.in);
		System.out.print("Enter the Array Limit :");
		int l =input.nextInt();
		int [] a =new int[l];
		int sum = 0;
		for(int i=0;i<l;i++)
		{
			System.out.printf("Element of a[%d] :",i);
			a[i]=input.nextInt();
		}
		for(int o:a)
		{
			if(o%2==1)
				sum = sum + o;
		}		
		System.out.println("Sum of Odd Array Elements : "+sum);
    }
}
 

Output

Enter the Array Limit :5
Element of a[0] :12
Element of a[1] :34
Element of a[2] :59
Element of a[3] :45
Element of a[4] :22
Sum of Odd Array Elements : 104

Example Programs