// I heavily modified the original code, because Arduino provides functions
// which parse the serial input for you, thus not requiring the manual checking
// for newline characters, casting data types, dealing with things 1 byte at a time, etc.
void setup()
{
Serial.begin(9600);
Serial.println("Enter the number of Multiplications (up to 25), and then the pairs of numbers to be multiplied (in a list separated by spaces or commas");
Serial.setTimeout(5000); // max time allowed between serial inputs
}
void loop()
{
int numOfMults = 0; // number of pairs to multiply
float *numArray; // pointer to beginning of array memory block
numArray = (float *)malloc(sizeof(float)*50); // dynamically allocate an array that can hold up to 50 floats
numOfMults = Serial.parseInt(); // take in the number of multiplications from user
Serial.println(numOfMults);
// take in the specified amount of numbers (2 times the num of multiplications) in format: 1,2,3...
// then convert that into an array of floats, where every 2 indices
// is a pair of numbers to multiply
for (int i = 0; i < (2*numOfMults) ;i++)
{
numArray[i] = Serial.parseFloat();
Serial.println(numArray[i]);
}
multNums(numOfMults,numArray); // call function to get the product of all the numbers
delay(5000); // wait 5 seconds before starting the loop again
}
void multNums(int numofNums,float nums[])
{
float *productArray; // pointer to beginning of the product array memory block
productArray = (float *)malloc(sizeof(float)*25); // dynamically allocate an array that can hold up to 25 floats (for the products)
// multiply all the number pairs in the array, store the product in another
for(int i=0;i<numofNums;i+2)
{
productArray[i/2] = nums[i]*nums[i+1]; // multiply current number pair, store in the product array one index at a time
}
// print the products
for(int i=0; i < sizeof(productArray) ;i++)
{
Serial.println(productArray[i]);
}
}