-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloops.cs
53 lines (49 loc) · 1.25 KB
/
loops.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using System;
public class LoopDemo
{
public static void Main(string[] args)
{
/*
for loop:
use when you know the exact number of iterations
*/
for (int i = 1; i <= 5; i++)
{
Console.WriteLine($"for loop: Iteration #: {i}");
}
/*
while loop:
use when you need to repeat
a block of code as long as
a condition is true
*/
int j = 1;
while (j <= 5)
{
Console.WriteLine($"while loop: Iteration #: {j}");
j++;
}
/*
do-while loop:
use when you need to execute a block of code
at least once, then continue as long as
a condition is true
*/
int k = 1;
do
{
Console.WriteLine($"do-while loop: Iteration #: {k}");
k++;
} while (k <= 5);
/*
foreach loop:
use to iterate through all elements in a collection
without managing an index variable
*/
string[] names = { "John", "Mary", "Peter" };
foreach (string name in names)
{
Console.WriteLine($"foreach loop: {name}");
}
}
}