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.
- while(expression)
- {
- statement block
- }
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'.
- while(1) {
- statement block
- }
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
- #include<stdio.h>
- void main()
- {
- int index = 0;
- while(index < 10)
- {
- printf("%d\n", index++);
- }
- }
- Output:
- 0
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 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:
Post a Comment