'How do i multiply two one-dimensional arrays?
I will be honest with you, I have absolutely no idea what i am doing, nor have the slightest of ideas where to look and it is my homework so if someone would be kind enough to help me out, I would be truly grateful.
"Write a program that declares three arrays named price, qty, and amt. Each array should be declared in main()and capable of holding 3 values. Make up numbers for price and qty (quantity).(ShoppingCart.java) (4 pts) Write a method to fill the amt array with the product of the corresponding elements in price and qty. (3–create a method within the ShoppingCart class)"
What i have attempted is just this:
public class Shoppingjava {
public static void main(String[] args) {
int price[] = {4, 9, 7};
int qty[] = {2, 5, 3};
int amt[] = new int[3];
System.out.println(product(price, qty));
}
public product(int P[], int Q[]) {
int[][] c = new int[P.length][Q.length];
return product;
}
}
But i really don't know where to go with this, I am sorry to bother anyone with this and if it someone is willing to help me out, thank you.
Solution 1:[1]
Array elements can be accessed by their index in the form int val = arr[0] (for retrieving) or arr[i] = val (for storing).
You can iterate through the parallel arrays price and qty with a for loop, cycling through each index, and storing the product of each pair in amt.
Generic code:
for (int i = 0; i < arrZ.length; i++) {
arrZ[i] = arrX[i] * arrY[i];
}
Your scenario:
for (int i = 0; i < amt.length; i++) {
amt[i] = price[i] * qty[i];
}
I'd also recommend referring to the Java tutorials for using arrays: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Solution 2:[2]
public class ShoppingCart {
public static void main(String[] args) {
int price[] = {4, 9, 7};
int qty[] = {2, 5, 3};
int amt[] = new int[3];
for (int i = 0; i < price.length; i++) {
amt[i] = price[i] * qty[i];
System.out.println(amt[i]); //TESTING
}
}
Solution 3:[3]
public class ShoppingCart {
public static void main(String[] args) {
int price[] = {4, 9, 7};
int qty[] = {2, 5, 3};
int amt[] = new int[3];
//calculate amounts
product(price, qty, amt);
//prints details
System.out.println("Price Quantity Amount");
for (int i = 0; i < price.length; i++) {
System.out.println(price[i]+" "+qty[i]+" "+amt[i]);
}
}
public static void product(int price[], int quantity[], int amount[]) {
for (int i = 0; i < price.length; i++) {
amount[i] = price[i] * quantity[i];
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | always007 |
| Solution 3 | Dinushika Rathnayake |
