
Branching Statements
29 March, 2023
0
0
0
Contributors
Branching Statements
In the Dart programming language, branching statements are used to alter the flow of execution in a program. There are three types of branching statements: break
, continue
, and return
.
break
statement
The break
statement is used to exit a loop or a switch statement and move on to the next line of code. It can be used to exit a for
, while
, do-while
, or switch
statement.
Here is an example of a break
statement being used in a for
loop:
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
print(i);
}
This code would output the numbers 1 through 4 to the console, and then exit the loop.
continue
statement
The continue
statement is used to skip the current iteration of a loop and move on to the next iteration. It can be used in a for
, while
, or do-while
loop.
Here is an example of a continue
statement being used in a for
loop:
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue;
}
print(i);
}
This code would output the odd numbers from 1 to 10 to the console.
return
statement
The return
statement is used to exit a function and return a value. It can be used in any function that returns a value.
Here is an example of a return
statement being used in a function:
int sum(int a, int b) {
return a + b;
}
int result = sum(1, 2);
print(result); // prints 3