How to perform a sum of an int[] array [duplicate] - java

This question already has answers here:
How do you find the sum of all the numbers in an array in Java?
(28 answers)
Closed 5 years ago.
Given an array A of 10 ints, initialize a local variable called sum and use a loop to find the sum of all numbers in the array A.
This was my answer that I submitted:
sum = 0;
while( A, < 10) {
sum = sum += A;
}
I didn't get any points on this question. What did I do wrong?

Once java-8 is out (March 2014) you'll be able to use streams:
int sum = IntStream.of(a).sum();
or even
int sum = IntStream.of(a).parallel().sum();

Your syntax and logic are incorrect in a number of ways. You need to create an index variable and use it to access the array's elements, like so:
int i = 0; // Create a separate integer to serve as your array indexer.
while(i < 10) { // The indexer needs to be less than 10, not A itself.
sum += A[i]; // either sum = sum + ... or sum += ..., but not both
i++; // You need to increment the index at the end of the loop.
}
The above example uses a while loop, since that's the approach you took. A more appropriate construct would be a for loop, as in Bogdan's answer.

int sum=0;
for(int i:A)
sum+=i;

int sum = 0;
for(int i = 0; i < A.length; i++){
sum += A[i];
}

When you declare a variable, you need to declare its type - in this case: int. Also you've put a random comma in the while loop. It probably worth looking up the syntax for Java and consider using a IDE that picks up on these kind of mistakes. You probably want something like this:
int [] numbers = { 1, 2, 3, 4, 5 ,6, 7, 8, 9 , 10 };
int sum = 0;
for(int i = 0; i < numbers.length; i++){
sum += numbers[i];
}
System.out.println("The sum is: " + sum);

Here is an efficient way to solve this question using For loops in Java
public static void main(String[] args) {
int [] numbers = { 1, 2, 3, 4 };
int size = numbers.length;
int sum = 0;
for (int i = 0; i < size; i++) {
sum += numbers[i];
}
System.out.println(sum);
}

Related

Solving a matrix equation in Java

I have been trying to implement the given formula in JAVA but i was unsuccessful. Can someone help me find what I am doing wrong?
Do i need to shift the summation index and if so how?
My code:
public final class LinearSystem {
private LinearSystem() {
}
public static int[] solve(int [][]A , int []y) {
int n = A.length;
int[] x = new int[n];
for (int i = 0 ; i < n; i++) {
x[i] = 0;
int sum = 0;
for(int k = i + 1 ; k == n; k++) {
sum += A[i][k]*x[k]; // **java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3**
}
x[i] = 1/A[i][i] * (y[i] - sum);
}
return x;
}
public static void main(String[] args) {
int[][]A = new int[][]{{2,-1,-3},{0,4,-1},{0,0,3}};
int [] y = new int[] {4,-1,23};
System.out.println(Arrays.toString(solve(A,y))); **// awaited result [2, -3, 1]**
}
}
Just trying to collect all my comments under the question into one coherent answer, since there are quite a few different mistakes in your program.
This method of solving linear equations relies on your calculating the components of the answer in reverse order - that is, from bottom to top. That's because each x[i] value depends on the values below it in the vector, but not on the values above it. So your outer loop, where you iterate over the x values needs to start at the biggest index, and work down to the smallest. In other words, instead of being for (int i = 0; i < n; i++), it needs to be for (int i = n - 1; i >= 0; i++).
The inner loop has the wrong stopping condition. With a for loop, the part between the two semicolons is the condition to continue iterating, not the condition to stop. So instead of for(int k = i + 1; k == n; k++), you need for(int k = i + 1; k < n; k++).
You're doing an integer division at the beginning of 1 / A[i][i] * (y[i] - sum);, which means the value is rounded to an integer before carrying on. When you divide 1 by another integer, you always get -1, 0 or 1 because of the rounding, and that makes your answer incorrect. The fix from point 4 below will deal with this.
The formula relies on the mathematical accuracy that comes with working with either floating point types or decimal types. Integers aren't going to be accurate. So you need to change the declarations of some of your variables, as follows.
public static double[] solve(double[][] A, double[] y)
double x[] = new double[n];
double sum = 0.0;
along with the corresponding changes in the main method.
First, you need the second loop to go until k < n, otherwise this throws the ArrayOutOfBounds Exceptions.
Second, you need to calculate your x in reverse order as #Dawood ibn Kareem said.
Also, you probably want x[] to be a double-array to not only get 0-values as result.
I am sorry I don't know much about math side so I couldn't fix it to the right solution but I noticed a few things wrong about your code.
1-You shouldn't initialize your arrays as integer arrays, because you will be doing integer division all over the place. For example 1/A[i][i] will result in 0 even if A[i][i] = 2
2-You shouldn't write k == n, if you do it like this then your for loop will only execute if k equals n, which is impossible for your case.
I think you want to do k < n, which loops from i+1 to the point where k = n - 1
Here is my code:
import java.util.Arrays;
public final class LinearSystem {
private LinearSystem() {
}
public static double[] solve(double [][]A , double []y) {
int n = A.length;
double[] x = new double[n];
for (int i = 0 ; i < n; i++) {
x[i] = 0;
int sum = 0;
for(int k = i + 1 ; k < n; k++) {
sum += A[i][k] * x[k]; // **java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3**
}
x[i] = 1/A[i][i] * (y[i] - sum);
}
return x;
}
public static void main(String[] args) {
double[][]A = new double[][]{{2,-1,-3},{0,4,-1},{0,0,3}};
double [] y = new double[] {4,-1,23};
System.out.println(Arrays.toString(solve(A,y))); // awaited result [2, -3, 1]**
}
}
Remember that arrays are indexed from 0, so the last element is at index n - 1, not n.

Java/ Sum of any two values in an array of numbers

I have a task:
Write code that will have an array of valuesTable and givenNumber from integer. The method will list the number of such combinations that the sum of any two
elements in the array equal to the number stored in givenNumber.
Should I make another array to storage sum of any two elements?
What kind of method use to get the sum of any two elements in the array?
How list the number of combinations?
I would be very grateful for your help, this is my first steps in Java :)
public class NumberOfCombinations {
public static void main(String[] args) {
int[] valuesTable = {1, 2, 3, 4, 5};
int givenNumber = 3;
int index=0;
int sum = 0;
int n = valuesTable.length;
for (index = 0; index < n; index++)
sum = valuesTable[index] + valuesTable[++index];
}
}
Should I make another array to storage sum of any two elements?
If it is required to provide only the number of the pairs equal to the given number, array is not required, simple if statement allows to check the condition and increment the counter (and print the pair if needed):
if (a[i] + a[j] == x) {
pairs++;
System.out.println("Found a pair: " + a[i] + " + " + a[j]);
}
What kind of method use to get the sum of any two elements in the array?
Two nested loops:
for (int i = 0; i < a.length - 1; i++) {
for (int j = i + 1; j < a.length; j++) {
//...
}
}
How list the number of combinations?
The total number of possible pairs is calculated by the formula of decreasing progression from n - 1 to 1: S = n * (n - 1) / 2, so for n = 5 it is 5 * 4 / 2 = 10.
The number of matching pairs is simply counted in the innermost loop.

return the sum of int[ [duplicate]

This question already has answers here:
How do you find the sum of all the numbers in an array in Java?
(28 answers)
Closed 1 year ago.
This is my code using loops. Assume that num is not null or empty;
public int[] num;
public double[] sumNum() {
double[] sum;
for (int i = 0; i < num.length; i++) {
sum = sum + num[i];
}
return sum;
}
If you want to devise a function to sum the values of an array, consider the below:
public int sumNum(int[] num) {
int sum = 0;
for (int i = 0; i < num.length; i++) {
sum = sum + num[i];
}
return sum;
}
It doesn't make sense to return a double for a function like this, but you still can. I changed it to int since num is always int as per its declaration. I'm only making an assumption to what you really wanted.
Also consider taking num as argument for the function, thereby giving it local scope within the function. You could keep it global but again, I'm making an assumption of what you really want. Plus, it allows for re-using this function if you ever wanted to find the sum of something else.
You also want some initial value for sum: since you're summing the values in an array, I initialized sum to 0. Otherwise, when you do sum = sum + num[i], what exactly is sum initially? You need some starting point.

How can I locate and print the index of a max value in an array?

For my project, I need to make a program that takes 10 numbers as input and displays the mode of these numbers. The program should use two arrays and a method that takes array of numbers as parameter and returns max value in array.
Basically, what I've done so far is used a second array to keep track of how many times a number appears. Looking at the initial array, you will see that the mode is 4. (Number that appears most). In the second array, the index 4 will have a value of 2, and thus 2 will be the maximum value in the second array. I need to locate this max value in my second array, and print the index. My output should be '4'.
My program is good up until I attempt to produce the '4', and I've tried a few different things but can't seem to get it to work properly.
Thank you for your time!
public class arrayProject {
public static void main(String[] args) {
int[] arraytwo = {0, 1, 2, 3, 4, 4, 6, 7, 8, 9};
projecttwo(arraytwo);
}
public static void projecttwo(int[]array){
/*Program that takes 10 numbers as input and displays the mode of these numbers. Program should use parallel
arrays and a method that takes array of numbers as parameter and returns max value in array*/
int modetracker[] = new int[10];
int max = 0; int number = 0;
for (int i = 0; i < array.length; i++){
modetracker[array[i]] += 1; //Add one to each index of modetracker where the element of array[i] appears.
}
int index = 0;
for (int i = 1; i < modetracker.length; i++){
int newnumber = modetracker[i];
if ((newnumber > modetracker[i-1]) == true){
index = i;
}
} System.out.println(+index);
}
}
Your mistake is in comparing if ((newnumber > modetracker[i-1]). You should check if the newnumber is bigger then the already found max. That is if ((newnumber > modetracker[maxIndex])
You should change your last rows to:
int maxIndex = 0;
for (int i = 1; i < modetracker.length; i++) {
int newnumber = modetracker[i];
if ((newnumber > modetracker[maxIndex])) {
maxIndex = i;
}
}
System.out.println(maxIndex);
You could change last part to:
int maxIndex = 0;
for (int i = 0; i < modetracker.length; i++) {
if (modetracker[i] > max) {
max = modetracker[i];
maxIndex = i;
}
}
System.out.println(maxIndex);

Find Duplicates In Arrays

I am writing a method that would take the values and the array and find duplicates. If there are duplicates, like for instance two values have the same value, I will multiple that value by 2. If two values have the same value, I will multiple that value by 3. This will continue until if seven values are the same. I will multiple that value by 7.
This is my source code.
public static double calculateWinnings(int[]numbers)
{
double total = 0;
for (int i = 0; i < numbers.length - 1; i++)
{
for (int j = i + 1; j < numbers.length; j++)
{
if(numbers[i] == numbers[j])
{
total = numbers[i] * .01;
System.out.println("Total is " + total);
return total;
}
}
}
return total;
}
If order doesn't matter, you should sort first, then analyze.
Sorting will put identical values next to each other, where you could more easily notice them in a for loop.
The Java Collections classes may also be of use here.
See for instance http://download.oracle.com/javase/tutorial/collections/intro/index.html
For instance, if you don't want to sort first and use a loop, you could use a HashMap from the collections classes.
HashMap<Integer, Integer> counts = new HashMap<Integer, Integer>();
for(int i=0; i < numbers.length; ++i){
Integer before = counts.get(numbers[i]);
if (before == null) before=0;
counts.put(numbers[i], before+1);
}
now you have a mapper from numbers to counts
later you can use something like max(counts.valueSet()) to find the maximum count
and then loop back through your hash to see which number caused that.
If you have same values at index 1, 4, 6, you will find them with
i j conclusion
--------------
1 4 2 values
1 6 3 values
4 6 4 values // oops! already counted
and so on. Well you would - but there is no so on, since you return on the first hit:
if(numbers[i] == numbers[j])
{
total = numbers[i] * .01;
System.out.println("Total is " + total);
return total; // oops!
}
Do you mean break?
You should provide some example inputs and outputs. It's not clear exactly what output you expect. Are you just looking to find the most duplicates and then multiply that number by the frequency it appears? For example:
1 2 5 5 5 7 8 8 = three 5's = 15
Or perhaps the two 8's wins because their total is 16? Or are you going to sum all of the duplicates? In any case I'd start with this, where MAX_NUM is the highest number you expect in the array:
int[] counts = new int[MAX_NUM];
for (int i = 0; i < numbers.length; i++) {
counts[numbers[i]]++;
}
Now you have the counts of each number. If you're looking for the number with the highest count:
int num = 0;
int best = 0;
for (int i = 0; i < counts.length; i++) {
if (counts[i] > best) {
num = i;
best = counts[i];
}
}
Now num * best would be 15 for my example. Now num will contain the number that occurs the most and best will be the count for it. If there are two numbers with the same count then the higher number will win. Perhaps though in my example above you want 16 instead of 15 because the two 8's have a greater sum:
int max = 0;
for (int i = 0; i < counts.length; i++) {
max = Math.max(i * counts[i], max);
}
Now max would have 16.

Categories

Resources