Csharp/C Sharp/Language Basics/Break
Версия от 15:31, 26 мая 2010; (обсуждение)
Find the smallest factor of a value
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Find the smallest factor of a value.
using System;
public class FindSmallestFactor {
public static void Main() {
int factor = 1;
int num = 1000;
for(int i=2; i < num/2; i++) {
if((num%i) == 0) {
factor = i;
break; // stop loop when factor is found
}
}
Console.WriteLine("Smallest factor is " + factor);
}
}
the break statement
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
Example4_13.cs illustrates the use of
the break statement
*/
public class Example4_13
{
public static void Main()
{
int total = 0;
for (int counter = 1; counter <= 10; counter++)
{
System.Console.WriteLine("counter = " + counter);
total += counter;
if (counter == 5)
{
System.Console.WriteLine("break from loop");
break;
}
}
System.Console.WriteLine("total = " + total);
}
}
Using break with nested loops
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Using break with nested loops.
using System;
public class BreakNested {
public static void Main() {
for(int i=0; i<3; i++) {
Console.WriteLine("Outer loop count: " + i);
Console.Write(" Inner loop count: ");
int t = 0;
while(t < 100) {
if(t == 10) break; // terminate loop if t is 10
Console.Write(t + " ");
t++;
}
Console.WriteLine();
}
Console.WriteLine("Loops complete.");
}
}