sum of columns in a 2 dimensional array - java

static double [][] initialArray = {{7.432, 8.541, 23.398, 3.981}, {721.859, 6.9211, 29.7505, 53.6483}, {87.901, 455.72, 91.567, 57.988}};
public double[] columnSum(double [][] array){
int index = 0;
double temp[] = new double[array[index].length];
for (int i = 0; i < array[i].length; i++){
double sum = 0;
for (int j = 0; j < array.length; j++){
sum += array[j][i];
}
temp[index] = sum;
System.out.println("Index is: " + index + " Sum is: "+sum);
index++;
}
return temp;
}
public static void main(String[] args) {
arrayq test = new arrayq();
test.columnSum(initialArray);
}
I want to get the sum of all the columns, but I keep getting an outofbounds exception. This is the output I get:
Index is: 0 Sum is: 817.192
Index is: 1 Sum is: 471.18210000000005
Index is: 2 Sum is: 144.7155
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at NewExam.arrayq.columnSum(arrayq.java:11)

Your outer for loop condition is giving you problems. Here's your loop: -
for (int i = 0; i < array[i].length; i++)
Now, when i reaches the value 3, you are trying to access array[3].length. This will throw you IndexOutOfBounds exception.
Since the size of every internal arrays are same, you can change your loop to: -
for (int i = 0; i < array[0].length; i++)
Or, even better, just store the array[0].length in some variable before hand. But that will not make much of a difference.
I would also suggest you to use a better way to calculate the sum of columns. Avoid iterating over rows first. Keep the iteration a normal one probably like this: -
public double[] columnSum(double [][] array){
int size = array[0].length; // Replace it with the size of maximum length inner array
double temp[] = new double[size];
for (int i = 0; i < array.length; i++){
for (int j = 0; j < array[i].length; j++){
temp[j] += array[i][j]; // Note that, I am adding to `temp[j]`.
}
}
System.out.println(Arrays.toString(temp));
return temp; // Note you are not using this return value in the calling method
}
So, you can see that how your problem is highly simplified. What I did is, rather than assigning the value to the array, I added the new value of array[i][j] to the existing value of temp[j]. So, gradually, the value of array[i][j] for all i's (rows) gets summed up in temp[j]. This way you don't have to use confusing iteration. So, just add the above code to your method, and remove the old one.
This method will also work fine, even if you have jagged-array, i.e., you inner arrays are not of same size. But just remember to define the size of temp array carefully.
Also note that, I have used Arrays.toString(temp) method to print the array.

Problem with your code is when it tries to fetch arr[3].length as there does not exist simple solution like sum = sum+arr[i][j] where i refers to row and j refers to column.
int row = arr.length;
int col = arr[0].length;
for(int j = 0; j < cols; j++)
{
int sum = 0;
for(int i = 0; i < rows; i++)
{
sum = sum + input[i][j];
}
}

for (int i = 0; i < array[i].length; i++)
for(int i=0;i<size;i++)
i & size must never be change in the loop

So close. The problem is that you are using array[i].length in your for loop. I changed it from array[i].length to array[0].length and your problem is gone. You need j there but you don't actually HAVE it yet.
You COULD do something like this although there isn't really any point if you know how you are going to get your array. Differently sized lists still would break the code for calculating sum though, you'd have to change that as well.
for (int i = 0, j = 0; i < initialArray[j].length; i++) {
for (; j < initialArray.length; j++) {
System.out.println(i + " " + j);
}
j = 0;
}
And here is your modified program.
public class Main {
static double[][] initialArray = { { 7.432, 8.541, 23.398, 3.981 }, { 721.859, 6.9211, 29.7505, 53.6483 }, { 87.901, 455.72, 91.567, 57.988 } };
public double[] columnSum(double[][] array) {
int index = 0;
double temp[] = new double[array[index].length];
for (int i = 0; i < array[0].length; i++) {
double sum = 0;
for (int j = 0; j < array.length; j++) {
sum += array[j][i];
}
temp[index] = sum;
System.out.println("Index is: " + index + " Sum is: " + sum);
index++;
}
return temp;
}
public static void main(String[] args) {
new Main().columnSum(initialArray);
}
}

for index = 3, i is also equal with 3 and you have array[i].length in your code, but array have 3 item so you get Exception on array[3].length expression
try it
public double[] columnSum(double [][] array){
double temp[] = new double[array[0].length];
for (int i = 0; i < array[0].length; i++){
double sum = 0;
for (int j = 0; j < array.length; j++){
sum += array[j][i];
}
temp[i] = sum;
System.out.println("Index is: " + i + " Sum is: "+sum);
}
return temp;
}

Related

Printing out the sum of rows in a 2D array using a loop

I want to print out my array first then the summation of each row, after my full array, using a nested for loop. But, it seems that nothing else happens after my first nested for loop that assigns values to my 2D array. I want it to look like:
The sum of the 1st row is: ...
The sum of the 2nd row is ... and so on until the last row.
Here is what I have so far.
My code:
public class RowsSum {
public static void main(String[] args) {
int num = 1;
int[][] nums = new int[5][3]; //declaring a 2D array of type int
for (int i = 0; i <= nums.length; i++) {
for (int j = 0; j < nums[0].length; j++) {
num *= 2;
nums[i][j] = num;
System.out.print(nums[i][j] + "\t");
}//closing inner loop
System.out.println("");
}// closing nested for loop
int sum = 0;
int row = 0;
for (int i = 0; i <= nums.length; i++) { //second nested for loop
row++;
for (int j = 0; j < nums[0].length; j++) {
sum = sum + nums[i][j];
}//closing inner loop
System.out.println("The sum of the " + row + "is" + sum + "\t");
System.out.println("");
}// closing nested for loop
}// closing main method
}//closing class
You are not re-initializing the sum variable to 0 before traversing through the row. Also, it's not clear what your second double for-loop is trying to accomplish with this code:
num *= 2;
nums[i][j] = num;
This repeated code is actual altering the values in the array, you should remove it, it is causing unwanted effects.
Adjust to this:
for (int i = 0; i <nums.length; i++){ //second Outer loop
sum = 0;
for (int j = 0; j < nums[0].length; j++){
sum = sum + nums[i][j];
}//closing inner loop
System.out.println("The sum of row " + (i+1) + " is " + sum);
}
Also, the nested for-loops are in fact the inner loops not the outer loops.
EDIT: You are actually also accessing outside of the bounds of the original array, specifically in the outer loops. You have this:
for (int i = 0; i <= nums.length; i++)
Change it to this:
for (int i = 0; i < nums.length; i++)
Note the small change of <= to <, its subtle yet important since arrays are 0 indexed in java so in an array of length 5, the maximum index will be 4.

Find sum of every subarray in 2D array

I'm trying to find the sum of every subarray in a 2D array in Java and store them in a new array. This includes the sums of columns and rows. So far, all I can get down is code that can print out the sum of columns and rows.
I don't care about the complexity. In fact, I want to know the most brute force, obvious answer even if it is O(n^4). I am going to be comparing the subarray sums to a given value to see if that sum exists in the rectangular 2D array.
What I have:
public static void outputArray(int[][] array) {
for (int i = 0; i < array.length; i++){
int sum=0;
for (int j = 0; j < array[0].length; j++){
sum += array[i][j];
}
System.out.println("Print the sum of rows =" + sum);
}
int colSum=0;
for(int col=0;col<array[0].length;col++){
for(int row=0;row<array.length;row++){
colSum+=array[row][col];
}
System.out.println("Sum is "+colSum);
colSum = 0;
}
}
If u don't care about complexity && don't want to store the value then u can do it 0(n^6).
public static void outputArray(int[][] array) {
for(int i = 0; i < array.length; i++){
for(int j = 0; j< array[i].length; j++){
for(int k = i; k < array.length; k++){
for(int l = j; l < array[i].length; l++){
System.out.print("["+i+","+j+"]--->"+"["+k+","+l+"]");
int sum = 0;
for(int x = i; x <= k; x++){
for(int y = j; y<= l; y++){
sum+=array[x][y];
}
}
System.out.println("--->"+sum);
}
}
}
}
}
If u do some optimize like store prefix some then u can do it 0(n^4). With more optimization its possible to solve O(n^3).

Elements of array differ from average and less than number

I have small problem maybe anyone can help me. I have a random elements array, then count the average and scan a number from the user.
I'm looking numbers of elements array differ than average less than the number scanned from user.
public static double average(int[][] array){
double average = 0;
int sum = 0;
for(int i = 0; i < array.length; i++){
for(int j = 0; j < array.length; j++){
sum += array[i][j];
}
}
average = (double) sum/array.length;
return average;
}
public static void main(String[] args) {
Random rnd = new Random();
Scanner scan = new Scanner(System.in);
int[][] array = new int[4][4];
for(int i = 0; i < array.length; i++){
for(int j = 0; j < array.length; j++){
array[i][j] = rnd.nextInt(10);
}
}
int a = scan.nextInt();
average(array);
int elements = 0;
for(int i = 0; i < array.length; i++){
for(int j = 0; j < array.length; j++){
if(array[i][j]) {
// ?? need help here
}
}
}
Here:
average(array);
You are calling your average method ... but you are not using its result!
double averageForArray = average(array);
allows you to later compare against that value, like:
int deltaGivenByUser = scan.nextInt();
for(int i = 0; i < array.length; i++){
for(int j = 0; j < array.length; j++){
if(Math.abs(array[i][j] - average) >= deltaGivenByUser) {
...
Notes:
The above is on a "pseudo code" level; I didn't ran it through the compiler; so beware of subtle bugs/typos. My code is meant to give you an idea how to do things; it is not meant for "copy/paste/solved".
Please look into your naming. A variable name like "a" doesn't say anything. My name deltaGivenByUser is probably not perfect, but at least it gives some idea what that variable will be used for.
Then have a closer look how to work with scanners; for example by using the hasNextInt() method. Right now your code will fail when the user provided something that is not a number
Also separate things: you have a nice method for computing that average; you could also create another method that receives that value provided by the user; to do that processing outside of the main method
This is risky:
for(int i = 0; i < array.length; i++){
for(int j = 0; j < array.length; j++){
sum += array[i][j];
}
You are using the size of the outer array for both loops. Better to use the actual size of the sub array:
for(int i = 0; i < array.length; i++) {
int[] subArray = array[i];
for(int j = 0; j < subArray.length; j++){
sum += subArray[j];
}

Sort Array with two loops Implementation

I am new with Java.
I try to do one of my assignment, but i can not figure out why my result still can not sort.
I have a prompt value(argument) 20 10 30 60 55, and i want to sort it.
I wrote two loops, and converted prompt value (which is string) to Integer.
Result: ( It is not sorted)
20
10
30
60
55
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at question2.SortedArray.main(SortedArray.java:29)
This is the code i wrote:
int temp = 0;
int array[] = null;
int array2[];
for(int i=0; i<args.length; i++){
int a = Integer.parseInt(args[i]);
array = new int[a];
for(int j=0; j<args.length; j++){
int b = Integer.parseInt(args[i]);
array2 = new int[b];
if(array[i]>array2[j])
temp = array2[j];
array2[j] = array[i];
array[i] = temp;
}
}
for (int i = 0; i < array.length; i++)
{
System.out.println(args[i].toString());
}
I could understand this code i fould online below
int tempVar;
for (int i = 0; i < numbers.length; i++)
{
for(int j = 0; j < numbers.length; j++)
{
if(numbers[i] > numbers[j])
{
tempVar = numbers [j ];
numbers [j]= numbers [i];
numbers [i] = tempVar;
}
}
}
for (int i = 0; i < numbers.length; i++)
{
System.out.print(numbers[i]+" ");
}
}
First, convert the String array of args into an int array of values. Then sort and display values. You've been sorting arrays (sized by your array int value), then printing the arguments (which you didn't sort). So, something like
int[] values = new int[args.length];
for (int i = 0; i < args.length; i++) {
values[i] = Integer.parseInt(args[i]);
}
int temp = 0;
for (int i = 0; i < values.length - 1; i++) {
for (int j = i + 1; j < values.length; j++) {
if (values[i] > values[j]) {
temp = values[j];
values[j] = values[i];
values[i] = temp;
}
}
}
System.out.println(Arrays.toString(values));
You need to initialize your array to hold your prompt values
int [] yourArray = {2,3,4 5,};
You don't need a second array to sort the values just a temporary int to hold the value that is being moved.
The statements below if needs to be enclose with { } otherwise all it will do is run to the first semicolon and then get out of the if.
Basically what the code you pasted in the second part is checking if element at the value i is greater than the value at element j. If the value is greater it swaps j with i.
for (int i = 0; i < numbers.length; i++)
{
for(int j = 0; j < numbers.length; j++)
{
if(numbers[i] > numbers[j]) //if element at i is greater than element a j
{
tempVar = numbers [j ]; //store the number at element j in temp
numbers [j]= numbers [i];// set the number at element i to element j
numbers [i] = tempVar;// set the number at temp to element
}
} // does this for each element until no element i greater than j
}
Get the integers to an array at first.
int[] yourArray = { 20, 10, 30, 60, 55 };
for (int i = 0; i < yourArray.length; i++) {
for (int j = 0; j < yourArray.length - 1; j++) {
// swap
if (yourArray[i] < yourArray[j]) {
int temp = yourArray[i];
yourArray[i] = yourArray[j];
yourArray[j] = temp;
}
}
}
for (int i : yourArray)
System.out.println(i);
Output
10
20
30
55
60

2-dimensional array in Java

Assume you are given an int variable named nPositive and a 2-dimensional array of ints that has been created and assigned to a2d. Write some statements that compute the number of all the elements in the entire 2-dimensional array that are greater than zero and assign the value to nPositive.
Code:
for(int i=0; i<a2d.length; i++){
int nPositive;
for(int j=0; j<a2d[a2d.length-1].length; j++) {
if(a2d[i][j] > 0) {
nPositive = a2d[i][j];
}
}
}
It has a compilation error. Why?
The iiner cycle is incorrect:
for(int j=0; j<a2d[i].length; j++){
You didn't initialize nPositive.
// make nPositive a global variable
int nPositive = 0;
for(int i=0; i<a2d.length; i++){
for(int j=0; j<a2d[a2d.length-1].length; j++) {
if(a2d[i][j] > 0) {
nPositive += a2d[i][j]; // add the value into nPositive as you go through the array
}
}
}
I tested it and find that,There is no any compilation error in your code...
for(int j=0; j<a2d[a2d.length-1].length; j++){//
let the length is a2d[10][10]
on statement a2d[a2d.length-1].length ,is equal a2d[10-1].length ,is equal a2d[9].length=>10
your algo is working fine for me ,i found no any error
here's my test code
public class A2dTest {
public static void main(String[] arr) {
int[][] a2d = new int[10][10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
a2d[i][j] = (int) (Math.random() * 100) + 1000000;// all positives
}
}
for (int i = 0; i < a2d.length; i++) {
int nPositive = 0;
for (int j = 0; j < a2d[a2d.length - 1].length; j++) {
if (a2d[i][j] > 0) {
nPositive = a2d[i][j];
System.out.println("nPositive=" + nPositive);
}}
}
}
}
I believe this is one of the questions on codeLab. You just need to properly initialize nPositive at 0 and increment it for every positive integer. That's all they're looking for involving the output. So your code needs to be:
nPositive = 0;
for (int i = 0; i < a2d.length; i++)
{
for (int j = 0; j < a2d[i].length; j++)
{
if (a2d[i][j] > 0)
{
nPositive++;
}
}
}

Categories

Resources