Home >Backend Development >C#.Net Tutorial >How to control for loop using break and continue statements in C#?
The Break statement terminates the loop. To use this in a for loop, you can get the user's input every time and display the output when the user enters a negative number. Then display the output and exit using the break statement -
for(i=1; i <= 10; ++i) { myVal = Console.Read(); val = Convert.ToInt32(myVal); // loop terminates if the number is negative if(val < 0) { break; } sum += val; }
Similarly, the continue statement in the for loop also works, but does not display negative numbers. The continue statement causes the loop to skip the rest of its body and retest its condition immediately before repeating -
for(i=1; i <= 10; ++i) { myVal = Console.Read(); val = Convert.ToInt32(myVal); // loop terminates if the number is negative and goes to next iteration if(val < 0) { continue; } sum += val; }
The above is the detailed content of How to control for loop using break and continue statements in C#?. For more information, please follow other related articles on the PHP Chinese website!