Which Loops is efficient?? - loops

According to my knowledge loops are used in programming to do repetitive task..
There are certain types of loops like for, while, do while etc... and their syntax differs from each other like for example in while loops we intialize the counter outside and check the conditions in while() and ++ || -- inside the code block, whereas in for loop we do all certain things like initialization,condition checking and ++ || -- in for keyword.
So my question is which loops is efficient and occupies less memory

The loops you listed aren't really going to differ in memory usage or "efficiency". Rather, each one should be used in different situations. A for loop is often used when one needs to iterate through some object that contains multiple indexes or lines etc. For example (Java):
for(int i = 0; i<fooString.length(); i++){
fooCharArray[i] = fooString.charAt(i);
}
You could also achieve the same with a while loop:
int i = 0;
while(i<fooString.length()){
fooCharArray[i] = fooString.charAt(i);
i++;
}
Often, recursion can achieve the sams results as loops, too (though in my example it'd seem slightly wasteful, since a loop could do it so easily). So really, it's more about what you're doing, what's easiest for you, and what makes it the most readable/understandable for you and other programmers.

Related

What is more efficient when using a for loop?

In a lot of for loops that work with arrays I see i < arr.length() as the 2nd statement
Would this:
for(i = 0; i < arr.length(); i++){
//do something
}
be LESS efficient than this:
size = arr.length();
for(i = 0; i < size; i++){
//do something
}?
Or is the difference so small I shouldn't care?
This question only applies to languages that need to use a function in order to find the length of an array/list, unlike java, for example, which is object-oriented and arrays have a length propriety arr.length
The first version can be slower regarding the language, the compiler, its configuration and the loop condition.
Indeed, in C, C++ and Java for example the function is called at each iteration and thus the resulting program can be slower when optimizations are disabled. Other languages, such as Python, have a different kind of loops which walk through given iterables / ranges (eg. list, generators) and the value is evaluated once.
In your case, no performance differences should be seen if optimizations are enabled since the function call arr.length() is usually a constant (in the context of the loop execution) and most compilers are good enough to detect this and to produce a fast equivalent code (you can see a simple example in C++ here). However, please note that interpreters generally do not perform such optimizations.

true/false regarding for and switch

In a C book there was a true/false question in which the following two statements were described as true.
1) Compiler implements a jump table for cases used in a switch.
2) for loop can be used if we want statements in a loop to get executed at least once.
I have following questions regarding these two points:
What is the meaning of statement number 1?
According to me, the second statement should be false, because for this task we a use a do while loop. Am I right?
The first point is somewhat misleading, if it's worded just like that. That might just be the point, of course. :)
It refers to one common way of generating fast code for a switch statement, but there's absolutely no requirement that a compiler does that. Even those that do, probably don't do it always since there's bound to be trade-offs that perhaps only make it worthwhile for a switch with more than n cases. Also the cases themselvesl typically have to be "compact" in order to provide a good index to use in the table.
And yes, a do loop is what to use if you want at least one iteration, since it does the test at the end whereas both for and while do it at the start.
1) It means that a common optimization is for a compiler to build a "jump table" which is like an array where the values are addresses of instructions where the program will execute next. The array is built such that the indexes correspond to values being switched on. Using a jump table like this is O(1), whereas a cascade of "if/else" statements is O(n) in the number of cases.
2) Sure, you can use a "do-while" loop to execute something "at least once." But you'll find that do-while loops are fairly uncommon in most applications, and "for" loops are the most common--partly because if you omit the first and third parts between their parentheses, they are really just fancy "while" loops! For example:
for (; i < x; ) // same as while (i < x)
for (i = 0; i == 0 || i < x; ) // like i = 0; do ... while (i < x)

Which languages support while or do/while loops with automatic iteration indexing?

As the title suggests, which languages support while or do/while loops with automatic iteration indexing?
In other words a [while] or [do/while] loop that provides the iteration index automatically without having to resort to an intrinsically indexed construct such as the [for] loop. This was an odd question to Google which fetched out of context results.
Take the following as an example for C#:
int count = 0;
while (count < 10)
{
Console.WriteLine("This is iteration #{0}", count++);
}
As opposed to the following fictitious loop:
while<int> (value < 10)
{
Console.WriteLine("This is iteration #{0}", value); // Or value-- for that matter.
}
I do not know much about language design and thus the question. the [for] loop has a lot of flexibility but each kind of loop is best suited for certain scenarios. Still, it makes certain scenarios very odd such as combining iterators with indexers.
This is not meant to be an open-ended question. Simply, Do any languages support such constructs, and if not, ummm, cannot ask that here as that would make it open ended
UPDATE: I do realize the complexity that would arise out of nesting such loops but am sure that can be circumvented by some clever naming convention.
Something I had in mind but did not mention was the use of a clever lambda expression in the case of C# for example. That would not be an addition to the language but merely an extension (which I believe is only valid for reflection-friendly platforms such as .NET and Java).
In ruby: array.each_index{|i| print i } will go through each index.
From my memory, the DO ... LOOP words in Forth supported kind of that.
The word to get the index of the current loop was I (obviously!) and that for the next outer loop was J.
Hence
10 1 DO I . 32 EMIT LOOP NL
would print:
1 2 3 4 5 6 7 8 9 10

Why don't people use (int i = length(); i > -1; i--) in for loops instead of creating a new length integer?

Throughout all tutorials and books I've read whilst learning programming the practice for iterating through arrays has always been with for loops using:
int len = array.length();
for(int i = 0; i < len; i++) {//loop code here}
Is there a reason why people don't use
for(int i = length(); i > -1; i--) {//loop code here}
From what I can see the code is shorter, easier to read and doesn't create unnecessary variables. I can see that iterating through arrays from 0 to end may be needed in some situations, but direction doesn't make a difference in most cases.
direction doesn't make a difference in most cases
True, in many cases you'll get the same result in the end, assuming there aren't any exceptions.
But in terms of thinking about what the code does, it's usually a lot simpler to think about it from start to finish. That's what we do all the time in the rest of our lives.
Oh, and you've got a bug in your code - you almost certainly don't want length() as the initial value - you probably want array.length() - 1 as otherwise it starts off being an invalid index into the array (and that's only after fixing length() to array.length()). The fact that you've got this bug demonstrates my point: your code is harder to reason about quickly than the code you dislike.
Making code easier to read and understand is much, much more important in almost every case than the tiny, almost-always-insignificant code of an extra variable. (You haven't specified the language, but in many cases in my own code I'd just call array.length() on every iteration, and let optimization sort it out.)
The reason is readability. Enumerating from 0 and up makes most sense to the most of us, therefore it is the default choice for most developers, unless the algorithm explicitly needs reverse iteration.
Declaring an extra integer variable costs virtually nothing in all common programming platforms today.
Depends on the platform you use. In Java for instance, compiler optimization is so good, I wouldn't be surprised if it doesn't make any noticeable difference. I used to benchmark all kinds of different tricks to see what really is faster and what isn't. Rule of thumb is, if you don't have strong evidence that you are wasting resources, don't try to outsmart Java.
First reason is how you think about it. Generally, as humans, we do iterate from the beginning to the end, not the other way around.
Second reason is that this syntax stems from languages like C. In such languages, going from the end to the beginning was downright impossible in some cases, the most obvious example being the string (char*), for which you usually were supplied with the start address and you had to figure out its length by enumerating until you found 0.

Which is the best way to write Loops?

I would like to know Which is the best way to write Loops?
Is Count Down_to_Zero Loop better than Count_Up_Loops?And particularly in Embedded Systems context which one is better choice ???
In the embedded world it can be better to use one scheme in preference to another dependant upon the processor that you are using. For example the PIC processor has an instruction "decrement and jump if not zero". This is really good for doing a count down "for" loop in a single instruction.
Other processors have different instruction sets so different rules apply.
You may also have to factor in the effects of compiler optimisation which may convert a count up into the possibly more efficient count down version.
As always, if you have to worry about these things then you are using the wrong processor and tools. The idea of writing in a higher level language than assembler is to explain to the maintenance engineer how the software works. If it is counter intuitive to use a count down loop then don't, regardless of the (minor) loss in processor efficiency.
It's personal preference. In the case of arrays, counting up from 0 is usually better because you typically want to process each value in order. Neither style is inherently better, but they may have different results (e.g. if you were printing each value in an array, the order of the output would be different).
In many cases (with the notable exception of arrays), the most logical choice is to use a while loop rather than a for loop, e.g. reading from a file:
int c;
while ((c = fgetc(somefile)) != EOF)
/* Do something */
The main thing to worry about is that you, or someone else, will read the code some time in the future, and person must be able to understand what the code is intended to do.
In other words, write your code in plain text. If you intend to do something ten times, loop from 0 to less-than-10. If you intend to walk backwards through an array, loop from the higher value to the lower.
Avoid placing anything that is not related to the control of the loop in the header of the for statement.
When it comes to efficiency, you can safely leave that to the compiler.
The best way to write a for loop is:
for(i=0; i<N; i++)
for(j=0; j<N; j++)
{
array[i][j] = ... ;
}
Everything else is "premature optimizations", ie things that the compiler really should be able to handle for you.
If you have a dumb compiler however, it may be more effective to count from N down to zero, as compare against zero is faster than compare against value on most CPUs.
Note that N should be a constant expression if possible. Leave out function calls like strlen() etc from the loop comparison.
++i will also be faster if the code might end up at a C++ compiler, where the C++ standard guarantees that ++i is faster than i++, because i++ creates a temporary invisible variable.
The order of the loop should be just as above for most systems, as this is often the most effective way to address cache memories, which is quite an advanced topic.

Resources