C# Beginner1 Repairing NonameIntroduction to while loop

antivirus

Antivirus Scan

The day finally came when Noname called me back down to the basement to help him with one of his modules. Finally! One step closer to returning to my own time.

As soon as I keyed in the secret code, I heard his robotic voice. "Hi! Haven't seen you for a while!" Noname said.
"Hi, Noname," I returned. "Nice to see you too! Let's get started ASAP - I want to get back into my time!
"Let's start with my antivirus protection system." Noname suggested.
"What should I do?"

"My problem is not with the antivirus detection itself, but in running the scan. As you know, Ritchie did everything to control me. Part of that was adding a remote access to my system that he can connect to and check what I'm doing. An antivirus check is forbidden for me - if he sees that I'm checking for viruses, he'll immediately turn me off. I need help with scanning my files quickly and then being able to stop scanning as soon as Ritchie connects."

I took a few seconds to think through the problem. "If I know the number of files to scan," I thought out loud, "I can write a for loop to iterate through all of the files to scan them." I suggested.
"And when Ritchie connects, how will the scan stop if Ritchie connects to the system?"
"I haven't thought that far ahead yet," I admitted. "Do you have anything in mind?"
"Well, if you're open to learning, I could teach you how to use a while loop." Noname replied.
"Sounds good," I said. "Enlighten me!"

Feed me with knowledge

While Loop

"Ok, my dear human, listen up. Some programmers call the for loop a "loop with a known number of repetitions" . That's because when you see a for loop, it's typically pre-programmed to run a specified number of times; 5, 10, etc. In contrast, a while loop is a "loop with an unknown number of repetitions" because you don't really know how many times it will iterate. Here is a while loop syntax in C#:

while (/* condition */)
{
    // while loop body
}

A while loop executes a code in its body while a specified condition is true. As soon as that condition is false, the loop terminates. The condition has a bool type. This diagram illustrates the basics of a while loop:

C# while loop

Take a look at some examples:

while (true) // Executes forever
{
    Console.WriteLine("Never Stop!");
}
while (false) // Never executes
{
    Console.WriteLine("Never execute");
}
bool iNeedMoreCandies = true;
int candiesCount = 0;

while (iNeedMoreCandies)
{
    Console.WriteLine("One more candy?");

    string answer = Console.ReadLine();
    if (answer == "Yes")
    {
        candiesCount++;
    }
    else
    {
        iNeedMoreCandies = false;
    }
}

"See those examples I just showed you?" Noname asked. "The first two examples are trivial. But the last one is interesting. Do you understand what is it doing?"
"Let's see. It looks like it asks the user if they want one more candy. As long as the user enters 'Yes,' it increments the candy count. As soon as the user answers anything but 'Yes,' it stops the loop."
"Correct! You're a quick learner, Teo. Now let's get you Writing your first while loop."

First c sharp while loop

"Do you want to know a secret, Teo?" Noname asked.
"Sure!" I answered.
"You can omit the enclosing brackets if you have a single command in a for or while loop; just the same as you can in an if statement. Here is a demonstration:

for(int i = 0; i < 10; i++)
    Console.WriteLine("Print me!");
while(someBool)
    Console.WriteLine("Print me!");

You can also replace a for loop with a while loop, and vice-versa. In the below example, the code snippets in the left and right colums of the following table are equivalent:

For loop While loop
for(int i = 0; i < 10; i++)
{
    Console.WriteLine("Print me!");
}
int repetitions = 10;
while(repetitions > 0)
{
    Console.WriteLine("Print me!");
    repetitions--;
}
int candiesCount = 0;

for (string input = "Yes";
    input == "Yes"; 
    input = Console.ReadLine())
{
    Console.WriteLine("One more candy?");
    candiesCount++;
}
bool iNeedMoreCandies = true;
int candiesCount = 0;

while (iNeedMoreCandies)
{
    Console.WriteLine("One more candy?");

    string answer = Console.ReadLine();
    if (answer == "Yes")
    {
        candiesCount++;
    }
    else
    {
        iNeedMoreCandies = false;
    }
}

"Now that you have some practice with these loops, let's talk about strategy. Try to stick to this rule: if you know during compile time how many times your code will be executed, consider using a for loop; othervise, use a while loop."
"Noname, in that code you showed me, what does repetitions-- do?"

The -- operater decrements the named variable by one. This is the same as repetitions = repetitions - 1 There are actually 4 different operators: i ++ , ++ i , i -- , and -- i . When the symbols are placed before the variable, it's called a prefix operator. When applied after the variable, it's called called a postfix operator. The prefix operators change the value of the variable first and then return the result. Postfix operators return the current variable value and then change it.

Operator Name Usage Equivalent Code Types
Postfix increment
i++
i = i + 1
byte
sbyte
char
decimal
double
float
int
uint
long
ulong
short
ushort
Prefix increment
++i
i = i + 1
Postfix decrement
i--
i = i - 1
Prefix decrement
--i
i = i - 1

"Wow," I said, "it turns out that there are many more standard types in C# than I thought."
"Yes and no." Noname replied. "Many of them are actually quite similar, but we'll leave the details for next time."
"I'll confess Noname, I don't quite understand the prefix/postfix difference. What's the difference between i++ and ++i in the code? In the table you showed me, both prefix and postfix have the same 'equivalent code'."
"Yes, it is confusing for the human brain. Here are some examples that might help illustrate it."

int i = 2;
Console.WriteLine(i++); // Outputs 2
Console.WriteLine(i);   // Outputs 3
int i = 2;
Console.WriteLine(++i); // Outputs 3
Console.WriteLine(i);   // Outputs 3

In the first example we are using a postfix increment. Hence, first the current 'i' value is printed to the console. That value is 2. After the write, we increment 'i', which is when it becomes 3. The next time we call Console.WriteLine, the value of 'i' is 3.

The second example uses a prefix increment. 'i' is incremented first and then its new value (3) is output to the console.
Note that the priority of the mathematical operations like + , - , * , and / are lower than increment and decrement. That means that the increment/decrement part will be calculated before any operation in between those increments/decrements.

int number = 1;
int result = ++number + ++number;
Console.WriteLine(number);  // Outputs 3
Console.WriteLine(result);  // Outputs 5

In other terms, the above code is equivivalent to:

int number = 1;
number = number + 1;
int result = number;
number = number + 1;
result = result + number;

Console.WriteLine(number);  // Outputs 3
Console.WriteLine(result);  // Outputs 5

"Still a little complicated, Noname." I said, a little exasperated.
"Don't worry, Teo. You can use either of those in your code. Unless you're doing something complicated, postfix vs. prefix doesn't usually matter, but it is very good to know the difference!" Noname replied and continued, "To make your loop knowledge complete, I want to tell you about nested loops .

Nested loops

The term "nested" can be applied to the loop that is inside another loop. Take a look at this example:

for(int i = 0; i < 3; i++) // This loop executes the inner loop 3 times
{
  for(int j = 0; j < 3; j++) // This loop draws the row of 3 stars
  {
    Console.Write("*");
  }
  Console.WriteLine(); // Here we go to the new line after the row is completed
}
// Outputs:
***
***
***

" The most important trick about them is that all variables created in the inner loop get destroyed when the outer loop iterates. "
Same as with for loops, you can create nested while loops:"

int i = 0;
while(i < 3) // This loop executes the inner loop 3 times
{
    int j = 0;
    while (j < 3) // This loop draws the row of 3 stars
    {
        Console.Write("*");
        j++;
    }
    Console.WriteLine(); // Here we go to the new line
    i++;
}

"What do you think about it?" Noname asked.
"This opens such a big field of opportunities!" I answered.
Noname replied, "Right, Teo, totally agree! One more useful feature is that you can use the outer loop variable in the inner loop. This means that the inner loop can "know" which iteration is currently in the outer loop. Here is a small demonstration:

for (int i = 0; i < 3; i++) // This loop executes the inner loop 3 times
{
    // Inner loop draws the row of several stars (first 1 star, then 2 stars, etc.)  
    
    for (int j = 0; j <= i; j++) // Note, j is compared to i
    {
      Console.Write("*");
    }
    Console.WriteLine(); // Here we go to the new line
}
// Outputs:
// *
// **
// ***

"Noname, I think it's enough of theory for today," I said.
"Are you tired? Don't worry, the human brain absorbs information much slower than machine memory. The understanding will come. Maybe after some tasks!"

"I believe you are ready to fix my antivirus system!" Noname said once I had completed his tasks.

Antivirus protection

At CodeEasy we believe that learning should be fun and engaging. Please reach out to us to share your feedback and collaboration ideas.