/* 24/07/2021 mathematicsv3 Multiplication How integers can over run with multiplication and give very unexpected results */ int q; int w; int myAnswer; long myLongAnswer; void setup() { // Serial.begin(9600) starts serial communication. 9600bps bits per second = 1200 characters per second Serial.begin(9600); //Send script name Serial.println("mathematicsv3..."); //this will print a blank line Serial.println(" "); } void loop() { if (q < 1) { //Example 1 //make q = 1 so the if statement will fail next time round q = 1; Serial.print("q = "); Serial.print(q); //Simple multiplication Serial.println("Simple multiplication"); for (w = 0; w < 10; w++) { // the symbol for multiplication is * myAnswer = w * q; Serial.print(" w ="); Serial.print(w); Serial.print(" myAnswer ="); Serial.println(myAnswer); } //change the value of q to 32760 q = 32760; //the answer can be positive or negative depending on the amount of over run. Serial.println("Simple multiplication...The problem of overflowing the variable type"); Serial.print("q = "); Serial.print(q); for (w = 0; w < 10; w++) { myAnswer = w * q; Serial.print(" w ="); Serial.print(w); Serial.print(" myAnswer ="); Serial.println(myAnswer); } //Example 3 //change the value of q to 32760 q = 32760; Serial.println("Simple multiplication... 2 integers converted to a long"); Serial.print("q = "); Serial.print(q); for (w = 0; w < 10; w++) { myLongAnswer = long(w) * long(q); Serial.print(" w ="); Serial.print(w); Serial.print(" myLongAnswer ="); Serial.println(myLongAnswer); } } }