-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathHW4_fifth_task.java
More file actions
31 lines (27 loc) · 1.05 KB
/
Copy pathHW4_fifth_task.java
File metadata and controls
31 lines (27 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//5) Найти сумму первых n элементов массива
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class HW4_fifth_task {
public static void main(String[] args) throws IOException {
int [] array = new int[10];
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter n:");
int n = Integer.parseInt(bufferedReader.readLine());
if(n < array.length) {
System.out.println("Enter array of numbers:");
for(int i = 0; i < array.length; i++)
array[i] = Integer.parseInt(bufferedReader.readLine());
System.out.println(addNElementsOfArray(n, array));
}
else
System.out.println("Can't be done, because array is shorter than n");
}
private static int addNElementsOfArray(int n, int[] array) {
int sum = 0;
for(int i = 0; i < n; i++) {
sum += array[i];
}
return sum;
}
}