Arrays

Hi There,

I am very new to all of this and I have been working through the manual that came with the kit. I have come across arrays and it gave me an example which I followed. Everything has worked fine but I can’t understand why I have the output I do for Array 1. I have attached the code and I was wondering if someone can please explain why the output is 336.

Thanks in advance.

Arrays.ino (719 Bytes)

I can’t understand why I have the output I do for Array 1.

What were you expecting to see? What did you actually see? How did those two things differ?

For array 1 it should print out

1
2
3
4

because that’s what you set all four of the array values to.

OP’s code:

// Arrays

int Array_1[4];
int Array_2[]={5,2,9};

void setup() {
  Serial.begin(9600);
  Serial.println("Arduino Arrays");
  Serial.println();
}

void loop() {
  byte x;

  Array_1[0]=1;
  Array_1[1]=2;
  Array_1[2]=3;
  Array_1[3]=4;

  Serial.println("Output of Array 1 ");
  Serial.println("----------------");

  // Output the data of the first array
  for(x=0;x<4;x++);
  {
    Serial.print(Array_1[x]);
    Serial.println();  
  }

  Serial.println("Output of Array 2 ");
  Serial.println("----------------");

  // Output the data of the second array
  Serial.print(Array_2[0]);
  Serial.println();
  Serial.print(Array_2[1]);
  Serial.println();
  Serial.print(Array_2[2]);
  Serial.println();

  while(1);
}

  for(x=0;x<4;x++);The trailing semicolon should not be there

I was expecting to see

1
2
3
4

Now I have removed the semicolon I have the result I expected Thank you for this.

Can someone explain why the semicolon created the result i ended up with?

The semicolon was the only code executed by the for loop

A for loop executes the next statement after. That can be a single statement, it can be a compound statement (many lines inside { and }) or it can even be the empty statement, the semicolon. The semicolon literally means, "Do nothing". So your for loop read, do "Nothing" 4 times. Without the semicolon the next thing after the for loop is the compound statement:

{
    Serial.print(Array_1[x]);
    Serial.println();  
  }

I understand now thank you for this, it has been a real help.