Wednesday, February 17, 2016

Loops in C - for, while and do...while Loops

Looping statement saves us from writing same code blocks again and again and executes the specific code block multiple times until some conditions are met. We may have known how many times we need to execute the code block or this decision could be made on the go. Looping has a solution for both cases.

'for' Loop in C

Most commonly used loop statement in C programming language is 'for' loop. Syntax of'for'loop is as given below.
  1. for(initialize expression; test condition; index modification expression)
  2. {
  3. Statement block
  4. }
The 'for'loop generally includes three expressions separated by semicolon (;),
  1. Init expression, which is executed first. You can initialize the loop control variable at this point. This expression is optional.
  2. Test condition is evaluated next. The body of loop is executed only if this condition evaluates to true. If this condition evaluates to false, the control moves to the next line after'for' loop
  3. Index modification expression is executed after body of the loop. You can update the loop control variable at this location. After the execution of index modification expression, loop test condition is evaluated again and this procedure follows until the test condition is evaluated to false

'for' Loop Example in C

Suppose we want to print first 10 integers starting from 0. How we can write this using for loop? What will be the three expressions? Let’s look at the following program.
  1. #include<stdio.h>
  2. void main()
  3. {
  4. int index;
  5. for(index = 0; index < 10; index++)
  6. {
  7. printf("%d\n", index);
  8. }
  9. }
  10.  
  11. Output:
  12.  
  13. 0
  14. 1
  15. 2
  16. 3
  17. 4
  18. 5
  19. 6
  20. 7
  21. 8
  22. 9
First, the initialize expression assigns the value 0 to 'index' variable. It declares that the loop will run with initial value 0. The second expression or test condition checks whether the value of the 'index' is less than 10 or not. The last expression modifies the 'index' variable, i.e. increments its value by 1. So, at start index is 0, the test condition is satisfied and the code block enclosed in braces is executed.

As a result, we get 0 in our screen and then a line feed. After the code block execution is finished, the third expression of 'for' loop gets executed and it increments the value of the 'index'. Again the control flow goes back to 'for' statement. But this time the value of the index does not revert back to 0 as initialization expression is executed only once i.e. at starting time of the loop. Next, the test condition is checked and now, the current value of the 'index', which is 1 satisfies the test expression. So, the 'printf' is executed and index 'index' incremented again. This is repeated until the index value is 10, when the test condition fails and execution will continue from the line following for loop code block, i.e. from the line after the closing brace.
The expressions of loop declaration are are separated by semicolons. All the expressions are not necessary, but the two semicolons are. You can omit one or two expressions or all three expressions and just leave two semicolons in the parenthesis and the code will compile normally and even run too.
The following lines are legal for 'for'loop in C language.
  1. /*
  2. Here the variable 'index' must be initialized before the loop,
  3. since the initialization is omitted from 'for' statement.
  4. If the variable is not initialized prior to execution of 'for' loop,
  5. it would be containing garbage value and result in unexpected output.
  6. */
  7. for(; index < 10; index++)
  8.  
  9. /*
  10. Here, both the initialization and loop control variable modification are omitted.
  11. The value of variable 'index' has to be modified as part of loop body, else the
  12. code will result in unexpected output since the test condition will always evaluate
  13. to a fixed value.
  14. */
  15. for(; index <10; )
  16.  
  17. /*
  18. Here, all the three expressions are omitted, and the loop will continue forever (infinite loop),
  19. unless you use the 'break' keyword explicitly in loop body.
  20. */
  21. for(;;)
As part of 'for'loop you can initialize and modify more than one variable and can contain more than one increment or decrement statement, but they should be separated by comma (,). Consider the example below.
  1. for(i = 0, j = 100; i < 10; i++)
In the above program, both of the variables, 'i' and 'j' would get initialized as part of the initialization statement.

No comments: