রবিবার, ১৯ সেপ্টেম্বর, ২০১০

15. Use break to exit a loop

The break statement allows you to exit a loop from any point within its body, bypassing its normal termination expression. If you use a break statement under a loop and when the program read the break statement then the loop is immediately stopped, and program control resumes at the next statement following the loop. For example, this loop prints only the numbers 1 to 10.


#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int i;
  for (i=1;i<100;i++)
  {
  printf("%d",i);
  if(i==10);
  break;                    /* exit the loop */
  }
}


The break statement can be used with all three of C'a loops.
   You can have as many break statements within a loops as you desire. However, since too many exit points from a loop tend to destructure your code, it is generally best to use the break for special purposes, not as your normal loop exit.


Here a another example for using break.


#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,x=0;
for(i=0;i<5;++i)
  {
  x+=(i+j-1);
  printf("%d",x);
  break;
  }
printf("\nx=%d",x);
}


(post by arnob)

কোন মন্তব্য নেই:

একটি মন্তব্য পোস্ট করুন