[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CppFor

(C++) for

Keyword enabling you to perform a for-loop.

for( [initialization] ; [condition] ; [step] )
{
  [statements]
}


This enables you to count from value X to (and not including) value Y in steps of Z:

  1. include <iostream>
int main() { const double X = 69.69; const double Y = 96.96; const double Z = 0.69; for (double counter=X; counter<Y; counter+=Z) { std::cout << counter << std::endl; } }


Most for loops are used for working with arrays, std::vectors or other indexable classes or data types. As indexes start at 0 and cannot be negative, an indexing for loop, looks like this:

  1. include <iostream>
  2. include <vector>
int main() { //Create a random-sized std::vector std::vector<int> myVector(rand()%100); //Fill it with random values const int myVectorSize = myVector.size(); for (int i=0; i!=myVectorSize; ++i) { myVector[i] = rand()%69; } //Print it to screen for (int i=0; i!=myVectorSize; ++i) { std::cout << i << " : " << myVector[i] << std::endl; } }


Prefer algorithm calls over hand-written loops [1,2].

When using STL classes like std::vector, there are techniques, using iterators and std::for_each:

  1. include <iostream>
  2. include <vector>
int main() { //Create a random-sized std::vector std::vector<double> myVector(100); //Fill it with random values const int myVectorSize = myVector.size(); for (int i=0; i!=myVectorSize; ++i) { myVector[i] = sqrt(rand()%69); } //Print it to screen for (std::vector<double>::const_iterator i = myVector.begin(); i!=myVector.end(); ++i) { std::cout << *i << std::endl; } }


Topic links

'for' links

References



last edited (November 6, 2006) by bilderbikkel, Number of views: 6454, Current Rev: 18 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.