When, Why and How to use break statement in C

Notes:

When, Why and How to use break statement in C Programming language:

EX: Linear search algorithm in C:
- Program to search an element in an array using linear search algorithm in c with step by step explanation. It is the best example for understanding when to use break statement.

When to use break statement?
- Break statement is used to terminate the loop manually; so that we can write efficient codes

Linear search without break statement:
- Searching for a given item in the list
Ex:
int numbers[5] = {10,20,30,40,50};
int item = 20;
int i = 0;
char found = 'n';

for(i=0;i<5;i++)
{
if(numbers[i]==item)
{
found = 'y';
}
}

printf("%s\n",(found == 'y') ? "Item found": "Item not found");

Linear search with break statement:
- Searching for a given item in the list
Ex:
int numbers[5] = {10,20,30,40,50};
int item = 20;
char found = 'n';
int i = 0;
for(i=0;i<5;i++)
{
if(numbers[i]==item)
{
found = 'y';
break;
}
}

printf("%s\n",(found == 'y') ? "Item found": "Item not found");