Jump to content
Search In
  • More options...
Find results that contain...
Find results in...

What is a good way to get better at For Loops (C++/Java)

Recommended Posts

Strip a for loop down to bare minimum:

for (initialization; condition; action) {
  // stuff

It's purpose is not meant to be just be a "have an int and increment it" as an index. It can be used for many more things than just that. Consider this for iterating over a linked list:

Item *head;
for (Item *item = head; item != null; item = item.Next()) {
  // do things with item

Or this for iterating over a ring:

Item *head;
for (Item *item = head; item != head; item = item.Next()) {
  // do things with item

Or this for reading a file until End Of File is hit:

byte[] data; // you'd need to allocate first of course
for (Result res = file.Read(data); res != EOF; res = file.Read(data)) {
  // do things with data

Feel free to adapt this, but note that this is from memory.

Pseudocode for imagining what a for loop does (just in a more attractive notation):

/* This */
for (int i = 0; i < some_num; i++) {
  // stuff

/* Is this underneath */
	int i = 0; // initialization
	// stuff
	if i < some_num: // condition
		i++; // action
		jump Loop;
		jump EndLoop:
	// continue on

This will always be the same, for the linked list or the file reading example. A for loop is merely that construct. Once you get that, you should be more comfortable with it.

Link to post
Share on other sites

Devblox has good advice, and depending what you're working on (and what language and version), I'd also consider using lambdas:


List<String> strList = getTheListOfStrings();
strList.foreach(str -> { 

// can also be abbreviated to

strList.foreach(str -> this::printTheString);


Javascript has got the same sort of thing in it.


For brain-melting advanced programmer points, consider using Streams.



Link to post
Share on other sites

Also if you are removing things from the thing you are iterating on, remember to use a concurrency-compatible operation.

Intel i7 5820K (4.5 GHz) | MSI X99A MPower | 32 GB Kingston HyperX Fury 2666MHz | Asus RoG STRIX GTX 1080ti OC | Samsung 951 m.2 nVME 512GB | Crucial MX200 1000GB | Western Digital Caviar Black 2000GB | Noctua NH-D15 | Fractal Define R5 | Seasonic 860 Platinum | Logitech G910 | Sennheiser 599 | Blue Yeti | Logitech G502


Nikon D500 | Nikon 200-500 f/5.6 | Nikon 50mm f/1.8 | Tamron 70-210 f/4 VCII | Sigma 10-20 f/3.5 | Nikon 17-55 f/2.8 | Tamron 90mm F2.8 SP Di VC USD Macro | Neewer 750II

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now