Home > Backend Development > C#.Net Tutorial > How to control for loop using break and continue statements in C#?

How to control for loop using break and continue statements in C#?

WBOY
Release: 2023-08-30 21:17:02
forward
1191 people have browsed it

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;
}
Copy after login

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;
}
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template