Tuesday, February 23, 2016

'continue' Statement in C

 The 'continue' statement does not terminate the loop. It just skips the remaining statements in the body of the loop for the current pass and then next pass is started. To use 'continue', you just have to include the keyword'continue' followed by a semicolon.

Example of 'Continue' Statement in C

The below example has an array of integers as input and it iterates over each number checking if each number of negative or positive. If it's positive, the program calculates the square of the number, else it goes to the next number.
  1. #include <stdio.h>
  2.  
  3. int main(void) {
  4. int a[5] = {1, -2, 3, -4, 5};
  5. int i;
  6. for (i = 0; i < 5; i++ ) {
  7. if (a[i] < 0)
  8. continue;
  9. printf("%d * %d = %d\n", a[i], a[i], a[i] * a[i]);
  10. }
  11. return 0;
  12. }
  13.  
  14. Output:
  15. 1 * 1 = 1
  16. 3 * 3 = 9
  17. 5 * 5 = 25
The program iterates over each number and when the number is less than 0, the 'continue'statement is executed and control goes to the next iteration of loop.

'goto' Statement

The 'goto' statement is used to transfer the control of execution of the program to another part of the program where a particular label is defined. The 'goto' statement is used alongside a label and has the general form goto label;
The label is the identifier which defines where the control should go on the execution of 'goto'statement. The target statement block must be labelled like - label: statement /statement block

Example of 'goto' Statement in C

Take look at the following simple program.
  1. #include<stdio.h>
  2. void main()
  3. {
  4. int i;
  5. for(i = 0; i < 10; i++)
  6. {
  7. if(i == 5)
  8. {
  9. goto out;
  10. }
  11. printf("%d\n", i);
  12. }
  13.  
  14. out:
  15. printf("I am tired now\n");
  16. }
This program will print the values 0 to 4 and when value of 'i' reaches 5, execution jumps to the statement with label 'out'. Then it will just print the string "I am tired now" and will exit from the program.
One advantage of 'goto' statement is that unlike 'break''goto' can exit from all nested loops. Also, if you use 'goto' correctly, you can write a block that loops multiple times without using forwhile or do...while loop. Following piece of code is an example of that.
  1. int i = 0;
  2. a:
  3. if(i < 10)
  4. {
  5. printf("%d\n", i);
  6. i++;
  7. goto a;
  8. }

No comments: