CS 1073 Introductory Programming
|
public class Arrays {
public static void main(String[] args) {
int[] a = {12, 23, 34, 45, 56};
int[] b = {4, 1, 2, 5, 3};
for (int i = 0; i < a.length; i++) // loop to print numbers
System.out.print(a[i] + " ");
System.out.println();
int sum = 0;
for (int i = 0; i < a.length; i++) // loop to add numbers
sum = sum + a[i];
System.out.println("Sum of entries: " + sum);
int[] c = new int[a.length];
for (int i = 0; i < a.length; i++) // loop to add arrays
c[i] = a[i] + b[i];
for (int i = 0; i < c.length; i++) // now print new array
System.out.print(c[i] + " ");
System.out.println();
int innerProduct = 0;
for (int i = 0; i < a.length; i++) // loop to add arrays
innerProduct = innerProduct + a[i]*b[i];
System.out.println("Inner Product of a and b: " + innerProduct);
}
}
Here are results of a run:
12 23 34 45 56 Sum of entries: 170 16 24 36 50 59 Inner Product of a and b: 532
public class Arrays2 {
public static void printArray(int[] x) {
for (int i = 0; i < x.length; i++) // loop to print numbers
System.out.print(x[i] + " ");
System.out.println();
}
public static int addElements(int[] x) {
int sum = 0;
for (int i = 0; i < x.length; i++) // loop to add numbers
sum = sum + x[i];
return sum;
}
public static int innerProduct(int[] x, int[] y) {
int innProd = 0;
for (int i = 0; i < x.length; i++) // loop to add arrays
innProd = innProd + x[i]*y[i];
return innProd;
}
public static int[] addArrays(int[] x, int[] y) {
int[] z = new int[x.length];
for (int i = 0; i < x.length; i++) // loop to add arrays
z[i] = x[i] + y[i];
return z;
}
public static void main(String[] args) {
int[] a = {12, 23, 34, 45, 56};
int[] b = {4, 1, 2, 5, 3};
printArray(a);
System.out.println("Sum of entries: " + addElements(a));
int[] c = addArrays(a, b);
printArray(c);
System.out.println("Inner Product of a and b: " +
innerProduct(a, b));
}
}
Here are results of a run. Notice that these results are exactly the same as the previous ones.
12 23 34 45 56 Sum of entries: 170 16 24 36 50 59 Inner Product of a and b: 532