if condition fail

hello everyone,
I am arduino beginners, I am executing a simple if condition in void loop function. In that
I want to print the “count” value in one time if my count==3 otherwise it will not to print. My doubt is,while executing my program it will print the count value more than one time. My output is 3 3 3 3 and so on.

Below I attached my program.

int count = 0;
void setup() {
Serial.begin(9600);

}

void loop() {

if (count == 3) {
Serial.println(count);
}
count++;
}

The if statement is not failing. It is doing exactly what you programmed.

Take out the if statement and see what is printed. Then you will see why you have a series of 3s.

hint: when does the count stop incrementing? what happens if/when it reaches its maximum value?

What range of values fits in an int? What happens if you try to store a larger value?

When count gets to 32767, and is incremented again, it becomes -32768. Because nothing else happens in loop(), count increments very rapidly back to 0, up to 3, and on up to 32767 again, where the rollover happens again, and round and round you go.

What are you REALLY trying to do?

Ahhh. You told him the answer. :D

Try this:

int count = 0;

void setup() {
  Serial.begin(9600);
}

void loop() {
  if ((count < 3) && (++count == 3)) {
    Serial.println(count);
  }
}

Danois90:
Try this:

int count = 0;

void setup() {
 Serial.begin(9600);
}

void loop() {
 if ((count < 3) && (++count == 3)) {
   Serial.println(count);
 }
}

How does that fix the problem?

(sorry I’m away from my arduino to test it personally)

How does that fix the problem?

The second part of an if statement won't be evaluated if the first part is false. So, once count becomes 3, it will never be incremented again.

Thank you guys, providing a solutions for my problem.

I have small doubt in my previous program. I did not understand,my count will get incremented but if condition will be true. what will be the reason behind this.

int count = 0; void setup() { Serial.begin(9600);

} void loop() { if(count==3){ Serial.println(count); } count++; }

If you format the code properly then it is much easier to see what is going on

int count = 0;
void setup()
{
  Serial.begin(9600);
}
void loop()
{
  if (count == 3)
  {
    Serial.println(count);
  }
  count++;
}

count is incremented each time through loop() whether or not the if returns true and the value of count is printed. The for loop will run very quickly, so count will be incremented very quickly until its value rolls over to zero and it starts counting up again as explained in reply #2

Thank you UKHeliBob for your kind information.Now I can understand what happened inside my program.