Jump to content

Cplusplus: Difference between revisions

12 bytes added ,  11 December 2007
no edit summary
No edit summary
No edit summary
Line 282: Line 282:
==Loops==
==Loops==


Most programming languages support ''loops'', which are useful for executing a certain part of code over and over.
Most programming languages support '''loops''', which are useful for executing a certain part of code over and over.


Here is a ''while'' loop
Here is a '''while''' loop


  #include <iostream>
  #include <iostream>
Line 313: Line 313:
  ...
  ...


The condition to make sure that a is less than 100 is checked at the start of each loop, and a is incremented by 1 at the end of each loop (denoted by ''a++''; you can also use ''a--'' to decrement by 1). Therefore, when a reaches 99, it will be printed to screen, then incremented. The loop will then check to see if it is less than 100, which it is not, resulting in the termination of the loop.
The condition to make sure that a is less than 100 is checked at the start of each loop, and a is incremented by 1 at the end of each loop (denoted by '''a++'''; you can also use '''a--''' to decrement by 1). Therefore, when a reaches 99, it will be printed to screen, then incremented. The loop will then check to see if it is less than 100, which it is not, resulting in the termination of the loop.


While loops are handy in games where you may want something to loop endlessly until the user makes an action (presses a key, for example). Here is a variation of the while loop, called the ''do while'' loop.
While loops are handy in games where you may want something to loop endlessly until the user makes an action (presses a key, for example). Here is a variation of the while loop, called the '''do while''' loop.


  #include <iostream>
  #include <iostream>
Line 337: Line 337:
This print the same 100 lines, 0 to 99. However, the condition for the loop is not checked until the end of the loop.
This print the same 100 lines, 0 to 99. However, the condition for the loop is not checked until the end of the loop.


If you're dealing with finite numbers of loops, you may want to consider the ''for loop''
If you're dealing with finite numbers of loops, you may want to consider the '''for loop'''


  #include <iostream>
  #include <iostream>
244

edits