Reputation: 1498
public void calculatePercentage(int exam[][])
{
int perc = 0;
for (int i = 0; i < examen.length; i++)
{
for (int[] score : exam)
perc += score;
perc /= exam.length;
}
}
Hello, I am really stuck at this one. I want to create a new mathod calculatePercentages given the parameter exam[][]. The double array exam holds 3 rows of elements. What the method has to do is simple calculate the sum of each row. The answer is probably quite simple, but I just don't know how to do it. For a single array, I guess the code is:
double perc = 0;
for(int score : exam)
{
perc += score;
}
perc /= (exam.length);
return perc;
The exam[][] could look like:
|10 12 18 5 3 | |12 3 5 15 20 | |20 15 13 11 9 |
The output percentage[] should like:
{48,55,68} Each element of percentage[] is the sum of the elements of 1 row of exam[]
Upvotes: 0
Views: 103
Reputation: 37843
The double array exam holds 3 rows of elements. What the method has to do is simple calculate the sum of each row.
The name makes no sense, but it does what you want it to do.
public int[] calculatePercentage(int exam[][]) {
int[] sums = new int[exam.length];
for (int i = 0; i < exam.length; i++) {
int sum = 0;
for (int j = 0; j < exam[i].length; j++) {
sum += exam[i][j];
}
sums[i] = sum;
}
return sums;
}
Also a double array would be double[]
, you are talking about two dimensional int arrays int[][]
EDIT
Pshemo pointed out a shorter solution is possible:
public int[] calculatePercentage(int exam[][]) {
int[] sums = new int[exam.length];
for (int i = 0; i < exam.length; i++) {
for (int j = 0; j < exam[i].length; j++) {
sums[i] += exam[i][j];
}
}
return sums;
}
or even just
public int[] calculatePercentage(int exam[][]) {
int[] sums = new int[exam.length];
for (int i = 0; i < exam.length; i++)
for (int j = 0; j < exam[i].length; j++)
sums[i] += exam[i][j];
return sums;
}
but I still prefer the first one, for it's readability.
Upvotes: 3
Reputation: 4114
for (int i = 0; i < exam.length; i++) {
int sum = 0;
for (int j = 0; j < exam[i].length; j++) {
sum += exam[i][j];
}
}
using for each
for (int x[] : exam) {
for (int y : x) {
sum += y;
}
}
Upvotes: 0