 # if() and for() structures

Beating my head against a desk trying to figure out this really simple bit of #arduino programming.

The objective I am trying to meet is to write a program to print "Hello" fifty times on your computer twice. Use if() structure once, and for() structure once.

I have this code below which can print a numbered list of 50 "hello"s, but not sure how to end it after two loops using a for loop, or if I'm just going the wrong way to start.

int x = 1; void setup() { Serial.begin(9600); delay(2000); }

void loop() { Serial.println(x); Serial.println("Hello"); delay(100); x++; if (x>50) {delay(1000); x=1;}; }

Am I going the wrong direction? How would you do this simple task?

How would you do this simple task?

``````void setup()
{
Serial.begin(115200);
for(int i=0; i<2; i++)
{
for(int j=0; j<50; j++)
{
Serial.println("Yo");
}
}
}

void loop()
{
}
``````

You could do it in loop() instead, and use a counter.

``````void loop()
{
static int i = 0;
if(i < 2)
{
for(int j=0; j<50; j++)
{
Serial.println("Yo");
}
i++;
}
}
``````

Hope we get a good grade.

Heh, not a real homework assignment, just a practice problem :)

Still getting a hang of this coding thing. Took this class as a senior elective - I am a mechanical engineer with zero coding and the bare minimum of basic ECE... a whole new world this arduino playground is...

Loop will run indefinitely. If you want it to stop at 50, try:

``````void loop() {
If ( x++ <= 50 ) {
Serial.println( x );
Serial.println( "Hello" );
delay( 100 );
}
}
``````

Oh and a big THANK YOU to PaulS as well, since I seemed to have forgotten my manners and left out a thank you in the first reply!

If you want a sketch to perform a task and then stop you could also put the code inside setup() and leave loop() totally void:

loop() { }