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:


#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("%dn", i);
}
return 0;
}

But you should avoid for loop if the variable needs to be updated in for loop.

Which loop should I select in Programming

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("%dn",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.

Looking for more effecive Course?

C Programming For Beginners by Udemyicon
$15 (Original $145)
30-Day Money-Back Guarantee
Buy

Includes:

  • 6 hours on-demand video
  • 1 Article
  • 2 Supplemental Resources
  • Full lifetime access
  • Access on mobile and TV
  • Certificate of Completion


About The Author

Comments

Write a Reply or Comment

Your email address will not be published. Required fields are marked *