Repository navigation
Expand file tree
/
Copy pathArraySum.java
More file actions
51 lines (41 loc) · 1.45 KB
/
Copy pathArraySum.java
File metadata and controls
51 lines (41 loc) · 1.45 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
public class ArraySum {
public static void main(String[] args) {
// original logic: sum elements in an int array
int[] arr = {2, 3, 5, 3, 5};
int sum = 0;
for (int counter : arr) {
sum += counter;
}
System.out.println("Sum: " + sum);
System.out.println();
// simple string array example
String[] fruits = {"Apple", "Banana", "Cherry", "Mango"};
System.out.print("Fruits: ");
for (String fruit : fruits) {
System.out.print(fruit + " | ");
}
System.out.println("\n");
// calculate total and average price
double[] prices = {19.99, 15.50, 5.00, 10.25};
double totalCost = 0;
for (double price : prices) {
totalCost += price;
}
double averagePrice = totalCost / prices.length;
System.out.println("Total: $" + totalCost);
System.out.println("Avg: $" + averagePrice);
System.out.println();
// print a 3x3 grid
int[][] grid = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[row].length; col++) {
System.out.print(grid[row][col] + " ");
}
System.out.println(); // drop to next line after row finishes
}
}
}