Lesson # 3. Programming on c sharp, For Loop

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


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

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

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

    The result examples:

    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
    


    ✍ Algorithm:

    • Open Visual Studio.
    • Create Console Application with the name Lesson_3Lab1: File -> New -> Project/Solution -> Console 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 with 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
    

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

    The result example:

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

    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 must use a method:

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

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

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

    Task 3 for Lesson #3:

    To do: 10 integers are inputted. Output the quantity of positive and negative among them.
      
    Note: 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: Don't forget to convert the variable for inputted numbers to integer type (Int32.Parse(...)).
     
    [Solution and Project name: Lesson_3Task3, file name L3Task3.cs]
      
    The result example:

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

    Task 4 for Lesson #3:

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

      
    Note: Don't forget to convert the variable for inputted numbers to integer type (Int32.Parse(...)).
     
    [Solution and Project name: Lesson_3task4, file name L3Task4.cs]
      
    The result example:

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

    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 inputted, you have to get them, using a loop).
      
    Note: To calculate the addition you have to use the variable with the name sum.

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

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

    Task 6 for Lesson #3:

    To do: 10 real numbers are inputted. Output the multiplication of inputted numbers.
      
    Note: Create for loop to input the numbers. To calculate the multiplication you have to use the variable with the name product.

      
    Note: 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())).
     
    [Solution and Project name: Lesson_3Task6, file name L3Task6.cs]
     
    The result example:

    1,1  2,4  5,1  7,2  6,4  8,1  6,7  3,2  3,3  2,4  =>  product = 853338,921998746
    


    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]

    The result examples:

    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: File -> New -> Project/Solution -> Console 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);

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

    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.
    

    Task 8 for Lesson #3:

    To do: For every x in the interval [30;33] find the value of the function z(x,y) = x - y. The variable y varies in the interval [1;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.

    [Solution and Project name: Lesson_3Task8, file name L3Task8.cs]
      
    The result example:

    z(x,y) = 30-1=29
    z(x,y) = 30-2=28
    z(x,y) = 30-3=27
    z(x,y) = 30-4=26
    z(x,y) = 30-5=25
    z(x,y) = 31-1=30
    ... etc.
    

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

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

    *
    *


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