C Language : Chapter 3 : While loop

 Loops

If something is worth doing, it's worth doing more than once.

The versatility of computer lies in its ability to perform a set of instructions repeatedly.

This involves repeating some portion of the program either a specific number of times or until a condition is being satisfied. This is done by loop control instructions.

There are three methods by which we can repeat some portion of the program.

  1. while
  2. do while
  3. for

Syntax of while loop

initialize loop counter;

while (test condition)
{
execute statement;
increment counter;
}


@program- Flow chart





Loop Counter / Index variable - Count variable sometimes called index variable or loop counter.
in above program, variable count is loop counter or index variable.
  1. It is not necessary that the loop counter should always be an integer value. It can be real number as well.
  2. Instead of increment the loop counter we can decrement it as well.

Other conditions which can be tested in while loops are:
while (i<=10)
while (i>=10 && j>=15)
while(j>10 && (b<15||c<20))

while (i<=10)
i=i+1;

is same as 
while(i<1=10)
{
i=i+1;
}

As a rule, while loop must test a condition that will eventually become false, otherwise it run indefinitely and becomes infinite loop.




Another example of infinite loop.
Allowed range for integer constant is -32768 to 32767, even if the counter variable increases to 32769, eventually it will fall under the range of -32768 to 32767 therefore condition will never becomes non-zero.

i++;
i=i+1;

i--;
i=i-1;

Compound assignment operators.

*
/
%
+
-

i+=1;    
i-=1;
i/=1;
i*/=1;
i%=1;

Pre-increment operator  - first increase the counter and then test the condition
++i;

Post Increment Operator- first test the condition and then increase the counter.
i++;








Comments

Popular posts from this blog

C language : Chapter 2

C Language: Chapter 4 The case control structure.