Lesson # 3. Programming on c sharp, For Loop

Programming on c sharp in Microsoft Visual Studio. Using Console Application. For loops, sum, product.

Lesson # 3. C# Theory

Lecture in pdf format

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];
    names[0] = "Ivan"; names[1] = "Ann"; names[2] = "Mike";
    // Process each name in the array.
    foreach (string name in names)
    {
         Console.WriteLine(name);
    }
  • 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 a Visual Studio IDE.
    • Create a Console Application with a name Lesson_3Lab1: FileNewProject/SolutionConsole Application.
    • In a Solution Explorer window find a Program.cs file 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 of 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 counter variable as a counter of the FOR loop (you can also use the code snippet for + Tab(twice)):
    • ...
      for(int counter = 1; counter <= N; counter++)
        {
           ...
        }
      ...
      
    • Output the values of the 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 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 and upload the file L3Lab1.cs.
    Task 1:

    To do: Output the sequence -3 0 3 6 9 12 15 18 21 24. Perform 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:

    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:

    To do: 10 integers are entered. Output the quantity of positive and negative among them.
      
    Note 1: Create for loop to enter 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 a variable storing entered numbers to integer type (Int32.Parse(...)).
     
      
    Expected output:

    1  -5  -12   2   3   9   -1  9   5   -8   
    ve the numbers randomly generated acounter_positive = 6, counter_negative = 4
    

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

    Task 4:

    To do: 10 integers are randomly generated. Output these numbers and the addition (a sum) of the numbers.
      
    Note 1: Create for loop to enter the numbers. To calculate the addition, you have to use a variable named 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,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:

    To do: Calculate the addition of 10 sequence numbers: 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 a variable named 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:

    To do: 10 real numbers are entered or randomly generated. Output a multiplication of that numbers.
      
    Note 1: Create for loop to enter or generate the numbers. You should use a variable named product to calculate the multiplication.

      
    Note 2: Don't forget to initialize the product variable with a double type value (double product = 1.0;) and convert a variable, storing entered 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();
    //...
    numb = (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 which are less than 100 (starting with a 2 number).

    [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 the Visual Studio.
    • Create a Console Application with the name Lesson_3Lab2: FileNewProject/SolutionConsole Application.
    • In the Solution Explorer window find a Program.cs file 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 an open curly brace of 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($"{outer} is prime");
             }
         }
      ...
      
      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 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 file.
    Task 7:

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

    Note 2: To output the power of a number use the following statement:

    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) = 2^5 = 32
    z(x,y) = 3^2 = 9
    z(x,y) = 3^3 = 27
    z(x,y) = 3^4 = 81
    z(x,y) = 3^5 = 243
    z(x,y) = 4^2 = 16
    z(x,y) = 4^3 = 64
    z(x,y) = 4^4 = 256
    z(x,y) = 4^5 = 1024
    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]

    Task 8:

    To do: Ask user to enter a text and then, to enter a character. Output each letter of the text adding entered character to it. You should use foreach loop.

    Note: When entering a character you should convert it into Char type. It is better to use Convert.ToChar method.

    Expected output:

    Enter the text, please:
    >> Hello world!
    Enter a charecter to add, please:
    >> &
    H& e& l& l& o&  & w& o& r& l& d& !&
    

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