Archive

Posts Tagged ‘cplusplus’

The For(); Loop

May 13th, 2009 admin No comments

Many new programmers are perplexed by the “for” loop. However, it is one of the most essential and powerful tools in any developer’s arsenal. Without it, efficient and clean programming would not be as possible. Early on, most developers seem to stick to the while(); loop. I mean sure, while(); is great for some things, but may not exist in some programming languages and not to mention won’t work for everything you need.

Let’s begin by going into the basics about the for(); loop. Well really, a lot depends on the programming language (I will provide both PHP and C++ examples in the source file). But more or less, the for(); loop is simply iteration. It will run until its defined limit is hit providing whatever results you wish. We’re going to do this in more standard languages (e.g.: C/C++ and Java) instead of PHP for mass compatibility. Just note, if you’re looking to do this for php, you do not need to define the type of variable, and your variable will just start with the “$” symbol. So for example, PHP would be for($i=0;…;…){}.

Now we’re going to write a sample program and break it down:

for(int i=0;i<=5;i++){
std::cout<< "This is line number "<< i << std::endl;
}

Now as most of you may have noticed, this is a C++ example, but will effectively explain how the loop works for ALL programming languages!

int i=0; – This simply defines the variable and starting place (0 in this case). In PHP you would simply use $i=0; and so on for the rest of the statements.
i<=5 – This tells the loop when to stop (This <= symbol means less than or equal to). When i>5, the loop will stop and proceed on to the rest of the code.
i++ – This tells what the loop should do after every time it is run. In this case, we’re using i++ which means to add 1 each time around.

Now those are the basics to the loop. What lies within is just simply the code to be executed, which could of course have conditionals and such within it as well (e.g.: if(), etc.). So now we’ll move on to a more complex example.

unsigned int choices=5;
char* choice = new char[choices];
for(int i=0;i<=choices;i++){
std::cout<<"Please enter a value: ";
std::cin>>choice[i];

if(!choice[i]){
std::cout<<"No value for choice "<< i<< std::endl;
}
}
for(int i=0;i<=choices;i++){
std::cout<<"Choice "<< i<<" was "<< choice[i] << std::endl;
}

This will store an array of choices and then after entering them, they will be printed back!

In the source below, all working examples will be provided!
For(); Loop Tutorial

So, that basically wraps everything up! If you need anymore clarification, just let me know.

Regards,
Dennis M.

Categories: C/C++, Java, Other, PHP Tags: , , , , , ,