Wednesday, December 14, 2016

Which loop should I select in Programming?

Last Update:

Recommended Cloud & Hosting: Cloudways, Hostinger & BlueHost
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("%d\n", 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("%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.

Looking for more effecive Course?

C Programming For Beginners by Udemy icon
$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 me


Elliyas Ahmed
Elliyas Ahmed

Hi, I am Elliyas Ahmed, the founder of ComProMath. I try to share what I learn.

Work With Me - SEO Expert, WordPress, Blogger Theme Developer on Fiverr

Lets Disucss on this Article

Don't try SPAMMING here! Submit your Feedback, Questions or Comment related to this Article. Read our Comment Policy.