Содержание:
Lesson # 3. C# Theory
Repetitions | Loops
for loops
, while loops
, and do loops
. The for Loops
for ([initializers]; [condition]; [iterator]) { // code to repeat goes here }
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
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. } |
Labs and tasks
Console Applications
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
: File → New → Project/Solution → Console Application. - In the Solution Explorer window find a file
Program.cs
and rename it intoL3Lab1.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: - Assign the entered value to the variable
N
. ConvertN
to integer before using: - Create a for loop with
N
repetiotions. Use a variable with the namecounter
as a counter forFOR
loop (you can also use the code snippet for + Tab(twice)): - Output the values of the variable
counter
within the loop: - 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
thenCtrl+K
and thenCtrl+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
.
static void Main(string[] args) { Console.WriteLine("Please enter a number and press Enter"); } |
... int N = Int32.Parse(Console.ReadLine()); ...
... for(int counter = 1; counter <= N; counter++) { ... } ...
... for(int counter = 1; counter <= N; counter++) { Console.WriteLine($"Counter is at: {counter}"); } ...
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
]
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
]
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
]
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
]
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
]
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
]
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
: File → New → Project/Solution → Console Application. - In the Solution Explorer window find a file
Program.cs
and rename it intoL3Lab2.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: ":
- Declare two integer variables, the counters for the loops:
- Create an outer
for
loop with a counter calledouter
. 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)): - Create a nested
for
loop (within the previous loop) with a counter calledinner
. This loop has to check whether or not every number is a prime number. If it is, the prime has to be outputted: - 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
or5 × 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
thenCtrl+K
and thenCtrl+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.
static void Main(string[] args) { // lab 4 Console.WriteLine("Prime numbers: "); } |
... int outer; int inner; ...
... for (outer = 2; outer < 100; outer++) { ... } ...
... 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); } } ...
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 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:
- 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.
- 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).
- Place all the controls as it is given in the figure above.
- Give the proper names to all the controls, by selecting a control and using Property window. Use the table above to have the names.
- 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 andy
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: - Now, we can create nested loops to calculate the function
z(x,y) = x - y
. The outer loop will iterate over thex
range, and inner loop - over they
range. Continue theclick
event of the button: - 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 ofItems
collection of the list box: - Run the application, enter some values to text boxes and press the button.
- Now, let's consider the entered range was from bigger number to less number. In this case the error will occur.
- Add the following code to check the entered range before the loop:
- We've checked the range of
x
variable. Now add the same code to check the range ofy
variable. Do it yourself. - Run and debug the program.
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 |
private button1_Click(object sender, EventArgs e) { // here your code starts: fromX = .Parse(txtX1.Text); toX = .Parse(txtX2.Text); fromY = .Parse(txtY1.Text); toY = .Parse(txtY2.Text); //... }
//... for (int x = fromX; x <= toX; x++) { for (int y = fromY; y <= toY; y++) { // ... } }
//... 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 }
if (fromX > toX) { .Show("the range must be from less to bigger"); txtX1.Text = ""; txtX2.Text = ""; }
Show
method of MessageBox
class is used to inform user.To students of SFEDU: follow the hyperlink to watch the lesson in Teams