آموزش برنامه نویسی با سی شارپ C# - قسمت 9 – حَلقه (Loop)
زمان مطالعه: 2 دقیقه
زمان ویدیو:
15m44s
لینک یوتیوب
لینک آپارات

لوپ یا حلقه چیه؟
حلقه While
while (condition)
{
// do something ...
}
int totalHits = 0;
while (totalHits < 100)
{
TakeDamage();
totalHits++;
}
حلقه do while
int totalHits = 0;
do {
TakeDamage();
totalHits++;
}
while(totalHits < 100);
حلقه for
for (int totalHits = 0; totalHits < 100; totalHits++)
{
TakeDamage();
}
کیورد break
while (true)
{
TakeDamage();
if (health < 10)
{
break;
}
}
کیورد continue
int totalLevels = 10;
int magicLevel1 = 3;
int magicLevel2 = 6;
void CreateLevel(int level)
{
Console.WriteLine($"Level {level} created!");
}
for (int levelNumber = 1; levelNumber <= totalLevels; levelNumber++)
{
if (levelNumber == magicLevel1 || levelNumber == magicLevel2)
{
continue;
}
CreateLevel(levelNumber);
}
حلقه بی نهایت (Infinite Loop) با for
for (; ; )
{
Console.WriteLine("Boom!");
TakeDamage();
if (isDead)
{
break;
}
}
Console.WriteLine("Loop finished");
حلقه های تو در تو - Nested Loops
int rows = 6;
int columns = 6;
for (int row = 0; row < rows; row++)
{
for (int column = 0; column < columns; column++)
{
Console.Write($" # ");
}
Console.WriteLine();
}
int rows = 6;
int columns = 6;
for (int row = 0; row < rows; row++)
{
for (int column = 0; column < columns; column++)
{
Console.Write($" ({column}, {row}) ");
}
Console.WriteLine();
}
int rows = 6;
int columns = 6;
for (int row = 0; row < rows; row++)
{
for (int column = 0; column < columns; column++)
{
if (row == 3 && column == 1 )
{
Console.Write($" ###### ");
continue;
}
Console.Write($" ({column}, {row}) ");
}
Console.WriteLine();
}
int rows = 6;
int columns = 6;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
Console.Write($" ({j}, {i}) ");
}
Console.WriteLine();
}