Main Menu

search

You are here

Arduino: Flow Control Statements

[last updated: 2022-08-10]
Arduino home page
Arduino programming - main page
-----

On this page:

  • if ... else ... else if
  • for
  • while
  • switch/case
  • break
  • return

==========================================

  • if ... else:
    if ( [some boolean condition] )
            { [statements] }
    -----


    if no 'else' statement is used, and if there is only One statement to be executed,
    then the curly braces can be omitted:

      if ( [some boolean condition] )
              [statement];

    -----


    if ( [some boolean condition] )
            { [statements] }
    else
            { [statements] }
    -----


    if ( [some boolean condition] )
            { [statements] }
    else if ( [some boolean condition] )
            { [statements] }

    -------------------------------------------

  • for:
    for (int n=0; n <=3; n++) {
      // the "for loop" will repeatedly execute the enclosed statements.
           // The counter, "n"
           // will increment in each loop according to "n++"
           // until the test ("n <=3") fails

    // [statements to execute]

    } // endfor

    • ----------
      Tip to get a Logarithmic progression:
      for (int x = 2; x<100; x = x * 1.5) {
            println(x);
      }

      Using a multiplication in the increment line will generate a logarithmic progression.

    -------------------------------------------

  • while:
    while ( [condition to eval as T/F] ) {
        //statements to execute
    } // endwhile
  • -------------------------------------------

  • switch/case:
    switch ([someVariable]) {
         case value1:
            // statements
            break;
        case valuel2:
            // statements
            break;
        default:
             // statements
    }
    Note: someVariable must be either an int or a single char
    For example, if someVariable is = value1, then the statements following "case value1:" will be executed
  • -------------------------------------------

  • break:
    can be used ( break; ) to force exit from:
    for,
    or while,
    or do-while statements,
    or from case statements, as shown above.
  • -------------------------------------------

  • return:
    can be used to terminate a function and return to the calling function:
          return;
    can also be used to return a value to the calling function, with:
          return value;
    If a value is to be returned, the type of that value must be declared with eg.:
          int functionName() { ... where int is the type of whatever value is to be returned
    as opposed to standard way of defining a function:
          void functionName() { ...

.

.

.

eof