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

Дата изменения: 26 февраля 2021
Programming on c sharp in Microsoft Visual Studio. Using while and do Loops in Console Application of c sharp.

Lesson # 4. C# Theory

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 = PromptUser();
    while (answer != "Quit") // "Quit" - is a special value to end the loop
    {
        // Process the data.
        answer = PromptUser();
    }
  • It’s necessary to include the answer = PromptUser(); inside the loop braces. Failure to put this into the loop body will result in an infinite loop because the sentinel 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.
  • do
    {
        // Process the data.
        answer = PromptUser();
    } 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 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 in the Main method, then press enter to create a new line.
    • Request user to input with 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 goint 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 variable with the name counter 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 the text of the task as a comment before the program.
    • To upload the file into the moodle system, find the solution folder on the computer (d:\Projects\Lesson_4Lab1\) and upload the file L4Lab1.cs.
    • 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 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 in 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 variable with the name counter 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 variable counter 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 on the computer (d:\Projects\Lesson_4Lab2\) and upload the file L4Lab2.cs.

    Task 1 for Lesson #4:

    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 for Lesson #4:

    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 for Lesson #4:

    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 for Lesson #4:

    To do: 5 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: A sequence of integers is entered. The indication of completion of the sequence is entered 0 number (if 0 is entered the input of the numbers of the set is finished). Output a minimum number of the numbers of the sequence. 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 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 input 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 the variable for minimum (min) 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 situation with exception: as if we user enters not a number but string. 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 on the computer (d:\Projects\Lesson_4Lab3\) and upload the file L4Lab3.cs.

    Task 5 for Lesson #4:

    To do: A sequence of integers is entered. The indication of completion of the sequence is 0 number (if 0 is entered the input of the numbers of the set is finished). Output a maximum number of the numbers 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]

    Windows Forms Applications

    To create a Windows Forms Applications in Visual Studio 2019:
    Lab 4. Do..while loop

    To do: Create Windows Forms Application to calculate the sum of the sequence x + x/2 + x/3 + x/4 + … (|x| < 1) and the number of summands in this sum. The calculation must be performed until the increment is less than a given precision.
      
    [Solution and Project name: Lesson_4Lab4, form name L4Lab4.cs]
      
    Expected output:

    ✍ Algorithm:

      Controls:

      control name property value text property value
      form L4Lab4 Sum of the sequence
      button btnCalc Calculate
      textbox 1 txtX 0
      textbox 2 txtPrecision 0
      Label lblResult 0
      Labels
    1. Note! Give the names to the controls as it is in the table above.
    2. Create new project (File → New → Project → Windows Forms Application ), and give it a name - Lesson_4Lab4; the form of the project must be named as L4Lab4 (Properties window → (Name) property).
    3. Place all the controls as it is given in the figure above.
    4. Give the proper names to all the controls, by selecting a control and using Property window. Use the table above to have the names.
    5. After, program the Click event for the button. Make double mouse click on the button to open a code of the event.
    6. First, let's declare the variables to store the number of summands at the resulting sequence, sum and summands:
    7. private void btnCalc_Click(object sender, EventArgs e)
        {
          // here your code starts
          int counter=0;
          double sum=0;
          double summand=0.0;
          double x;
         //...
      }
    8. To calculate the sum we're going to use do..while loop. Each summand will be calculated as x divided by the counter. To avoid the error in the case of wrong input of x, we'll use TryParse() procedure:
    9. //...
      do
                  {
                      counter++;
                      if (double.TryParse(txtX.Text, out x)){
                          summand = double.Parse(txtX.Text) / counter;
                      }
                      sum += summand;
                  } while (Math.Abs(summand) > double.Parse(txtPrecision.Text));
    10. After the loop ad the code to have the calculated results in the lblResults label:
    11. lblResult.Text = "sum = " + sum + ", quantity = " + counter;
    12. Run the application and check the output: use comma to enter the floating point number: e.g.: 0,3.
    13. In the case when the user enters incorrect precision, we're going to change the loop condition. Instead of it we'll use a variable of boolean type. Add the following code before the loop:
    14. bool f = false;
                  if (double.TryParse(txtPrecision.Text, out precision)) {
                      f = true;
                  }
      the f variable is used to understand if the input was correct. If it was, so we set f to true and the precision variable to entered value.
    15. Then, change the condition of the loop:
    16. //..
      while (f && Math.Abs(summand) > precision);
      Here we check the f variable. If it equals true, so the precision was entered correctly, and we can repeat the loop. And also, of course, summand must be greater than the precision.
    17. To inform the user in the case when it enters incorrect value we'll use Message box and if statement. Change the code to output the result as follows:
    18. if (f) { 
                      lblResult.Text = "sum = " + sum + ", quantity = " + counter;
                  }
                  else
                  {
                      MessageBox.Show("Enter numeric values");
                  }
    19. Run and debug the program. You should use comma to enter the floating point number: e.g.: 0,3. Run it again and enter incorrect values (any string type data). See the results.

    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]

    Добавить комментарий

    Ваш адрес email не будет опубликован. Обязательные поля помечены *

    *
    *


    Вставить формулу как
    Блок
    Строка
    Дополнительные настройки
    Цвет формулы
    Цвет текста
    #333333
    Используйте LaTeX для набора формулы
    Предпросмотр
    \({}\)
    Формула не набрана
    Вставить