Содержание:
Lesson # 3. C# Theory
Lecture in pdf format
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]; names[0] = "Ivan"; names[1] = "Ann"; names[2] = "Mike"; // Process each name in the array. foreach (string name in names) { Console.WriteLine(name); } |
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 a Visual Studio IDE.
- Create a Console Application with a name
Lesson_3Lab1
: File → New → Project/Solution → Console Application. - In a Solution Explorer window find a
Program.cs
file 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 of 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 acounter
variable as a counter of theFOR
loop (you can also use the code snippet for + Tab(twice)): - Output the values of the
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 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 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
. 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
]
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 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
]
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
]
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
]
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
]
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
: File → New → Project/Solution → Console Application. - In the Solution Explorer window find a
Program.cs
file and rename it intoL3Lab2.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: ":
- 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 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.
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($"{outer} is prime"); } } ...
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
]
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
]