1. While Loop
1. While loop checks the condition first.
2. If the condition is true, statements with in the loop are executed.
3. This process is repeated as long as the condition evaluates to true.
2. Do While Loop
1. A do loop checks its condition at the end of the loop
2. This means that the do loop is guaranteed to execute at least one time
3. Do loops are used to present a menu to the user
3. For Loop
initialization, condition check and modifying the variable are at one place
4. For Each Loop
Be used to iterate through the items in a collection.
ex) foreach loop can be used with arrays or collections such as ArrayList, HashTable and Generics
========================================
using System;
class Program
{
static void Main()
{
string UserChoice = string.Empty;
do
{
Console.WriteLine("Please enter your target?");
int UserTarget = int.Parse(Console.ReadLine());
int Start = 0;
while (Start <= UserTarget)
{
Console.Write(Start + " ");
Start += 2;
}
do
{
Console.WriteLine("Do you want to continue - Yes or No?");
UserChoice = Console.ReadLine().ToUpper();
if (UserChoice != "YES" && UserChoice != "NO")
{
Console.WriteLine("Invalid Choice, please say Yes or No");
}
} while (UserChoice != "YES" && UserChoice != "NO");
} while (UserChoice == "YES");
}
}
=====================================
using System;
class Program
{
static void Main()
{
int TotalCoffeeCost = 0;
string UserDecision = string.Empty;
do
{
int UserChoice = -1;
do
{
Console.WriteLine("Please Select Your coffee size : 1 - Small, 2 - Medium, 3 - Large");
UserChoice = int.Parse(Console.ReadLine());
switch (UserChoice)
{
case 1:
TotalCoffeeCost += 1;
break;
case 2:
TotalCoffeeCost += 2;
break;
case 3:
TotalCoffeeCost += 3;
break;
default:
Console.WriteLine("Your choice {0} is invalid", UserChoice);
break;
}
} while (UserChoice != 1 && UserChoice != 2 && UserChoice != 3);
do
{
Console.WriteLine("Do you want to buy another coffee - Yes or No?");
UserDecision = Console.ReadLine().ToUpper();
if(UserDecision != "YES" && UserDecision != "NO")
{
Console.WriteLine("Your chois {0} is invalid. Please try agin...", UserDecision);
}
} while (UserDecision != "YES" && UserDecision != "NO");
} while (UserDecision.ToUpper() != "NO");
Console.WriteLine("Thank you for shopping with us");
Console.WriteLine("Bill Amount = {0}", TotalCoffeeCost);
}
}
==========================================
using System;
class Program
{
static void Main()
{
int[] Numbers = new int[3];
Numbers[0] = 101;
Numbers[1] = 102;
Numbers[2] = 103;
foreach (int k in Numbers)
{
Console.WriteLine(Numbers[k]);
}
for (int j = 0; j < Numbers.Length; j++)
{
Console.WriteLine(Numbers[j]);
}
int i = 0;
while (i < Numbers.Length)
{
Console.WriteLine(Numbers[i]);
i++;
}
}
}