Monday, February 22, 2016

'break' Statement in C

'break' Statement Example in C

Let’s take a look at an example of how to use 'break' statement with 'for'loop.
  1. #include<stdio.h>
  2. void main()
  3. {
  4. int i;
  5. int number;
  6.  
  7. printf("Enter a number:");
  8. scanf("%d", &number);
  9.  
  10. for(i = 2; i < number; i++)
  11. {
  12. if((number % i) == 0)
  13. {
  14. printf("%d is not prime", number);
  15. break;
  16. }
  17. }
  18. }
The above program will check if the input number is a prime or not and if the number is not prime, program will print stating so. The program starts with index variable 'i' initialized with the value 2 (which gets incremented in each cycle of loop) and checks if the input number is divisible by'i'. If it is divisible by any number other than 1 and itself, then it's not a prime and we don't need to try remaining values. So, after 'printf' statement, the 'break' will take the program control out of 'for' loop.
The program given below prints the non-prime numbers between 5 and 20 using a nested loop. The outer loop iterates from 5 to 20 and the inner loop checks if the number is prime or not. If number is not prime, inner loop prints that and the 'break' statement takes the control out of inner loop. That means, control is taken back to the outer loop, which begin to process with the next value for loop variable 'i'
  1. #include<stdio.h>
  2. void main()
  3. {
  4. int i, j;
  5.  
  6. for(i = 5; i <= 20; i++)
  7. {
  8. for(j = 2; j < i; j++)
  9. {
  10. if((i % j) == 0)
  11. {
  12. printf("%d\n", i);
  13. break;
  14. }
  15. }
  16. }
  17. }

No comments: