Lesson # 3. Programming on c sharp, For Loop

Дата изменения: 24 февраля 2021
Programming on c sharp in Microsoft Visual Studio. Using Console Application. For loops, sum, product.

Lesson # 3. C# Theory

Repetitions | Loops

  • In programming, you often have to use repetition to iterate over items in a collection or to perform the same task over and over again.
  • Visual C# provides a number of loops that you can use to implement iteration logic. They are for loops, while loops, and do loops.
  • The for Loops

  • The for loop executes a block of code again and again until the specified expression evaluates to false. For loop has a syntax:
  • for ([initializers]; [condition]; [iterator])
    {
       // code to repeat goes here
    }
    
  • The [initializers] section is used to initialize a value as a counter for the loop. On each iteration, the loop checks that the value of the counter is within the range to execute the for loop, specified in the [condition] section, and if so, execute the body of the loop. At the end of each loop iteration, the [iterator] section is responsible for incrementing the loop counter.
  • for (int i = 0 ; i < 10; i++)
    {
        // Code to execute.
    }

    In this example:
    i = 0; is the initializer,
    i < 10; is the condition, and
    i++ is the iterator.
    If the theory is clear, make lab.

    For Each Loops

  • Consider iterating over a collection or an array of values. You would need to know how many elements are in the collection or array. In many cases you will know this, but sometimes you may have collections or arrays that are dynamic and are not sized at compile-time. If the size of the collection or array changes during runtime, it might be a better option to use a foreach loop.
  • An example of how to use a foreach loop to iterate the characters of a string:

    string s = "loops";
    // Process each character in the s:
                foreach (char c in s)
                {
                   // Code to execute.
                }

    An example of how to use a foreach loop to iterate a string array:

    string[] names = new string[10];
    // Process each name in the array.
    foreach (string name in names)
    {
        // Code to execute.
    }
  • C# will stop executing the loop when the end of items in the array is reached.
  • Labs and tasks

    Console Applications

    Lab 1. FOR loop. The values of the counter (read theory)

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

    Expected output:

    Please enter a number and press Enter
    3
    The result: 
    Counter is at: 1
    Counter is at: 2
    Counter is at: 3
    
    Please enter a number and press Enter
    1
    The result: 
    Counter is at: 1
    

    [Solution and Project name: Lesson_3Lab1, file name L3Lab1.cs]

    ✍ Algorithm:

    • Open Visual Studio.
    • Create a Console Application with a name Lesson_3Lab1: FileNewProject/SolutionConsole Application.
    • In the Solution Explorer window find a file Program.cs and rename it into L3Lab1.cs.
    • Make sure that the file L3Lab1.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 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());
      ...
      
    • Create a for loop with N repetiotions. Use a variable with the name counter as a counter for FOR loop (you can also use the code snippet for + Tab(twice)):
    • ...
      for(int counter = 1; counter <= N; counter++)
        {
           ...
        }
      ...
      
    • Output the values of the variable counter within the loop:
    • ...
      for(int counter = 1; counter <= N; counter++)
        {
            Console.WriteLine($"Counter is at: {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.
    • 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_3Lab1\) and upload the file L3Lab1.cs.
    Task 1 for Lesson #3:

    To do: Output the sequence -3 0 3 6 9 12 15 18 21 24. Make the task using FOR loop. An Iterator of the loop has a step equaled 3.
      
    Note: To make a step equaled 3 see syntax:

    for ([initializers]; [condition]; [iterator]) → 
    instead of the iterator you'll have counter+=3
    

    Expected output:

    The sequence : -3 0 3 6 9 12 15 18 21 24
    

    [Solution and Project name: Lesson_3Task1, file name L3Task1.cs]

    Task 2 for Lesson #3:

    To do: Output the sequence: 1 2 3 4 . . . 99 100 99 . . . 3 2 1.
      
    Note 1: Create two for loops: the first loop 1 2 3 4 . . . 99 100, the second loop 99 . . . 3 2 1 (with a step i-- as a counter for loop).

    Note 2: To output all the values within one line you should use the following method:

    Console.Write($"{i} ");
    

     
    Expected output:

    The sequence : 1 2 3 4 5 . . . 99 100 99 . . . 4 3 2 1
    

    [Solution and Project name: Lesson_3Task2, file name L3Task2.cs]

    Task 3 for Lesson #3:

    To do: 10 integers are entered. Output the quantity of positive and negative among them.
      
    Note 1: Create for loop to input the numbers. Check whether the number is positive or negative within the loop. Use two counters to find the quantity.

      Note 2: Don't forget to convert the variable storing entered numbers to integer type (Int32.Parse(...)).
     
      
    Expected output:

    1  -5  -12   2   3   9   -1  9   5   -8   => counter_positive = 6, counter_negative = 4
    

    [Solution and Project name: Lesson_3Task3, file name L3Task3.cs]

    Task 4 for Lesson #3:

    To do: 10 integers are randomly generated. Output these numbers and the addition (a sum) of the numbers.
      
    Note 1: Create for loop to input the numbers. To calculate the addition, you have to use the variable with the name sum.

      
    Note 2: To have the numbers randomly generated a special variable (random object) and Next(maxValue) method should be used:

    var rand = new Random();
    a = rand.Next(10);

      
    Expected output:

    1  -5  -12   2   3   9   -1  9   5   -8   => sum = 3
    

     
    [Solution and Project name: Lesson_3task4, file name L3Task4.cs]

    Task 5 for Lesson #3:

    To do: Calculate the addition of 10 numbers of the sequence: 1 + 3 + 5 + 7 + 9 + 11 + 13 + 15 + 17 + 19 (numbers are NOT entered, you have to get them, using a loop).
      
    Note: To calculate the addition you have to use the variable with the name sum.

      
    Expected output:

    1 + 3 + 5 + 7 + 9 + 11 + 13 + 15 + 17 + 19   => sum = 100
    

      
    [Solution and Project name: Lesson_3task5, file name L3Task5.cs]

    Task 6 for Lesson #3:

    To do: 10 real numbers are entered or randomly generated. Output a multiplication of input numbers.
      
    Note 1: Create for loop to input the numbers. To calculate the multiplication you have to use the variable with the name product.

      
    Note 2: Don't forget to initialize the variable product with a double type value (double product = 1.0;) and to convert the variable for inputted numbers to double type (Double.Parse(Console.ReadLine())).

    Note 3: To have randomly generated reals you should use a special variable (random object) and conversion to float type:

    // reals are generated in the range from 10.6 to 20.7
    var rand = new Random();
    a = (float)rand.Next(106, 207) / 10f;

     

    Expected output:

    14,8000 17,1000 19,7000 14,2000 13,5000 16,8000 11,0000 17,2000 17,9000 11,0000 
    product = 598 166 786 228,4310
    

     
    [Solution and Project name: Lesson_3Task6, file name L3Task6.cs]

    Lab 2. NESTED loop. Prime numbers

    To do: Create a nested for loop to find all prime numbers less than 100 (beginning with number 2).

    [Solution and Project name: Lesson_3Lab2, file name L3Lab2.cs]

    Expected output:

    Prime numbers: 
    2 is prime
    3 is prime
    5 is prime
    7 is prime
    11 is prime
    ...
    97 is prime
    

    ✍ Algorithm:

    • Open Visual Studio.
    • Create Console Application with the name Lesson_3Lab2: FileNewProject/SolutionConsole Application.
    • In the Solution Explorer window find a file Program.cs and rename it into L3Lab2.cs.
    • Make sure that the file L3Lab2.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.
    • Output the phrase "Prime numbers: ":
    • static void Main(string[] args)
        {
           // lab 4
           Console.WriteLine("Prime numbers: ");
        }
    • Declare two integer variables, the counters for the loops:
    • ...
       int outer;
       int inner;
      ...
      
    • Create an outer for loop with a counter called outer. This loop has to iterate through all the numbers in the interval [2,99] (or you can also use the code snippet for + Tab(twice)):
    • ...
      for (outer = 2; outer < 100; outer++)
         {
          ...
         }
      ...
      
    • Create a nested for loop (within the previous loop) with a counter called inner. This loop has to check whether or not every number is a prime number. If it is, the prime has to be outputted:
    • ...
      for (outer = 2; outer < 100; outer++)
         {
          for (inner = 2; inner <= (outer / 2); inner++)
             {
                 if ((outer % inner) == 0) break; // if factor found, not prime
             }
          if (inner > (outer / inner))
             {
                Console.WriteLine("{0} is prime", outer);
             }
         }
      ...
      
      How we check whether a number is Prime or not?

    • A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. A natural number greater than 1 that is not prime is called a composite number.
    • For example, 5 is prime because the only ways of writing it as a product, 1 × 5 or 5 × 1, involve 5 itself.
    • 6 is composite because it is the product of two numbers (2 × 3) that are both smaller than 6.
    • Primes are central in number theory because of the fundamental theorem of arithmetic: every natural number greater than 1 is either a prime itself or can be factorized as a product of primes that is unique up to their order.
    • 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.
    • 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_3Lab2\) and upload the file.
    Task 7 for Lesson #3:

    To do: For every x in the interval [2;8] find the value of the function z(x,y) = xy. The variable y varies in the interval [2;5].
      
    Note: Create two for loops (nested loop): one loop within the other. Variable x has to be modified in the outer loop, variable y has to be modified in the inner loop.

    Note: To output the power of a number:

    using static System.Math;
    ...
    Math.Pow(x,y);

      
    Expected output:

    z(x,y) = 2^2 = 4
    z(x,y) = 2^3 = 8
    z(x,y) = 2^4 = 16
    z(x,y) = 3^2 = 9
    z(x,y) = 3^3 = 27
    z(x,y) = 3^4 = 81
    z(x,y) = 4^2 = 16
    z(x,y) = 4^3 = 64
    z(x,y) = 4^4 = 256
    z(x,y) = 5^2 = 25
    z(x,y) = 5^3 = 125
    z(x,y) = 5^4 = 625
    ... etc.
    

    [Solution and Project name: Lesson_3Task7, file name L3Task7.cs]

    Windows Forms Applications

    To create a Windows Forms Applications in Visual Studio 2019:
    Lab 3. For loop

    To do: Create Windows Forms Application to calculate the value of the function z(x,y) = x - y. The ranges of x and y variables are entered into text fields.
      
    [Solution and Project name: Lesson_3Lab3, form name L3Lab3.cs]
      
    Expected output:

    ✍ Algorithm:

      Controls:

      control name property value text property value
      form L3Lab3 for loops
      button btnCalc calculate z(x,y)
      textbox 1 txtX1 0
      textbox 2 txtX2 0
      textbox 3 txtY1 0
      textbox 4 txtY2 0
      ListBox lstResult
      Labels
    1. Note! Give the names to the controls as it is in the specification of C# language and as it is always written in the lab or in the table above.
    2. Create new project (File → New → Project → Windows Forms Application ), and give it a name - Lesson_3Lab3; the form of the project must be named as L3Lab3 (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. Now program the Click event for the button. Make double mouse click on the button to open a code of the event. The x range and y range will be entered to the text boxes. Let's associate these text boxes with the variables. And don't forget to convert entered values to integers:
    6. private void button1_Click(object sender, EventArgs e)
              {
                  // here your code starts:
                  int fromX = int.Parse(txtX1.Text);
                  int toX = int.Parse(txtX2.Text);
                  int fromY = int.Parse(txtY1.Text);
                  int toY = int.Parse(txtY2.Text);
                  //...
              }
      
    7. Now, we can create nested loops to calculate the function z(x,y) = x - y. The outer loop will iterate over the x range, and inner loop - over the y range. Continue the click event of the button:
    8.    //...
         for (int x = fromX; x <= toX; x++)
                  {
                      for (int y = fromY; y <= toY; y++)
                      {
                          // ...
                      }
                  }
      
    9. The results of the calculations will be added to list box control - each calculation must be in the separate line. We will use Add method of Items collection of the list box:
    10.         //...
               for (int y = fromY; y <= toY; y++)
                      {
                          // here your code starts:
                          lstResult.Items.Add($"z(x,y) = {x} - {y} = {x - y}");
                          // the end of you code
                      }
      
    11. Run the application, enter some values to text boxes and press the button.
    12. Now, let's consider the entered range was from bigger number to less number. In this case the error will occur.
    13. Add the following code to check the entered range before the loop:
    14. if (fromX > toX)
                  {
                      MessageBox.Show("the range must be from less to bigger");
                      txtX1.Text = "";
                      txtX2.Text = "";
                  }
      
      Show method of MessageBox class is used to inform user.
    15. We've checked the range of x variable. Now add the same code to check the range of y variable. Do it yourself.
    16. Run and debug the program.

    To students of SFEDU: follow the hyperlink to watch the lesson in Teams

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

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

    *
    *


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