Which loop should I select in Programming?
Which loop should I select in Programming?
You should select for loop cause of the following:
- If you know the exact number of times or counting number you want to loop iteration.
- If you want to do multiplication table.
- If you want to iterate over arrays.
- If you have single loop condition.
Example:
But you should avoid for loop if the variable needs to be updated in for loop.
#include <stdio.h>
int main(int argc, char const *argv[])
{
int count = 10; // Exact number of time is known
for (int i = 0; i < count; ++i)
{
printf("%d\n", i);
}
return 0;
}
But you should avoid for loop if the variable needs to be updated in for loop.
You should select while loop cause of the following:
- If you don't know the exact number of times or counting number you want to loop iteration but you know the condition till the loop will be continued.
- If you need the variable to be updated.
- If you need to update step requires multiple lines of code.
- If you have a complicated loop condition.
Example:
#include <stdio.h>
int main(int argc, char const *argv[])
{
int i = 0;
int j = 5;
while ( i < 10 && j > 0 )
{
printf("%d\n",i * j);
j = i - j;
i++;
}
return 0;
}
You should select do while loop cause of the following:
Expert programmers always suggest to avoid this loop without using do-while loop to do something at least once.