Learn C++ Lesson 8: Loops

E

EvNTHriZen

Guest
/*

Loops... "While" and "For"

I hope that Cunbelin doesn't mind that i take over, but it seems that it has been a while since he has
updated the Lessons... so i thought i would try to pick it up. If you have a problem with it let me know, and i'll stop. It' s long, BTW...


WHILE LOOPS

This time around we are going to talk a bit about program flow, or, more specifically, "While" loops and "For" loops. A loop is a
basically a bit of code which is marked with a beginning tag, followed by some type of condition which tells the computer when to exit the loop
and contine with the execution of the rest of the code. An example of this in pseudocode (which is code we as humans can read easily)
can be something like the following:

Code:
  while(The_Game_Is_Still_Running is equal to True)
  {
		if(Process_The_Users_Input() is equal to Done_Playing)
			The_Game_Is_Still_Running is False;
  }

  Shutdown_The_Game();

  End();

In the above example, we created a "while" loop and told the computer to check to see if The_Game_Is_Still_Running, and if it is, do
what is included within the braces. Otherwise, don't. Within the while loop we created a conditional expression which calls the function
Process_The_Users_Input(), and if the function returns a value which is equal to Done_Playing, we change the value of The_Game_Is_Still_Running.
When the program flow moves back to the "while" statement, it makes the comparison again, but this time it is false, so the flow jumps down past the
closing brace of the "while" loop, and calls Shutdown_The_Game(). Here it is in real code:

Code:
  //some program stuff up here

  bool The_Game_Is_Still_Running = true;   //always initialise your variables!
  while(The_Game_Is_Still_Running == true)
  {
		if(Process_The_Users_Input() == Done_Playing)
			The_Game_Is_Still_Running = false;
  }

  Shutdown_The_Game();

  //do some more code here

Wait, that looks exaclty the same! Well, almost. The exceptions are that i declared The_Game_Is_Still_Running as a bool
and changed some keywords to lowercase and added equal signs and the comparative operator (the "=="). What we have created here is a simple
game loop... and if you get more into game programming then you will learn more about it.

The "while" statement can be either at the beginning of the block or at the end. so:

while(...)
{
}

and

do
{
}
while(...);

are both perfectly legal. The difference bewteen the two is that the top one is not guaranteed to execute at least one, whereas the bottom will.
Also notice that i added another keyword to the beginning of the loop, and added a semicolon at the end of the "while" statement. syntax, baby, syntax.
You can have full statements in the while loop, and you can also have a infinite loop as well...

while((1+1) == 2);//infinite loop
while(1); //infinite loop
while(true); //inifinte loop
while((somevalue == anothervalue);

you get the idea. To get out of an infinte loop you would use the keyword "break", or press ctrl-break if you did it unintentionally :).
So lets write a simple program which goes into a loop and checks the users input.


Code:
#include <iostream>
using namespace std;


bool ProcessInput()
{
	char answer;
	do
	{
		cout<<"\nWould you like to coninue? (y/n):";
		cin>>answer;
	}
	while((answer != 'y') && (answer != 'n'));	//make sure that the user inputted a valid response, or i'll program will break.
	
	
	if(answer == 'y')
		return true;
	
	return false;
};

int main()
{

	bool bRunning = true;

	cout<<"Entering game loop..\n\n";

	//game loop
	while(bRunning == true)	//check to see if we are still running the game
	{
		if(!ProcessInput())	//if we are, lets process some input!
		{
			bRunning = false;	//if it returns false, the user wants to quit, so...
			continue;			// go to the beginning of the loop.  I could actually use "break" here if i wanted.
		}

		//otherwise, lets do it again!
		cout<<"\nNext Loop!";
	}

	//we aren't shutting anything down.
	cout<<endl;	//for looks ;)

	return 0;
};

A bit about this code.. well, it does the same thing the previous example did. It basically calls a function every frame of the
game loop. I used a keyword in there called "continue". This just tells the program that i want it to start
back at the beginning of the loop, without executing any following code. Antoher keyowrd you could use is "break", which breaks out of the loop.
I could have probably done the same thing with the "goto" keyword, but you really don't want to use that, because It can
lead to code which is difficult to read and follow as well as maintain. If you find yourself using the goto keyword, there is probably a better way.

---> FOR Loops....

Another type of loop is called the "for" loop. It gets it's name from the saying "i want you to repeat FOR this many times until you reach this condition." Essentailly
a for loop syntax has a counter, a condition which breaks the loop, and an incrementing (or decreminting) operator.
the most typical type of "for" loop yo will see probably looks like this:

Code:
  for(int j = 0; j < SomeAmount; j++)
  {
		//do something
  }

j is the counter. It is a normal variable, and can have any name you want. A lot of times you will want to do something a determined
amount of time. The for loop is perfect for such a condition. You can increment the counter, or you can decrement. You can also go
in powers of two, or three. It doesn't matter. You could also do this:

Code:
  for(;;)
  {
  }

This is an infinite loop.

You learned about arrays in #7 of this series. A good example of how to use a "for" loop is to parse an array.

Code:
  int intArray[10];
  int i = 0;
  for(i; i < 10; i++)
  {
		intArray[i] = i*3;		//why not?
		cout<<"the value of i is: "<<intArray[i]<<endl;
  }

A bit about this code: Well, i created an integer array with 10 items in it. then i created a variable called i and intialised it to 0.
then i set up a "for" loop using "i" as the counter, making sure that i is always less then 10, and incrementing it by one everytime. You
might havce noticed that i wrote both loops differently. Both are correct sytactically, but the latter is ANSI compliant, i believe.
Somebody might want to correct me on this.

Since we now know about "for" loops, lets write a program which creates an array of user specified length and display the numbers. Here we go:


Code:
#include <iostream>
using namespace std;

int main()
{

	int Answer = 0;
	unsigned long* Array;

	cout<<"Please indicate an array length:";
	cin>>Answer;

	if(Answer == 0)
	{
		cout<<"You did not specify a length.  Aborting!";
		return 0;
	}

	Array =  new unsigned long[Answer];

	int i = 0;
	for(i; i < Answer; i++)
	{
		Array[i] = i;	
		cout<<"Array Location "<<i<<" is "<<Array[i]<<endl;	
	}

	cout<<endl;

	delete[] Array;

	return 0;
}

A Bit about this code: I used some more advaced stuff here, particularly a pointer to an array which i defined later. Remember in #6 when
he told you that an array was just a pointer to a section of memory? Well, here we name the pointer, but later we use the "new" keyword to tell the
computer that we want to make an array on the Free store (or heap). This is the only way to create a "dynamic" array, as compared to
a static array, which is defined like so:

Code:
  int Array[10];	//static array
  int* Array2;		//dynamic
  Array2 = new int[SomeValue];
  delete[] Array2;

When i am done with the array, i use the delete keyword. It's VERY IMPORTANT you delete any memory you have asked for that isn't static!
Otherwise you create a situation known as a "memory leak", and, as far as i can tell, users don'e like it when their computer slows to a halt
because some neglegent programmer forgot to free memory! Notice also that i used "[]" after delete. You could do this two ways..loop through
and destoy memory one at a time, or kill the whole array using delete[].. it's up to you..



It's pretty simple to write a "for" loop. AS well as single loops, you can nest "for" loops to iterate through more then one demensional arrays.
If you wanted to loop through a 2 demensional array, you would just need to do this:

Code:
  for(int i = 0; i < AomeValue; i++)
		for(int j = 0; j < SomeOtherValue; j++)
			Do Stuff

If you wanted to use a 2D array in a game, think of a top down tilemap. Each square is a member of a 2D array. Lets say you wanted to render the map..

Code:
  //assuming that each array index contains some item that has a Render() function and MapArray is a 2D array
  int x, y;
  for(x = 0; x < MapWidth; x++)
		for(y = 0; y < MapHeight; y++)
			MapArray[x][y].Render();


Simple? I hope you found this educational, and i know it was fairly bland.. but c'mon, it's programming!

*/
 
Back
Top