How is the break statement different from continue statement? Explain with example
Answers
Answer:
A break can appear in both switch and loop (for, while, do) statements.
The break statement can be used in both switch and loop statements.
A continue can appear only in loop (for, while, do) statements.
The continue statement can appear only in loops. You will get an error if this appears in switch statement.
Explanation:
Example-
Break-
int trim(char s[])
{
int n;
for (n = strlen(s)-1; n >= 0; n--)
if (s[n] != ' ' && s[n] != '\t' && s[n] != '\n')
break;
s[n+1] = '\0';
return n;
}
Continue-
#include <stdio.h>
int main()
{
int a[10] = {-1, 2, -3, 4, -5, 6, -7, 8, -9, 10};
int i, sum = 0;
for (i = 0; i < 10; i++)
{
if (a[i] < 0) /* skip negative elements */
continue;
sum += a[i]; /* sum positive elements */
}
printf("Sum of positive elements: %d\n", sum);
}