Reputation: 51
I am having trouble in multiplying 2 arrays
.
Firstly, I want to have the user to input 7
int and store it in the first array.
Second array will be a const[] == {2765432};
The question is how do I multiply each of the element in both array
(i.e.) If the user input = 6192354
, this will store first in an array then I want it to multiply with the second array. So it will be
6 * 2.. 1 * 7.. 9 * 6..
etc..
Upvotes: 3
Views: 24883
Reputation: 881313
First off, {2765432}
is not a seven-element array. It is a one-element array holding the single integer 2765432
but you seem to be after the seven-element variety.
To get that array of one-digit values, you need something like:
int second[] = {2,7,6,5,4,3,2};
Then, assuming you've read your user values into another seven-element array, it's as simple as:
for (int i = 0; i < 7; i++)
result[i] = user[i] * second[i];
For example, this program:
#include <iostream>
int main() {
int i, user[7], second[] = {2,7,6,5,4,3,2}, result[7];
for (i = 0; i < 7; i++) {
std::cout << "Enter value #" << (i + 1) << ": ";
std::cin >> user[i];
}
for (i = 0; i < 7; i++) {
result[i] = user[i] * second[i];
}
for (i = 0; i < 7; i++) {
std::cout << user[i] << " * " << second[i] << " = " << result[i] << '\n';
}
return 0;
}
produces the following transcript when run:
Enter value #1: 1
Enter value #2: 3
Enter value #3: 2
Enter value #4: 8
Enter value #5: 4
Enter value #6: 7
Enter value #7: 4
1 * 2 = 2
3 * 7 = 21
2 * 6 = 12
8 * 5 = 40
4 * 4 = 16
7 * 3 = 21
4 * 2 = 8
If you find yourself needing to input one number and have it split up into an array of seven digits, you can start with this:
#include <iostream>
int main() {
int i, val, user[7], second[] = {2,7,6,5,4,3,2}, result[7];
std::cout << "Enter a seven-digit value: ";
std::cin >> val;
for (i = 6; i >= 0; i--) {
user[i] = val % 10;
val /= 10;
}
for (i = 0; i < 7; i++) {
result[i] = user[i] * second[i];
}
for (i = 0; i < 7; i++) {
std::cout << user[i] << " * " << second[i] << " = " << result[i] << '\n';
}
return 0;
}
It uses modulo and division to extract the digits one at a time into the user
array, after which you're in the same situation as had you input the digits directly into the array.
Upvotes: 3
Reputation: 1296
Try to use std::transform
. In the following manner:
#include <algorithm>
#include <functional>
...
std::transform(user, user + 7*sizeof(user[0]), second, result, std::multiplies<int>());
Upvotes: 2
Reputation: 81
Assuming both arrays have the same size, then the code below should work. Otherwise, a different logic would be needed.
for(int i = 0; i < 7; i++)
{
int temp = answer[i] * const[i];
}
Upvotes: 0