Ejemplo 1: suma de todos los números en la matriz java
int[] a = {10,20,30,40,50};
int sum = IntStream.of(a).sum();
System.out.println("The sum is " + sum);
Ejemplo 2: suma de números en una matriz java
public class Exercise2 {
public static void main(String[] args) {
int my_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = 0;
for (int i : my_array)
sum += i;
System.out.println("The sum is " + sum);
}
}
Ejemplo 3: agregue cada elemento en una matriz java
import java.util.Arrays;
import java.util.Scanner;
public class SumOfElementsOfAnArray {
public static void main(String args[]){
System.out.println("Enter the required size of the array :: ");
Scanner s = new Scanner(System.in);
int size = s.nextInt();
int myArray[] = new int [size];
int sum = 0;
System.out.println("Enter the elements of the array one by one ");
for(int i=0; i<size; i++){
myArray[i] = s.nextInt();
sum = sum + myArray[i];
}
System.out.println("Elements of the array are: "+Arrays.toString(myArray));
System.out.println("Sum of the elements of the array ::"+sum);
}
}
Ejemplo 4: suma de matriz de ejecución de Java
class Solution {
public int[] runningSum(int[] nums) {
int[] sol = new int[nums.length];
sol[0] = nums[0];
for(int i = 1; i < nums.length; i++) {
sol[i] = sol[i-1] + nums[i];
}
return sol;
}
}
// Example: runningSum([1,3,6,9]) = [1, 4, 10, 19] = [1, 1+3, 1+3+6, 1+3+6+9]
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)