Ejemplo 1: programa Java para calcular la suma de números pares e impares en una matriz
// Java program to calculate sum of even and odd numbers in an array
import java.util.Scanner;
public class FindSumOf
{
public static void main(String[] args)
{
int number, sumEven = 0, sumOdd = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter number of elements in an array: ");
number = sc.nextInt();
int[] arrNumbers = new int[number];
System.out.println("Please enter elements of the array: ");
for(int a = 0; a < number; a++)
{
arrNumbers[a] = sc.nextInt();
}
for(int a = 0; a < number; a++)
{
if(arrNumbers[a] % 2 == 0)
{
sumEven = sumEven + arrNumbers[a];
}
else
{
sumOdd = sumOdd + arrNumbers[a];
}
}
System.out.println("Sum of even numbers in an array: " + sumEven);
System.out.println("Sum of odd numbers in an array : " + sumOdd);
sc.close();
}
}
Ejemplo 2: programa Java para encontrar la suma de todos los números pares del 1 al 10
int sum = 0;
for (int i = 1; i <= 10; i++) {
// Logic for sum of EVEN
if (i % 2 == 0) {
sum = sum + i;
}
}
System.out.println("Sum of all even from 1 to 10 is: " + sum);
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)