Jump to content

Cplusplus: Difference between revisions

1,946 bytes added ,  11 December 2007
no edit summary
No edit summary
No edit summary
Line 240: Line 240:
  #include <iostream>
  #include <iostream>
   
   
using namespace std;
  int main()
  int main()
  {
  {
Line 277: Line 279:
* '''<''' less than
* '''<''' less than
* '''>''' greater than
* '''>''' greater than
==Loops==
Most programming languages support ''loops'', which are useful for executing a certain part of code over and over.
Here is a ''while'' loop
#include <iostream>
using namespace std;
int main()
{
    int a = 0;
    while(a < 100)
    {
        cout << a << endl;
        a++;
    }
    return(0);
}
This will print 100 lines of numbers, going from 0 to 99
0
1
2
3
4
5
...
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.
#include <iostream>
using namespace std;
int main()
{
    int a = 0;
    do
    {
        cout << a << endl;
        a++;
    }
    while(a < 100);
    return(0);
}
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''
#include <iostream>
using namespace std;
int main()
{
    for(int a = 0; a < 100; a++)
    {
      cout << a << endl;
    }
    return(0);
}
This produces the same result, except in a much handier format. There are three things you declare when creating a for loop: a variable, what condition must be met for the loop to continue cycling, and what happens at the end of a loop. a is the initialised variable, the loop will continue until it reaches 100 and at the end of each loop, a is incremented by 1. Simple.


[[Category:Helpdesk]]
[[Category:Helpdesk]]
244

edits