Jun 24, 2014

C Programming #20: Loop - Introduction

Till now all program that you saw was sequential, one after another statements were executed. Following diagram depicts the sequential program. Note in below program each statement is executed only once.


flow chart - Sequential statements
Looping is one of the very important construct in any Programming language. Loop is type of construct which allows programmer to execute block of statements repeatedly till some condition is true. Following diagram depicts the loop program. Here statements 2 and 3 are looped.
flow chart loop - simple
Above picture fails to tell the details of how many times loop is executed ?

Detailed diagram of the generic loop is as follows.
flow chart - loop detailed

Each loop will have the  following
  1. Condition when the loop has to exit. (if condition)
  2. Loop counter.(initialize_counter)
  3. Body of the loop. (statements)
  4. Change loop counter. (change_condition)

Each point above is labelled to one item in diagram. Flow is as follows first the counter is initialized, then condition is evaluated to check if loop statement has to be executed. If condition is true then statements are executed and later condition is changed (loop counter is changed) and again the condition is evaluated till it becomes false.

Only mandatory thing is 1. We can construct a loop without 2, 3, 4. But it is better to have the construct with all 4 parts, it gives easy understanding to other programmers of what you are doing.

If condition of loop is wrong so that it never becomes false, then we call such loops as infinite loops. Sometimes it might be necessary to construct an infinite loop, while in some cases it should be avoided.

This article gave the idea about a loop , future few articles will cover it in details.


Links

Quiz - Not Yet written !!
Next Article - C Programming #21: Loop - for
Previous Article - C Programming #19: Decision Making - Switch
All Articles - C Programming

No comments :

Post a Comment