C# Programming for Beginners (2015)
Chapter 4: Iteration Statements
While writing a program, you might want to repeatedly execute a particular piece of code. One way is to write that piece of code the number of times you want to repeatedly execute it. However, this approach is extremely unprofessional, resulting in unnecessarily verbose code. To address this problem, iteration statements were introduced. The concept of iteration statements dates back to the earliest programming languages. Their syntax may differ in different languages, but the core concept remains the same; they are meant to execute the code a number of times as specified by developer. Iteration statements are often referred as “loops” since they execute code repeatedly in the form of loops.
C# contains four types of iteration statements. In this chapter, we are going to study each of those types.
Content
· “For” loop
· “While” Loop
· “Do While” Loop
· “Foreach” Loop
1- The “For” Loop
“For” loops allow developers to write a piece of code which executes exactly the number of times as specified by the developer. This loop is perfect to use when you know the exact number of iterations you want your code to go through. For instance, if you want to print your name ten times on the screen, a “for loop” is the solution since you already know that there will be ten iterations of the code which prints your name on the screen. To see a “for loop” in action, have a look at the first example of this chapter.
Example1:
using System;
namespaceMyCSharpApplication
{
class Program
{
static void Main(string[] args)
{
for (inti = 1; i<= 10; i++)
{
Console.WriteLine("Welcome to C#");
}
Console.Read();
}
}
}
Pay attention to the syntax of the “for loop”; it starts with an opening round bracket. Inside the round bracket we have three expressions separated by semicolons. The first expression, “i=1”, is the initialization-clause which means that loop starts with “i=1”. This is evaluated only once. The second expression “i<=10” is the condition-clause, which says that the loop will keep executing until this condition returns true. After evaluating the condition-clause, the body of the loop (which is inside the curly brackets followed by the closing round bracket) executes. The last expression inside the round bracket is “i++”. This is called the iteration clause; each time the body of the loop executes, this clause executes and the control again shifts to the “condition-clause”. The loop keeps executing until the condition-clause returns true. In Example1, the loop starts from “i=1” and keeps executing until “i” is less than or equal to ten, with increments of 1 in each execution. This means that the loop would execute 10 times. Each time, the statement “Welcome to C#” will be printed on the console, so the output would contain “Welcome to C#” printed on screen 10 times.
Output 1:
Welcome to C#
Welcome to C#
Welcome to C#
Welcome to C#
Welcome to C#
Welcome to C#
Welcome to C#
Welcome to C#
Welcome to C#
Welcome to C#
2- “While” Loop
A “while” loop keeps executing until a certain condition becomes true. “While” loop should be used when you do not exactly know that how many times you want to execute a particular piece of code. Rather, you want your loop to execute until a specific condition becomes true or false. In Example2, we will again print “Welcome to C#” on screen ten times, but this time using “while loop”.
Example2:
using System;
namespaceMyCSharpApplication
{
class Program
{
static void Main(string[] args)
{
inti = 1;
while (i<=10)
{
Console.WriteLine("Welcome to C#");
i++;
}
Console.Read();
}
}
}
In Example2, we can see that the “while” loop only has a condition-clause inside the round brackets. This is because the “while” loop doesn’t know how many times it has to execute. All it knows is that, unless the condition-clause becomes true, it has to execute. If you write “true” in the condition-clause, the “while” loop will keep executing forever.
Output2:
Welcome to C#
Welcome to C#
Welcome to C#
Welcome to C#
Welcome to C#
Welcome to C#
Welcome to C#
Welcome to C#
Welcome to C#
Welcome to C#
3- “Do While” Loop
The “do while” loop is similar to the “while” loop in functionality. It depends only upon the condition clause. However, unlike the “while” loop, the “do while” loop executes at least once. This is because the condition clause of the “do while” loop is evaluated at the end of the code block. This way, the code block executes at least once before the condition-clause is evaluated. Example3 demonstrates this process.
Example3:
using System;
namespaceMyCSharpApplication
{
class Program
{
static void Main(string[] args)
{
inti = 1;
do
{
Console.WriteLine("Welcome to C#");
i++;
}
while (i<= 10) ;
Console.Read();
}
}
}
In Example3, you can see that the body of the loop starts with a keyword, “do”, followed by the code block. At the end of the code block you can see the “while” keyword. The condition clause is evaluated here, but before reaching this point of code, the loop has executed at least once. The output will again display “Welcome to C#” on the console, but this time using the “do while” loop.
Output3:
Welcome to C#
Welcome to C#
Welcome to C#
Welcome to C#
Welcome to C#
Welcome to C#
Welcome to C#
Welcome to C#
Welcome to C#
Welcome to C#
4- “Foreach” Loop
In C#, the “foreach” loop iterates over all those objects which can be enumerated. Most of the .NET types which contain list or sets of elements are enumerable. For example, arrays and strings. They can be iterated using a “foreach” loop since they store collections of items. This concept has been demonstrated in Example4.
Example4:
using System;
namespaceMyCSharpApplication
{
class Program
{
static void Main(string[] args)
{
foreach (char c in "Welcome to C#")
{
Console.WriteLine(c);
}
Console.Read();
}
}
}
Pay attention to the body of the “foreach” loop. It starts with a variable, which is “char c” in this case. Here, the type used for the variable is char because we are iterating over the string “Welcome to C#” and each item of this string is of the “char” type. Then we used the keyword “in”. This keyword has to be used whenever you are using a “foreach” loop to iterate over a collection. Finally, we have to enter the name of the collection on which we want to enumerate. The “foreach” loop executes a number of times equal to the items inside the collection. In the code block, we printed each character of the string “Welcome to C#” on a new line.
Output4:
W
e
l
c
o
m
e
t
o
C
#
Exercise 4
Task:
Using a “while” loop, display the sum of all the even numbers between 0 and 100 (inclusive).
Solution:
using System;
usingSystem.Diagnostics;
namespaceMyCSharpApplication
{
class Program
{
static void Main(string[] args)
{
inti = 0;
int sum = 0;
while (i<= 100)
{
if (i % 2 == 0)
{
sum = sum + i;
}
i++;
}
Console.WriteLine("Sum of even numbers between 0 and 100 is:"+sum);
Console.Read();
}
}
}