Bifalgorithm post · Computer science one · For Loops

How are for loops structured in C?

How are for loops structured in C? (Computer science one · For Loops) — "17.2. For Loops\n\nFor loops in C use the familiar syntax of placing the initializatio…

Ideas in this flowchart

  • For loops in C
  • The for keyword combines initialization, continuation condition, and iteration on one line.
  • The initialization and continuation condition are separated by semicolons; the iteration statement is not followed by one.
  • Example: for(i=1; i<=10; i++) { /* perform some action */ }
  • The opening curly bracket appears on the same line as the for keyword.
  • Statements inside the loop body are indented at the same indentation level.
  • In the example, the index variable i is declared before the for loop.
  • Some languages allow the index variable to be declared in the initialization statement.
  • Declaring the index variable in the loop 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 declaring the variable in the initialization statement.
  • Some compilers also support the newer syntax through non-standard C extensions.
  • For maximum portability, the older declaration convention is followed.
Feed/

How are for loops structured in C?

No cover

Channel

Computer science one

1 page

"17.2. For Loops\n\nFor 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.