Bifalgorithm post · Computer science one · Do-While Loops

How are for loops structured in C?

How are for loops structured in C? (Computer science one · Do-While Loops) — "For loops in C use the familiar syntax of placing the initialization, continuatio…

Ideas in this flowchart

  • For loops in C
  • The initialization, continuation condition, and iteration appear on the same line as the for keyword.
  • Code Sample 17.3 demonstrates a for loop with i initialized to 1 and continued through 10.
  • Semicolons follow the initialization and continuation condition, but not the iteration statement.
  • The opening curly bracket shares the for line, and the loop body is indented consistently.
  • In the shown convention, the index variable i is declared before the for loop.
  • Some languages allow the index variable to be declared in the initialization statement.
  • Declaring i in the initialization scopes it to the loop, so it is unavailable before and after the loop body.
  • C89 and earlier standards require the variable to be declared before the loop.
  • C99 and newer standards allow declaration of the index variable in the initialization statement.
  • The older declaration convention is followed for maximum portability.
Feed/

How are for loops structured in C?

No cover

Channel

Computer science one

1 page

"For loops in C use the familiar syntax of placing the initialization, continuation condition, and iteration on the same line as the keyword for. An example can be found in Code Sample 17.3.\n\n1 int i;\n\n2 for(i=1; i<=10; i++) {\n\n3 //perform some action\n\n4 }\n\nCode Sample 17.3.: For Loop in C\n\nSemicolons are placed at the end of the initialization and continuation condition, but not the iteration statement. Just as with while loops, the opening curly bracket is placed on the same line as the for keyword. Code within the loop body is indented, all at the same indentation level. Another observation is that we declared the index variable i prior to the for loop. Some languages allow you to declare the index variable in the initialization statement, for example for(int i=1; i<=10; i++). Doing so scopes the index variable to the loop and so i would be out-of-scope before and after the loop body. This is a nice convenience and is generally good practice. However, C89 and prior standards do not allow you to do this; the variable must be declared prior to the loop structure. C99 and newer standards do allow you to do this and some compilers will be somewhat forgiving when you use the newer syntax (by supporting their own non-standard extensions to C). For maximum portability, we’ll follow the older convention."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.