Thursday, February 18, 2016

'while' Loop in C

After 'for' loop, let's look at 'while' loop in C language. Unlike 'for' loop, 'while' loop contains only a single expression and it is used as the test condition. The initialization and modification expressions of 'for' loop is omitted in 'while' loop. The general syntax of'while'loop is given below.
  1. while(expression)
  2. {
  3. statement block
  4. }
If the 'expression' evaluates to true, i.e. it evaluates to a non-zero value, code in the 'statement block' gets executed. And after execution of 'statement block', the expression is evaluated again to check it's truth value and this process continues until the expression evaluates to false.
So if you place a non-zero value as the 'expression', 'while' loop executes infinitely unless you have an explicit 'break'statement as part of 'statement block'.
  1. while(1) {
  2. statement block
  3. }
In the above code snippet, the 'statement block' gets executed infinitely.

'while' Loop Example in C

We can write our program to print first 10 numbers using 'while'loop as given below
  1. #include<stdio.h>
  2. void main()
  3. {
  4. int index = 0;
  5. while(index < 10)
  6. {
  7. printf("%d\n", index++);
  8. }
  9. }
  10.  
  11. Output:
  12. 0
  13. 1
  14. 2
  15. 3
  16. 4
  17. 5
  18. 6
  19. 7
  20. 8
  21. 9
Here, the index is initialized during declaration and it is incremented inside 'while' code block. The 'while' statement contains only test condition (index < 10). Note that, here the increment is post-increment. So, the 'printf' will print the value starting from 0 up to 9 asindex++ will return the present value of index and then increment it by 1.
In case of 'while' loop and 'for' loop if you omit the braces, then only the immediate statement will be considered as the loop body.

No comments: