Comparison between "for, while and do-while" loops



comparison of loops

Example 1: Write a program to print p=4n & q=4-n table by using for statement.


Output:

Enter the value of n10
------------------------------------------
(4 to power n) (n) (4 to power -n)
------------------------------------------
1 0 1.0000000000000
4 1 0.2500000000000
16 2 0.0625000000000
64 3 0.0156250000000
256 4 0.0039062500000
1024 5 0.0009765625000
4096 6 0.0002441406250
16384 7 0.0000610351562
65536 8 0.0000152587891
262144 9 0.0000038146973
1048576 10 0.0000009536743
------------------------------------------

This Program evaluates the value p=4n & q=4-n. Note that we have declared p as a long int and q as a double.



`
Key points
  • for loop is entry controlled loop.
  • while loop is entry controlled loop.
  • do-while is exit controlled loop.
  • Don't use semicolon at the end of for statement, otherwise loop will terminate.


Do You Know?