Send
Close Add comments:
(status displays here)
Got it! This site "robinsnyder.com" uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website. Note: This appears on each machine/browser from which this site is accessed.
Loops
1. Loops
For comparison, here are some code examples of loops in C, Java and Python.
The running example is code that outputs the powers of 2 from 0 to 8.
2. While loops
The while loop is a general looping structure. Below is a code fragment in C for a while loop where Condition as a Boolean condition and Statements are a block of statements.
Here is the associated code fragment whileloopgoto using goto statements for code fragment whileloop.
The while loop in C and Java have the same syntax. Here is the Python code fragment for the while loop.
3. Syntax diagram and grammar
Here are the syntax diagrams and grammar for the
while loop in C (or Java).
WhileLoop = "while" Condition "{" { Statement } "}" .
Note:
The curly braces in quotes, "{" and "}", indicate terminal symbols in the file.
The curly braces without quotes indicate repetition of the enclosed parts, in this case, the variable/nonterminal Statement.
4. While loops
For comparison, here are some code examples of while loops in C, Java and Python.
5. Style comments
Here are some style comments.
I end many of my variable names with a digit.
I often separate declarations from initialization.
Most of my code examples are automatically and dynamically generated and run and included from a higher level text specification and text formatter system to look like they were hand-written. But sometimes it may be obvious that the code was generated and not hand-written.
6. C code and output
Here is the C code [#3]
Here is the output of the C code.
7. Java code and output
Here is the Java code [#1]
Here is the output of the Java code.
8. Python while loop
Python is dynamically typed and does not require type declarations as does C or Java.
Unlike C or Java, Python uses indentation and not curly braces to determine blocks (of statements, methods, etc.).
9. Python code and output
Here is the Python code [#2]
Here is the output of the Python code.
10. For loops
For comparison, here are some code examples of for loops in C, Java and Python.
The for loop is more complicated than the while loop, is less general, and has subtle semantics that vary from language to language. It is best to only use simple for loops that iterate from start to stop by increment 1.
11. C code and output
Here is the C code [#4]
Here is the output of the C code.
12. Java code and output
Here is the Java code [#2]
Here is the output of the Java code.
13. Python for loop
The Python for loop is general iterator structure and therefore takes a range object which goes from the start value up to, but not including, the ending value (for positive ranges).
14. Python code and output
Here is the Python code [#3]
Here is the output of the Python code.
15. End of page