Lesson 6 - For and while loops in C# .NET
In the previous exercise, Solved tasks for C# .NET lesson 5, we've practiced our knowledge from previous lessons.
Lesson highlights
Are you looking for a quick reference on for
and while
loops in C# .NET instead of a thorough-full lesson? Here
it is:
Using a for
loop to execute
code 3
times:
{CSHARP_CONSOLE}
for (int i=0; i < 3; i++) // runs 3 times in total
{
Console.WriteLine("Knock");
}
Console.WriteLine("Penny!");
Console.ReadKey();
{/CSHARP_CONSOLE}
Accessing the loop control variable each iteration:
{CSHARP_CONSOLE}
for (int i = 1; i <= 10; i++)
Console.Write("{0} ", i); // prints the current value of the loop control variable
Console.ReadKey();
{/CSHARP_CONSOLE}
Nesting loops to work with tabular data:
{CSHARP_CONSOLE}
Console.WriteLine("Here's a simple multiplication table using nested loops:");
for (int j = 1; j <= 10; j++)
{
for (int i = 1; i <= 10; i++)
Console.Write("{0} ", i * j);
Console.WriteLine();
}
Console.ReadKey();
{/CSHARP_CONSOLE}
Using a while
loop when we don't know
how many times the code is going to repeat:
Console.WriteLine("Welcome to our calculator"); string goOn = "yes"; while (goOn == "yes") { Console.WriteLine("Enter the first number:"); double a = double.Parse(Console.ReadLine()); Console.WriteLine("Enter the second number:"); double b = double.Parse(Console.ReadLine()); Console.WriteLine("Choose one of the following operations:"); Console.WriteLine("1 - addition"); Console.WriteLine("2 - subtraction"); Console.WriteLine("3 - multiplication"); Console.WriteLine("4 - division"); int option = int.Parse(Console.ReadLine()); double result = 0; switch (option) { case 1: result = a + b; break; case 2: result = a - b; break; case 3: result = a * b; break; case 4: result = a / b; break; } if ((option > 0) && (option < 5)) Console.WriteLine("Result: {0}", result); else Console.WriteLine("Invalid option"); Console.WriteLine("Would you like to make another calculation? [yes/no]"); goOn = Console.ReadLine(); } Console.WriteLine("Thank you for using our calculator. Press any key to end the program."); Console.ReadKey();
Would you like to learn more? A complete lesson on this topic follows.
In the previous tutorial, Solved tasks for C# .NET lesson 5, we learned about conditions in C# .NET. In today's lesson, we're going to introduce you all to loops. After today's lesson, we'll have almost covered all of the basic constructs to be able to create reasonable applications.
Loops
The word loop suggests that something is going to repeat. When we want a program to do something 100 times, certainly we'll not write the same code 100x. Instead, we'll put it in a loop. There are several types of loops. We'll explain how to use them, and of course, make practical examples.
The for
loop
This loop has a determined fixed number of steps and contains a control variable, typically an integer, which changes values gradually during the loop. The for loop syntax is the following:
for (variable; condition; command)
variable
is the control variable which is set to an initial value (usually0
, because in programming, everything starts from zero, never from one). For example:int i = 0
. Of course, we could also create the variable somewhere above it, and we wouldn't have to write theint
keyword, but usually we declareint i
there.condition
is the condition for executing the next step of the loop. Once it becomes false, the whole loop is terminated. The condition may be for examplei < 10
.command
tells us what will happen to our variable on every step i.e. whether it should be increased or decreased. We use special++
and--
operators for this. Of course, you can use these operators outside the loop as well, they decrease or increase a variable by1
.
Let's create a simple example, most of us certainly know Sheldon from The Big Bang Theory. For those who don't, we'll simulate a situation where a guy knocks on his neighbor's door. He always knocks 3 times and then yells: "Penny!". Our code, without a loop, would look like this:
{CSHARP_CONSOLE}
Console.WriteLine("Knock");
Console.WriteLine("Knock");
Console.WriteLine("Knock");
Console.WriteLine("Penny!");
Console.ReadKey();
{/CSHARP_CONSOLE}
However, using loops, we no longer have to copy the same code over and over:
{CSHARP_CONSOLE}
for (int i=0; i < 3; i++)
{
Console.WriteLine("Knock");
}
Console.WriteLine("Penny!");
Console.ReadKey();
{/CSHARP_CONSOLE}
Console application
Knock
Knock
Knock
Penny!
The loop will run through 3 times. At the very beginning, i
is
set to zero, the loop then prints "Knock" and increases i
by one.
It continues in the same way with values one and two. Once i
hits
three, the condition i < 3
is no longer true and the loop
terminates. Loops have the same rules for omitting curly brackets as conditions.
In this case, they may be omitted since the loop contains only one command. Now,
we can simply change value 3 to 10 in the loop declaration. The command will
execute 10x without writing anything extra. Surely you can see that loops are a
very powerful tool.
Now let's put the variable incrementation to use. We'll print the numbers
from one to ten. Since we don't want our output to be on separate lines, we'll
use the Write()
method rather than WriteLine()
.
{CSHARP_CONSOLE}
for (int i = 1; i <= 10; i++)
Console.Write("{0} ", i);
Console.ReadKey();
{/CSHARP_CONSOLE}
We can see that the control variable has a different value after each
iteration (iteration is one step of the loop). Notice that this time, the loop
doesn't start from zero because we want the initial value to be 1
and the last one to be 10
. Just keep in mind that in programming,
almost everything starts from zero, we'll find out why later.
Now let's print a simple multiplication table that contains multiples of
numbers from 1
to 10
. All we need to do is to declare
a loop from 1 to 10 and multiply the control variable with the current
multiplier. It might look like this:
{CSHARP_CONSOLE}
Console.WriteLine("Here's a simple multiplication table using loops:");
for (int i = 1; i <= 10; i++)
Console.Write("{0} ", i);
Console.WriteLine();
for (int i = 1; i <= 10; i++)
Console.Write("{0} ", i * 2);
Console.WriteLine();
for (int i = 1; i <= 10; i++)
Console.Write("{0} ", i * 3);
Console.WriteLine();
for (int i = 1; i <= 10; i++)
Console.Write("{0} ", i * 4);
Console.WriteLine();
for (int i = 1; i <= 10; i++)
Console.Write("{0} ", i * 5);
Console.WriteLine();
for (int i = 1; i <= 10; i++)
Console.Write("{0} ", i * 6);
Console.WriteLine();
for (int i = 1; i <= 10; i++)
Console.Write("{0} ", i * 7);
Console.WriteLine();
for (int i = 1; i <= 10; i++)
Console.Write("{0} ", i * 8);
Console.WriteLine();
for (int i = 1; i <= 10; i++)
Console.Write("{0} ", i * 9);
Console.WriteLine();
for (int i = 1; i <= 10; i++)
Console.Write("{0} ", i * 10);
Console.ReadKey();
{/CSHARP_CONSOLE}
The result:
Console application
Simple multiplication table using loops:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
The program works nicely, but we still wrote a lot. Honestly, we could break it down even more since all it does is repeat 10 times while increasing the multiplier. What we'll do is nest the loops (put one inside the other):
{CSHARP_CONSOLE}
Console.WriteLine("Here's a simple multiplication table using nested loops:");
for (int j = 1; j <= 10; j++)
{
for (int i = 1; i <= 10; i++)
Console.Write("{0} ", i * j);
Console.WriteLine();
}
Console.ReadKey();
{/CSHARP_CONSOLE}
Makes a big difference, doesn't it? Obviously, we can't use i
in
both loops since they are nested and would count as a re-declaration. The
variable j
of the outer loop gains the values from 1
to 10
. During each iteration of the loop, another inner loop with
the variable i
is executed. We already know that it'll write the
multiples, in this case, it multiplies by the variable j
. After
each time the inner loop terminates it's necessary to break the line, it's done
by Console.WriteLine()
. You can try to align printed rows by using
the PadLeft()
method, so the numbers will be printed nicely in
columns.
Let's make one more program where we'll practice working with an outer variable. The application will be able to calculate an arbitrary power of an arbitrary number:
{CSHARP_CONSOLE}
Console.WriteLine("Exponent calculator");
Console.WriteLine("===================");
Console.WriteLine("Enter the base: ");
int a = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the exponent: ");
int n = int.Parse(Console.ReadLine());
int result = a;
for (int i = 0; i < (n - 1); i++)
result = result * a;
Console.WriteLine("Result: {0}", result);
Console.WriteLine("Thank you for using our exponent calculator");
Console.ReadKey();
{/CSHARP_CONSOLE}
I'm sure we all know how powers (exponents) work. But just to be sure, let me
remind that, e.g. 23 = 2 * 2 * 2. So, we compute an by
multiplying the number a
by the number a
for n-1
times. Of course, the result must be stored in a variable. Initially, it'll have
a value of a
and this value will be gradually multiplying during
the loop. We can see that our result
variable in the loop body is
normally accessible. If, however, we create a variable in a loop body, this
variable will be no longer accessible after the loop terminates.
Console application
Exponent calculator
=========================
Enter the base:
2
Enter the exponent:
3
Result: 8
Thank you for using our exponent calculator
Now, we know what some practical uses of the for loop are. Remember that it has a fixed amount of iterations. We shouldn't modify the control variable from inside the loop since the program could get stuck in an infinite loop. Here's the last example of what you should not do:
{CSHARP_CONSOLE}
// this code is wrong
for (int i = 1; i <= 10; i++)
i = 1;
Console.ReadKey();
{/CSHARP_CONSOLE}
Ouch, we can see that the program is stuck. The loop always increments the
variable i
, but it is always set back to 1
. Meaning
that it never reaches values > 10
and the loop never ends. Close
the program window or use the Stop button in the Visual Studio toolbar.
The while
loop
The while
loop works differently, it simply repeats the commands
in a block while a condition is true. The syntax of the loop is the
following:
while (condition) { // commands }
If you realized that the for
loop can be simulated using the
while
loop, you are right The
for
loop is actually a special case of the
while
loop. However, the while
loop is used for
slightly different things. Typically, we call some method returning a logical
true
/false value
, in the while loop parentheses. We
could rewrite the original for
-loop example to use the
while
loop instead:
{CSHARP_CONSOLE}
int i = 1;
while (i <= 10)
{
Console.Write("{0} ", i);
i++;
}
Console.ReadKey();
{/CSHARP_CONSOLE}
But this is not an ideal example of using the while
loop. Let's
take our calculator from previous lessons and improve it a little bit. We'll add
an ability to enter more math problems. The program will not end immediately,
but it'll ask the user whether they wish to calculate another math problem.
Let's remind the original version of the code (this is the version with
switch
, but feel free to use the if-else version, it depends on
you):
{CSHARP_CONSOLE}
Console.WriteLine("Welcome to our calculator");
Console.WriteLine("Enter the first number:");
double a = double.Parse(Console.ReadLine());
Console.WriteLine("Enter the second number:");
double b = double.Parse(Console.ReadLine());
Console.WriteLine("Choose one of the following operations:");
Console.WriteLine("1 - addition");
Console.WriteLine("2 - subtraction");
Console.WriteLine("3 - multiplication");
Console.WriteLine("4 - division");
int option = int.Parse(Console.ReadLine());
double result = 0;
switch (option)
{
case 1:
result = a + b;
break;
case 2:
result = a - b;
break;
case 3:
result = a * b;
break;
case 4:
result = a / b;
break;
}
if ((option > 0) && (option < 5))
Console.WriteLine("Result: {0}", result);
else
Console.WriteLine("Invalid option");
Console.WriteLine("Thank you for using our calculator. Press any key to end the program.");
Console.ReadKey();
{/CSHARP_CONSOLE}
Now, we'll put almost all the code into a while
loop. Our
condition will be that the user entered "yes", so we'll check the content of a
goOn
variable. This variable will be set to "yes" at the beginning
since the program has to begin somehow, then we'll assign the user's input to
it:
Console.WriteLine("Welcome to our calculator"); string goOn = "yes"; while (goOn == "yes") { Console.WriteLine("Enter the first number:"); double a = double.Parse(Console.ReadLine()); Console.WriteLine("Enter the second number:"); double b = double.Parse(Console.ReadLine()); Console.WriteLine("Choose one of the following operations:"); Console.WriteLine("1 - addition"); Console.WriteLine("2 - subtraction"); Console.WriteLine("3 - multiplication"); Console.WriteLine("4 - division"); int option = int.Parse(Console.ReadLine()); double result = 0; switch (option) { case 1: result = a + b; break; case 2: result = a - b; break; case 3: result = a * b; break; case 4: result = a / b; break; } if ((option > 0) && (option < 5)) Console.WriteLine("Result: {0}", result); else Console.WriteLine("Invalid option"); Console.WriteLine("Would you like to make another calculation? [yes/no]"); goOn = Console.ReadLine(); } Console.WriteLine("Thank you for using our calculator. Press any key to end the program."); Console.ReadKey();
The result:
Console application
Welcome to our calculator
Enter the first number:
12
Enter the second number:
128
Choose one of the following operations:
1 - addition
2 - subtraction
3 - multiplication
4 - division
1
Result: 140
Would you like to make another calculation? [yes/no]
yes
Enter the first number
-10.5
Enter the second number:
Our application can now be used multiple times and is almost complete. Note:
this is one of the few codes that cannot be run online since our user bot would
have to repeat inputs. In the next lesson, Solved tasks for C# .NET lesson 6, we'll show you how to
sanitize user inputs. You've already learned quite a lot! Nothing better than a
little noggin exercise, right?
In the following exercise, Solved tasks for C# .NET lesson 6, we're gonna practice our knowledge from previous lessons.
Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.
Download
By downloading the following file, you agree to the license terms
Downloaded 48x (135.06 kB)
Application includes source codes in language C#