Write a java program to find sum of all even and sum of all odd numbers in an array.
Write a java program to find sum of all even and sum of all odd numbers in an array.
program :
import java.util.*;
public class sum_of_odd_even
{
public static void main (String args[])
{
int i,n;
int so=0,se=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the size of an array: ");
n=sc.nextInt();
int a[]=new int[n];
System.out.println("Enter the elements of an array: ");
for(i=0; i<n; i++)
{
a[i]=sc.nextInt();
}
for(i=0; i<n; i++)
{
if(a[i]%2==0)
se+=a[i]; //sum of even
else
so+=a[i]; //sum of odd
}
System.out.println("sum of all even numbers="+se);
System.out.println("sum of all odd numbers="+so);
}
}
Output:
Enter the size of an array:
8
Enter the elements of an array:
1
2
3
4
5
6
7
8
sum of all even numbers=20
sum of all odd numbers=16
Or
Enter the size of an array:
5
Enter the elements of an array:
6
10
5
14
25
sum of all even numbers=30
sum of all odd numbers=30
Comments
Post a Comment