Loops and beginners (some tips)

Cycles and beginners

My post will be short, but I think it will be useful for beginners.
Cycles.
They are everywhere. It's hard to imagine a program without loops.
But sometimes we don’t think about the correct organization of the cycles.
What I mean ? The number of operations within the loop should be kept to a minimum.
This means that if we can calculate any coefficient in advance (not in a loop),
then it must be calculated.

Example 1 :

for(int i = 0 ; i < k - 2; i ++){...}

If k does not change within the cycle, then the limiting difference must be calculated in advance.

It should be like this:

 int limit = k - 2;
 for(int i = 0 ; i < limit; i ++){...}

Example 2 :

  for(auto i : foo){
   ...
   if(t*t > 20) k = t*t + 20;
   ... 
}

If any action is evaluated more than once, it must be evaluated once and stored in a variable

It should be like this:

  for(auto i : foo){
   ...
   int temp = t*t;
   if(temp > 20) k = temp +20;
   ...
} 

Example 3 :

  for(int i = 1 ; i < k ; i++){
   ...
   if(arr[i] - arr[i - 1] > 0){...}
} 

If you can start another counter inside the loop, it should be started
(increment is faster than subtraction)

It should be like this:

for(int i = 1, j = 0 ; i < k ; i++, j++){
   ...
   if(arr[i] - arr[j] > 0){...}
} 

I hope these simple tips will improve your code. =)

Comments (1)