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

Дата изменения: 12 марта 2020
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");

    Labs and tasks


    Lab 1. While loop

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

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

    The result examples:

    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
    


    ✍ Algorithm:

    • Open Visual Studio.
    • Create Console Application with the name Lesson_4Lab1: File -> New -> Project/Solution -> Console Application.
    • In the Solution Explorer window find a file Program.cs and rename it into L4Lab1.cs.
    • Make sure that the file L4Lab1.cs 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. Convert N to integer before using:
    • ...
       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 to 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.


    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.

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

    The result examples:

    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
    


    ✍ Algorithm:

    • Open Visual Studio.
    • Create Console Application with the name Lesson_4Lab2: File -> New -> Project/Solution -> Console Application.
    • In the Solution Explorer window find a file Program.cs and rename it into L4Lab2.cs.
    • Make sure that the file L4Lab2.cs 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 to 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: In one project create two loops while and do..while loops with different counters (counter1, counter2).
    Note 2: To output the result in one line you have to use the method:

    Console.Write(...);

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

    3 5 7 9 11 13 15 17 19 21
    

    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: In one project create two loops while and do..while loops with different counters (counter1, counter2).
      
    [Solution and Project name: Lesson_4Task2, file name L4Task2.cs]
      
    The result example:

    15 12 9 6 3 0
    

    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). Make it using a while loop.
      
    Note: To calculate a multiplication you have to use a variable with the name product. Start with product = 1.
      
    [Solution and Project name: Lesson_4Task3, file name L4Task3.cs]
      
    The result example:

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

    Task 4 for Lesson #4:

    To do: 5 real numbers are inputted. Calculate an addition of inputted numbers. Make it using a while loop.
      
    Note 1: For real numbers and for variable sum you have to use the variable 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());
    

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

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

    Lab 3. Do loop

    To do: A sequence of integers is inputted. The indication of completion of the sequence is inputted number 0 (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.

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

    The result examples:

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


    ✍ Algorithm:

    • Open Visual Studio.
    • Create Console Application with the name Lesson_4Lab3: File -> New -> Project/Solution -> Console Application.
    • In the Solution Explorer window find a file Program.cs 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 for inputted nubmers. Call it numb. Inisialize the variable for minimum (min) with the maximum number of integers:
    • ...
      int numb;
      int min= int.MaxValue;
      ...
      
    • Create a do..while loop with a condition to check if the inputted 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 inputted numbers in the numb variable. Don't forget that it must be converted into integer:
    • ...
       numb = Int32.Parse(Console.ReadLine());
      ...
      
    • Afterward you must test the inputted 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;
         }
      ...
      
    • 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 inputted. The indication of completion of the sequence is inputted number 0 (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.
        
    [Solution and Project name: Lesson_4Task5, file name L4Task5.cs]
      
    The result example:

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

    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 inputted value of x. Use the auxiliary variable for (x-3). Make the program for 3 inputted 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;  

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

    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
    

    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 inputted 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;  

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

    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
    

    Extra Task 3:

    To do: Create the pattern of a chess board that is 8 x 8. Use X and O to represent the squares. 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.
      
     
    [Solution and Project name: Lesson_4ExTask3, file name L4ExTask2.cs]
      
    The result example:

    XOXOXOXO
    OXOXOXOX
    XOXOXOXO
    OXOXOXOX
    XOXOXOXO
    OXOXOXOX
    XOXOXOXO
    OXOXOXOX
    

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

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

    *
    *


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