While loop
It is often the case in programming that you want to repeat something a fixed number of time. Perhaps you want to calculate gross series of ten different persons, or you want to convert temperatures from centigrade to Fahrenheit for 15 different cities. The while loop is ideally suited for this.
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhrGIOskOcANw_VO_LyMehtSSF4vdIK8nts7HkWpvz2fuAdJjQhgQm8gr3pyiS3mF30qjoP2U8BvDlQ3r4bH7e2G-H3EfNaiAjA2UqNUgPOC1DoskMLC0GveR6abWqrZgVJ0p_xhL75G6Dg/w500-h424/while+loop.png)
General form of WHILE LOOP statement:
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhvuKCmjxaJcUVNpxeS6iNjelCyqjmgYo_Kpo-cOg7gVrALrFDm_woYrESUBFh-d7hPKCIvAEV5oRwXw-YMXPbrIlZ6Nj2Oc-sTdKrMwIFIxrD33qcSg4s82HIH5P7BFIklPNe9jCVwxZQe/w500-h400/while.png)
Note
the following points about WHILE…..
Ø
The
statement within the while loop will keep getting executed till the condition
being tested remain true. When the condition become false, the control passes
to the first statement that flows the body of the WHILE LOOP.
Ø
In
place of the condition, there can be any other valid expression. So long as the
expression evaluates to a non-zero value, the statements within the loop would
get executed.
Ø
The
condition being tested may use relational or logical operators as show in above
example: while(i<=10)
while(i>=10&&j<=15)
while(i>10&&(b<15||c<20))
Ø
The
statement within the loop may consist a single line or a block of statement. In
the first case, the braces are optional.
Ø
Almost
always, the while must test a condition that will eventually become false, otherwise
the loop would keep getting executed forever, indefinitely.
Ø
Instead
of incrementing a loop counter, we can decrement it and still manage to get the
body of the loop executed repeatedly.
Ø
It
is not necessary that a loop counter must only be an int. it can even be a
float.
Ø
Even
floating point counters can be decremented. Once again the increment and
decrement could be any value, not necessarily 1.
Comments
Post a Comment