Lesson # 4. Using while and do Loops in C sharp

Programming on c sharp in Microsoft Visual Studio. Using while and do Loops in Console Application of c sharp.

Lesson # 4. C# Theory

Lecture in pdf format

While Loops

  • A while loop enables you to execute a block of code while a given condition is true. For example, you can use a while loop to make user input until the user indicates that there is no more data to enter. The loop can continue to prompt the user until he decides to end the interaction by entering a special value. In this case, the special value is responsible for ending the loop.
  • string answer = Console.ReadLine();
    while (answer != "Quit") // "Quit" - is a special value to end the loop
                {
                    // Process the data.
                    answer = Console.ReadLine();
                }
  • It’s necessary to include the answer = Console.ReadLine(); inside the loop braces. Failure to put this into the loop body will result in an infinite loop because the initial value can never be changed.
  • Do..while Loop

  • A do loop is very similar to a while loop, with the exception that a do loop will always execute the body of the loop at least once. In a while loop, if the condition is false from the start, the body of the loop will never execute.
  • You might want to use a do loop if you know that the code will only execute in response to a user prompt for data. In this case, you know that the application will need to process at least one piece of data, and can, therefore, use a do loop.
  • string answer;
    do
             {
                 // Process the data.
                 answer = Console.ReadLine(); 
             } while (answer != "Quit");

    Exceptions

    • Exceptions are the best mechanism for error handling. An exception is thrown by a code with a run-time error, and caught by a code that can handle an error. If the exception is not handled by a program, then the program terminates with crash.
    • An exception in C# is an object of an Exception class or some inherited class. Name of a class defines type of exception.
    • Example:

      int a = 0;
      bool flag = false;
      do
      {
          try
          {
                          string s = Console.ReadLine();
                          a = int.Parse(s);
                          flag = true;
           }
           catch (FormatException e)
          {
                          Console.WriteLine(e.Message + " Repeat input");
           }
       } while (!flag);
       Console.WriteLine(a + " OK");
    • The exceptions are handled in try … catch block.
    • When an exception appears inside try block, the program execution goes to the first appropriate exception handler – catch block.
    • If there are no handlers for the created exception, the program terminates with an error message.
    • FormatException class handles the exceptions. The exception that is thrown when the format of an argument does not meet the parameter specifications of the invoked method.
    • Another way of error handling is using of TryParse procedure, which returns true value if conversion is possible (it has output parameter to return the converted value):

      int a = 0;
      string s = Console.ReadLine();
      if (Int32.TryParse(s, out a))
                  {
                      Console.WriteLine(a + " OK");
                  }
      else
                  {
                      Console.WriteLine("Wrong input");
                  }

    Labs and tasks

    Console applications

    Lab 1. While loop

    To do: Ask user to enter a number (N). Create a simple while loop with N repetitions that displays the values of the loop counter.

    Expected output:

    Please enter a number and press Enter
    3
    The result: 
    Current value of counter is 1
    Current value of counter is 2
    Current value of counter is 3
    
    Please enter a number and press Enter
    1
    The result: 
    Current value of counter is 1
    

    [Solution and Project name: Lesson_4Lab1, file name L4Lab1.cs]

    ✍ Algorithm:

    • Open the Visual Studio.
    • Create a Console Application with a name Lesson_4Lab1: File -> New -> Project/Solution -> Console Application.
    • In the Solution Explorer window find a Program.cs file and rename it into L4Lab1.cs.
    • Make sure that the L4Lab1.cs file is active in the Solution Explorer window.
    • Place your cursor immediately after the open curly brace of the Main method, then press enter to create a new line.
    • Request user to enter a number (ReadLine() method):
    • static void Main(string[] args)
        {
           Console.WriteLine("Please enter a number and press Enter");
        }
    • Assign the entered value to the variable N. We’re not going to convert N to integer because we’ll do it later. We’ll use var as a type, it we’ll be considered as a type of a value set to variable:
    • ...
        int N = Int32.Parse(Console.ReadLine());
      ...
      
    • We start with counter = 1. Create a while loop with N repetitions. Use a counter variable as a counter for while loop (or you can also use the code snippet while + Tab(twice)):
    • ...
      int counter = 1;
      while (counter <= N)
      {
          counter++;
      }
      ...
      
      The condition check for the while, tests if counter is less than N or equal to N, if so, the loop body code executes inside the loop, we output the value of counter and then increment it by 1.
    • Output the values of the variable counter within the loop:
    • ...
      int counter = 1;
      while (counter <= N)
      {
          Console.WriteLine($"Current value of counter is {counter}");
          counter++;
      }
      ...
      
    • Press the CTRL+F5 keys to start the application without debugging.
    • This will cause Visual Studio to compile the code and run the application. A console window will open asking you to enter an integer value.
    • Experiment with different values to see the output. Pay attention to the output to see what the last value is, to ensure you understand how the evaluation of the condition is done and how the while loop executes.
    • Experiment with this by setting counter to a value greater than N and run the code.
    • Format your code by pressing Ctrl+A then Ctrl+K and then Ctrl+F.
    • Don’t forget to place a text of the task as a comment before the program.
    • To upload the file into the moodle system, find the solution folder and upload the L4Lab1.cs file.
    • ExtraTask: Think about how to check if entered data was a number. To make it possible you should use try...catch block or TryParse() procedure.

    Lab 2. Do..while loop. The values of the counter

    To do: Create a simple do..while loop with 5 repetitions that displays the values of the loop counter.

    Expected output:

    The result: 
    Current value of counter is 1
    Current value of counter is 2
    Current value of counter is 3
    Current value of counter is 4
    Current value of counter is 5
    

    [Solution and Project name: Lesson_4Lab2, file name L4Lab2.cs]

    ✍ Algorithm:

    • Open the Visual Studio.
    • Create a Console Application with the name Lesson_4Lab2: File -> New -> Project/Solution -> Console Application.
    • In the Solution Explorer window find a Program.cs file and rename it into L4Lab2.cs.
    • Make sure that the L4Lab2.cs file is active in the Solution Explorer window.
    • Place your cursor immediately after the open curly brace of the Main method, then press enter to create a new line.
    • We start with counter = 1. Create a do..while loop with 5 repetitions. Use a counter variable as a counter for do..while loop (or you can also use the code snippet do + Tab(twice)):
    • ...
      int counter = 1;
      do
      {
          counter++;
      }
      while (counter <= 5);
      ...
      
      The condition check for the while, tests if counter is less than N or equal to N, if so, the loop body code executes inside the loop, we output the value of counter and then increment it by 1.
    • Output the values of the counter variable within the loop:
    • ...
      int counter = 1;
      do
      {
          Console.WriteLine($"Current value of counter is {counter}");
          counter++;
      }
      while (counter <= 5);
      ...
      
    • Press the CTRL+F5 keys to start the application without debugging.
    • This will cause Visual Studio to compile the code and run the application. A console window will open, asking you to enter an integer value.
    • Experiment with different values to see the output.
    • Format your code by pressing Ctrl+A then Ctrl+K and then Ctrl+F.
    • Don’t forget to place the text of the task as a comment before the program.
    • To upload the file into the moodle system, find the solution folder and upload the L4Lab2.cs file.

    Task 1:

    To do: Output the sequence 3 5 7 9 ... 21 (from 3 to 21 with a step = 2). Make it twice: using while and do..while loops.
      
    Note 1: Within one project create two loops: while and do..while loops with different counters (counter1, counter2).

    Note 2: To output the result within one line you have to use the following method:

    Console.Write(...);

      
    Expected output:

    3 5 7 9 11 13 15 17 19 21
    

      
    [Solution and Project name: Lesson_4Task1, file name L4Task1.cs]

    Task 2:

    To do: Output the sequence 15 12 9 6 3 0 (from 15 downto 0 with a step = -3). Make it twice: using while and do..while loops.
      
    Note 1: Within one project create two loops: while and do..while loops with different counters (counter1, counter2).
      
    Expected output:

    15 12 9 6 3 0
    

      
    [Solution and Project name: Lesson_4Task2, file name L4Task2.cs]

    Task 3:

    To do: Calculate a multiplication of 2-digit even integers in the interval [10;20] (10 * 12 * 14 * 16 * 18 * 20). You should use a while loop.
      
    Note: To calculate a multiplication you have to use a variable with the name product. Start with product = 1.
      
    Expected output:

    10 * 12 * 14 * 16 * 18 * 20  = 9676800
    

      
    [Solution and Project name: Lesson_4Task3, file name L4Task3.cs]

    Task 4:

    To do: Five real numbers are entered. Calculate an addition of the numbers. Make it using a while loop.
      
    Note 1: To solve this problem you should use the variables of double type:

    double sum = 0;
    double numb;

      
    Note 2: Don't forget to convert the values of inputted numbers into double type:

    numb=Double.Parse(Console.ReadLine());

      
    Expected output:

    Please enter 5 numbers and press Enter
    1 4 2 9 2
    The sum of inputted numbers = 18
    

      
    [Solution and Project name: Lesson_4Task4, file name L4Task4.cs]

    Lab 3. Do loop

    To do: An integer sequence is entered. The indication of completion of the sequence is 0 number entered (if 0 is entered the input of the numbers of the set is terminated). Output a minimum number of the sequence numbers. To make the program you have to use do..while loop. It is not allowed to use standard min function.

    Expected output:

    Please enter the sequence of numbers and finish with 0
    3 5 1 0
    the minimum number is 1
    

    [Solution and Project name: Lesson_4Lab3, file name L4Lab3.cs]

    ✍ Algorithm:

    • Open the Visual Studio.
    • Create a Console Application with the name Lesson_4Lab3: File -> New -> Project/Solution -> Console Application.
    • In the Solution Explorer window find a Program.cs file and rename it into L4Lab3.cs.
    • Request user to enter the numbers:
    • ...
      Console.WriteLine("Please enter the sequence of numbers and finish with 0");
      ...
    • Declare a variable to store the entered nubmers. Call it numb. Inisialize a min variable with the maximum value of integer type:
    • ...
      int numb;
      int min= int.MaxValue;
      ...
      
    • Create a do..while loop with a condition to check if entered number is not equal to 0:
    • ...
       do
         {
              ...
         }
       while (numb != 0);
      ...
      
      The condition check for the while, tests if numb is not equal to 0, if so, the loop body code executes inside the loop.
    • Within the loop body you have to use Console.ReadLine() method and store entered numbers in the numb variable. Don't forget that it must be converted into integer:
    • ...
       numb = Int32.Parse(Console.ReadLine());
      ...
      
    • Afterward you must test entered number if it is less than minimum and not equal to zero (because 0 means the end of the sequence):
    • ...
       numb = Int32.Parse(Console.ReadLine());
       if (numb < min && numb!=0)
         {
             min = numb;
         }
      ...
      
    • Then, let's modulate a situation with an exception occured: as if the user enters text intead of a number. To handle the exception we'll use try..catch block:
    •  try
                  {
                      do
                      {
                          numb = Int32.Parse(Console.ReadLine());
                          if (numb < min && numb != 0)
                          {
                              min = numb;
                          }
                      }
                      while (numb != 0);
                  }
                  catch (FormatException e)
                  {
                      Console.WriteLine(e.Message + " Repeat input");
                  }
      
    • Run the program and enter some string.
    • Output the value of the minimum variable (min) after the loop body:
    • ...
       Console.WriteLine($"the minimum number is {min}");
      ...
      
    • Press the CTRL+F5 keys to start the application without debugging.
    • Format your code by pressing Ctrl+A then Ctrl+K and then Ctrl+F.
    • Experiment with different values to see the output.
    • Don’t forget to place the text of the task as a comment before the program.
    • To upload the file into the moodle system, find the solution folder and upload the L4Lab3.cs file.

    Task 5:

    To do: A sequence of integers is entered. The indication of a completion of the sequence is 0 number (if 0 is entered the input of the numbers of the set is terminated). Output a maximum number of the sequence and its order number in the sequence. To make the program you have to use do..while loop. It is not allowed to use standard max function.
      
    Expected output:

    Please enter the sequence of numbers and finish with 0
    3 5 1 0
    the maximum number is 5, its position is 2
    

        
    [Solution and Project name: Lesson_4Task5, file name L4Task5.cs]


    Extra tasks

    Extra Task 1:

    To do: Calculate the value of the function y = 4(x-3)6-7(x-3)3 + 2 for the entered value of x. Use the auxiliary variable for (x-3). Make the program for 3 entered values of x (you have to use loop).
      
    Note: Include the following libraries not to print console class and math class:

    using static System.Console;
    using static System.Math;  

      
    Expected output:

    Please enter a value of x
    2
    x=2;y=13
    Please enter a value of x
    3
    x=3;y=2
    Please enter a value of x
    4
    x=4;y=-1
    

      
    [Solution and Project name: Lesson_4ExTask1, file name L4ExTask1.cs]

    Extra Task 2:

    To do: The coordinates of the chess board field x and y (integers in the range 1-8) are given. It is known that the lower left square of the Board ((1, 1)) is black, check if it is a truth that: "This square is white" (using entered coordinates). Do not use the conditional operator.
      
    Note: Include the following libraries not to print console class and math class:

    using static System.Console;
    using static System.Math;  

      
    Expected output:

    Please enter x (1-8)
    3
    Please enter y (1-8)
    4
    This square is white: true
    
    Please enter x (1-8)
    3
    Please enter y (1-8)
    5
    This square is white: false
    

      
    [Solution and Project name: Lesson_4ExTask2, file name L4ExTask2.cs]

    Extra Task 3:

    To do: Create the appropriate nested looping structure to output the characters in an 8 x 8 grid on the screen using Console.Write() or Console.WriteLine() as appropriate. Include a decision structure to ensure that alternate rows start with opposite characters as a real chess board alternates the colors among rows.
      
     
    Expected output:

    XOXOXOXO
    OXOXOXOX
    XOXOXOXO
    OXOXOXOX
    XOXOXOXO
    OXOXOXOX
    XOXOXOXO
    OXOXOXOX
    

     
    [Solution and Project name: Lesson_4ExTask3, file name L4ExTask3.cs]