while (expression) {
statements
}
คำสั่ง While loop
รูปแบบ
1
3
5
7
9
ตัวอย่าง คำสั่งวนซ้ำทำดอกจันเรียงลงตามลำดับ
using System; namespace while_loop { class Program { static void Main(string[] args) { int loop = 1; while (loop <= 10) { int i = 0; while (i < loop) { Console.Write("*"); i += 1; } Console.WriteLine(); loop += 1; } Console.ReadLine(); } } }
ผลการรัน
*
**
***
****
*****
******
*******
********
*********
**********
คำสั่ง Do-while loop
do-while loop นั้นคล้ายกับ while loop ซึ่งมันสามารถใช้ทดแทนกันได้ แต่ do-while loop จะต้องทำงานอย่างน้อย 1 รอบ
รูปแบบ
do {
statements
} while (expression) ;
ตัวอย่างรับค่าเพื่อเช็คค่า
using System; namespace do_while_loop { class Program { static void Main(string[] args) { int number,i=0; do { Console.Write("Enter Number Random : "); int.TryParse(Console.ReadLine(),out number); i += 1; } while (number != 5) ;// เงื่อนไขเป็นจริง จะกลับไป do คือรับค่า number // เป็นเท็จก็ออกจาก loop do while Console.WriteLine("Random Ok loop {0}",i); Console.ReadLine(); } } }
ผลการรัน
Enter Number Random : 4
Enter Number Random : 6
Enter Number Random : 3
Enter Number Random : 2
Enter Number Random : 12
Enter Number Random : 5
Random Ok loop 6
คำสั่ง For loop
เป็นลูปที่ใช้ทำซ้ำคำสั่งหรือชุดของคำสั่งเป็นจำนวนรอบที่แน่นอน
รูปแบบ
for (initialize; condition; iterator) {
statements
}
ตัวอย่างการใช้งานจริง
using System; namespace for_loop { class Program { static void Main(string[] args) { int j=1; for (int i = 0; i < 5; i++) { Console.WriteLine("loop = {0} ", i+1); } for (; j < 6; ) { Console.WriteLine(j); j++; } Console.ReadLine(); } } }
ผลการรัน
loop = 1
loop = 2
loop = 3
loop = 4
loop = 5
1
2
3
4
5
คำสั่ง foreach loop
จะใช้สำหรับวนซ้ำค่าในอาเรย์ ที่ทราบหรือไม่ทราบขนาด โดยลูปจะเริ่มอ่านค่าจากสมาชิกตัวแรกในอาเรย์ ไปจนถึงตัวสุดท้าย
ตัวอย่าง
using System; namespace foreach_loop { class Program { static void Main(string[] args) { int[] numbers = { 1, 2, 3, 4}; foreach (int i in numbers)// ค่าใน number[] เก็บไว้ในตัวแปร i แล้วก็แสดงผล { Console.WriteLine(i); } Console.ReadLine(); } } }
ผลการรัน
1
2
3
4
คำสั่ง break
คำสั่ง break เพื่อบังคับให้ลูปสิ้นสุดการทำงานในทันที
ตัวอย่าง
using System; namespace break_loop { class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) { if (i==5) { break; } Console.WriteLine(i); } Console.ReadLine(); } } }
ผลการรัน
0
1
2
3
4
คำสั่ง continue
จะข้ามการทำงานคำสั่งทั้งหมดภายในลูปหลังจากคำสั่ง continue และไปเริ่มต้นรอบใหม่
ตัวอย่าง
using System; namespace @continue { class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) { if (i % 2 == 0) { continue; } Console.WriteLine(i); } Console.ReadLine(); } } }
ผลการรัน