Friday, December 8, 2017

Loops in C programming

Did you ever write a single word hundred or thousand times as a punishment in your school life ? I guess most of us are familiar with this type of punishment. If yes, then it is very easy to understand what is loop and what it does.

Sometimes you have to repeat some particular block of code several times. Simply you can write those code several times. Surely this is a solution but not the efficient one. Using loop we can execute any block of code several times.

Look at the following example, where I want to print “Hello World” 5 times. You don’t have to be worry about the program/syntax (loop part) right now, we will discuss it on this section. Just see how simply we can repeat any block of code.


#include <stdio.h>

int main() 
{
      printf(“Hello World \n”);
      printf(“Hello World \n”);
      printf(“Hello World \n”);
      printf(“Hello World \n”);
      printf(“Hello World \n”);

      return 0;
}


Using while loop

#include <stdio.h>

int main() 
{
      int cnt = 1;
      while(cnt <= 5)
      {
           printf(“Hello World \n”);
           cnt++;
      }
      return 0;
}


Which one you will prefer when you have to write it millions of time ?

We can follow any of those process as both are valid but loops save our code, effort and time also. Repeating 5 times is not a big deal we can type this 5 times but when we have to do the same thing thousand or million time then loops are the best option.

Note
  • It saves code and time.
  • Makes program simple.

This section we will talk about

  • for loop
  • while loop
  • do while loop
  • Nested loop
  • Infinite loop


Previous Topic

Next Topic



No comments:

Post a Comment