I've ran in to a small problem regarding some code I need to write.
I have to use an array to store the square of numbers 1-9 and fill the array using a do/while loop. Input and output using the serial monitor.
My code gets as far as asking me to enter a number from 1-9, and then telling me my squared number is, but the answer it gives me is wrong?
For instance, if I enter 2 I would expect to get 4, but I get 1536?
Could somebody advise what I am doing wrong as I can't for the life of me figure it out?
Thanks
Code is:
void setup(){
Serial.begin(9600);
}
void loop(){
int x = 0;
int squarenum[10];
do{
squarenum[x]=x*x;
x=x+1;
Serial.println("Enter a number 1-9");
while(!Serial.available());
x = Serial.parseInt();
if (x<1||x>9){
Serial.println("You have entered an invalid number");
}
else{
Serial.print("Your number squared is ");
Serial.println(squarenum[x]);}
}while (x<10);
}
Your code is completely out of order. You square a number, put it into the array, and then tell the user to enter a number and simply show that array value.
The order should be
Prompt for number
Square number
Display to user
I don't know what purpose the array is supposed to serve, but I'll leave that up to you.
Thanks for your reply cedarlake.
Unfortunately, it is part of my assignment to have the code work it out instead of adding the square of the numbers to the array before hand.
I can get it to work in a while loop;
void setup(){
Serial.begin(9600);
}
void loop(){
int x = 0;
int squarenum[10];
while(x<10){
squarenum[x]=x*x;
x=x+1;}
Serial.println("Enter a number 1-9");
while(!Serial.available());
x = Serial.parseInt();
if (x<1||x>9){
Serial.println("You have entered an invalid number");
}
else{
Serial.print("Your number squared is ");
Serial.println(squarenum[x]);
}
}
seems that you square the value before it is read
and is seems the idea is to generate the squares before the value is read so that it's just a look up
consider
int squarenum [10];
void loop ()
{
if (! Serial.available ())
return;
int x = Serial.parseInt ();
if (x<1 || x>9)
Serial.println ("You have entered an invalid number");
else {
Serial.print ("Your number squared is ");
Serial.println (squarenum [x]);
}
Serial.println ("Enter a number 1-9");
}
void setup ()
{
Serial.begin (9600);
for (int x = 0; x < 10; x++)
squarenum [x] = x*x;
Serial.println ("Enter a number 1-9");
}