For Loop

For loop is used to do the task which contains repetition. In general, we should use a for loop when you know how many times the loop should run. If you want the loop to break based on a condition other than the number of times it runs, you should use a while loop. In for loop the condition is checked at the very last.

LOGO


Syntax: for( initializing ; condition ; update statement)
             {
               Statement 1;
               Statement 2;
                       :
               Statement n;
             } 

Working: 
Flow Chart of "for loop"
Flow Chart

  • First the compiler goes to initialization .
  • Then it checks the given condition. 
  • If the condition is incorrect then the compiler will move out of the loop.
  •  If the given condition is correct the the compiler will move to the Statements.
  • After executing all the repetitive statements the compiler will move to the update statements.
  • And after update statement it will go back to the given condition.
  • After checking the condition again it will move to repetitive statements and this process goes again and again until the given condition gets false.
Some example of "for loop"

  1. To print "Hello World!" five times.
    Example 1
    Example 1
    The output is: Hello World!
                                     Hello World!
                                       Hello World!  
                                     Hello World!
                                     Hello World!
  2. To print "Even" when the value of  'i' is even between 0-10.
    Example 1
    Example 1
    The Output is:
    Even Even Even Even Even Even

Things To Remember

  • In for loop the "Initialization", "Condition" and "Update Statement" are separated by semicolon( ; ) .
  • for loop is the only loop in which "Condition" is not compulsory i.e, if the condition is not given then the compiler will not show you an error, but the loop becomes infinite.
  • We can write for( ; ; ) , it will not give you an error.
  • Two semicolon is compulsory to be written in the for loop as "above".

Check out our post on while loop and do..while.



For giving some suggestion please check our "Contact us" page. Also more update related to coding will be added in this Blog later on, so please get attached with this Blog. Thank you for your support and time...

Post a Comment

0 Comments