Содержание:
Lesson # 4. C# Theory
Lecture in pdf format
While Loops
while loop
enables you to execute a block of code while a given condition is true. For example, you can use a while loop to make user input until the user indicates that there is no more data to enter. The loop can continue to prompt the user until he decides to end the interaction by entering a special value. In this case, the special value is responsible for ending the loop.string answer = Console.ReadLine(); while (answer != "Quit") // "Quit" - is a special value to end the loop { // Process the data. answer = Console.ReadLine(); } |
answer = Console.ReadLine();
inside the loop braces. Failure to put this into the loop body will result in an infinite loop because the initial value can never be changed. Do..while Loop
do loop
is very similar to a while loop
, with the exception that a do loop
will always execute the body of the loop at least once. In a while loop
, if the condition is false from the start, the body of the loop will never execute.do loop
if you know that the code will only execute in response to a user prompt for data. In this case, you know that the application will need to process at least one piece of data, and can, therefore, use a do
loop.string answer; do { // Process the data. answer = Console.ReadLine(); } while (answer != "Quit"); |
Exceptions
- Exceptions are the best mechanism for error handling. An exception is thrown by a code with a run-time error, and caught by a code that can handle an error. If the exception is not handled by a program, then the program terminates with crash.
- An exception in C# is an object of an Exception class or some inherited class. Name of a class defines type of exception.
- The exceptions are handled in
try … catch
block. - When an exception appears inside
try block
, the program execution goes to the first appropriate exception handler –catch
block. - If there are no handlers for the created exception, the program terminates with an error message.
FormatException
class handles the exceptions. The exception that is thrown when the format of an argument does not meet the parameter specifications of the invoked method.
Example:
int a = 0; bool flag = false; do { try { string s = Console.ReadLine(); a = int.Parse(s); flag = true; } catch (FormatException e) { Console.WriteLine(e.Message + " Repeat input"); } } while (!flag); Console.WriteLine(a + " OK"); |
Another way of error handling is using of TryParse
procedure, which returns true
value if conversion is possible (it has output parameter to return the converted value):
int a = 0; string s = Console.ReadLine(); if (Int32.TryParse(s, out a)) { Console.WriteLine(a + " OK"); } else { Console.WriteLine("Wrong input"); } |
Labs and tasks
Console applications
To do: Ask user to enter a number (N
). Create a simple while
loop with N
repetitions that displays the values of the loop counter.
Expected output:
Please enter a number and press Enter 3 The result: Current value of counter is 1 Current value of counter is 2 Current value of counter is 3
Please enter a number and press Enter 1 The result: Current value of counter is 1
[Solution and Project name: Lesson_4Lab1
, file name L4Lab1.cs
]
✍ Algorithm:
- Open the Visual Studio.
- Create a Console Application with a name
Lesson_4Lab1
: File -> New -> Project/Solution -> Console Application. - In the Solution Explorer window find a
Program.cs
file and rename it intoL4Lab1.cs
. - Make sure that the
L4Lab1.cs
file 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 to enter a number (
ReadLine()
method): - Assign the entered value to the variable
N
. We’re not going to convertN
to integer because we’ll do it later. We’ll usevar
as a type, it we’ll be considered as a type of a value set to variable: - We start with
counter = 1
. Create awhile
loop withN
repetitions. Use acounter
variable as a counter forwhile
loop (or you can also use the code snippet while + 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 run the application. A console window will open asking you to enter an integer value.
- Experiment with different values to see the output. Pay attention to the output to see what the last value is, to ensure you understand how the evaluation of the condition is done and how the
while
loop executes. - Experiment with this by setting
counter
to a value greater thanN
and run the code. - 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
L4Lab1.cs
file. - ExtraTask: Think about how to check if entered data was a number. To make it possible you should use try...catch block or
TryParse()
procedure.
static void Main(string[] args) { Console.WriteLine("Please enter a number and press Enter"); } |
... int N = Int32. (Console.ReadLine()); ...
... int counter = 1; while (counter <= N) { counter++; } ...
counter
is less than N
or equal to N
, if so, the loop body code executes inside the loop, we output the value of counter
and then increment it by 1.... int counter = 1; while (counter <= N) { Console.WriteLine($"Current value of counter is {counter}"); counter++; } ...
To do: Create a simple do..while
loop with 5
repetitions that displays the values of the loop counter.
Expected output:
The result: Current value of counter is 1 Current value of counter is 2 Current value of counter is 3 Current value of counter is 4 Current value of counter is 5
[Solution and Project name: Lesson_4Lab2
, file name L4Lab2.cs
]
✍ Algorithm:
- Open the Visual Studio.
- Create a Console Application with the name
Lesson_4Lab2
: File -> New -> Project/Solution -> Console Application. - In the Solution Explorer window find a
Program.cs
file and rename it intoL4Lab2.cs
. - Make sure that the
L4Lab2.cs
file 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. - We start with
counter = 1
. Create ado..while
loop with5
repetitions. Use acounter
variable as a counter fordo..while
loop (or you can also use the code snippet do + Tab(twice)): - Output the values of the
counter
variable 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.
- Experiment with different values to see the output.
- 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 and upload the
L4Lab2.cs
file.
... int counter = 1; do { counter++; } while (counter <= 5); ...
counter
is less than N
or equal to N
, if so, the loop body code executes inside the loop, we output the value of counter
and then increment it by 1.... int counter = 1; do { Console.WriteLine($"Current value of counter is {counter}"); counter++; } while (counter <= 5); ...
To do: Output the sequence 3 5 7 9 ... 21
(from 3 to 21 with a step = 2). Make it twice: using while
and do..while
loops.
Note 1: Within one project create two loops: while
and do..while
loops with different counters (counter1
, counter2
).
Note 2: To output the result within one line you have to use the following method:
Console.Write(...); |
Expected output:
3 5 7 9 11 13 15 17 19 21
[Solution and Project name: Lesson_4Task1
, file name L4Task1.cs
]
To do: Output the sequence 15 12 9 6 3 0
(from 15 downto 0 with a step = -3). Make it twice: using while
and do..while
loops.
Note 1: Within one project create two loops: while
and do..while
loops with different counters (counter1
, counter2
).
Expected output:
15 12 9 6 3 0
[Solution and Project name: Lesson_4Task2
, file name L4Task2.cs
]
To do: Calculate a multiplication of 2-digit even integers in the interval [10;20] (10 * 12 * 14 * 16 * 18 * 20
). You should use a while
loop.
Note: To calculate a multiplication you have to use a variable with the name product
. Start with product = 1
.
Expected output:
10 * 12 * 14 * 16 * 18 * 20 = 9676800
[Solution and Project name: Lesson_4Task3
, file name L4Task3.cs
]
To do: Five real numbers are entered. Calculate an addition of the numbers. Make it using a while
loop.
Note 1: To solve this problem you should use the variables of double
type:
double sum = 0; double numb; |
Note 2: Don't forget to convert the values of inputted numbers into double
type:
numb=Double.Parse(Console.ReadLine()); |
Expected output:
Please enter 5 numbers and press Enter 1 4 2 9 2 The sum of inputted numbers = 18
[Solution and Project name: Lesson_4Task4
, file name L4Task4.cs
]
To do: An integer sequence is entered. The indication of completion of the sequence is 0
number entered (if 0
is entered the input of the numbers of the set is terminated). Output a minimum number of the sequence numbers. To make the program you have to use do..while
loop. It is not allowed to use standard min
function.
Expected output:
Please enter the sequence of numbers and finish with 0 3 5 1 0 the minimum number is 1
[Solution and Project name: Lesson_4Lab3
, file name L4Lab3.cs
]
✍ Algorithm:
- Open the Visual Studio.
- Create a Console Application with the name
Lesson_4Lab3
: File -> New -> Project/Solution -> Console Application. - In the Solution Explorer window find a
Program.cs
file and rename it intoL4Lab3.cs
. - Request user to enter the numbers:
- Declare a variable to store the entered nubmers. Call it
numb
. Inisialize amin
variable with the maximum value of integer type: - Create a
do..while
loop with a condition to check if entered number is not equal to0
: - Within the loop body you have to use
Console.ReadLine()
method and store entered numbers in thenumb
variable. Don't forget that it must be converted into integer: - Afterward you must test entered number if it is less than minimum and not equal to zero (because
0
means the end of the sequence): - Then, let's modulate a situation with an exception occured: as if the user enters text intead of a number. To handle the exception we'll use
try..catch
block: - Run the program and enter some string.
- Output the value of the minimum variable (
min
) after the loop body: - Press the
CTRL+F5
keys to start the application without debugging. - 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 and upload the
L4Lab3.cs
file.
... Console.WriteLine("Please enter the sequence of numbers and finish with 0"); ... |
... int numb; int min= int.MaxValue; ...
... do { ... } while (numb != 0); ...
while
, tests if numb
is not equal to 0
, if so, the loop body code executes inside the loop.... numb = Int32.Parse(Console.ReadLine()); ...
... numb = Int32.Parse(Console.ReadLine()); if (numb < min && numb!=0) { min = numb; } ...
try { do { numb = Int32.Parse(Console.ReadLine()); if (numb < min && numb != 0) { min = numb; } } while (numb != 0); } catch ( e) { Console.WriteLine(e.Message + " Repeat input"); }
... Console.WriteLine($"the minimum number is {min}"); ...
To do: A sequence of integers is entered. The indication of a completion of the sequence is 0
number (if 0
is entered the input of the numbers of the set is terminated). Output a maximum number of the sequence and its order number in the sequence. To make the program you have to use do..while
loop. It is not allowed to use standard max
function.
Expected output:
Please enter the sequence of numbers and finish with 0 3 5 1 0 the maximum number is 5, its position is 2
[Solution and Project name: Lesson_4Task5
, file name L4Task5.cs
]
Extra tasks
To do: Calculate the value of the function y = 4(x-3)6-7(x-3)3 + 2
for the entered value of x
. Use the auxiliary variable for (x-3)
. Make the program for 3 entered values of x
(you have to use loop).
Note: Include the following libraries not to print console
class and math
class:
using static System.Console; using static System.Math; |
Expected output:
Please enter a value of x 2 x=2;y=13 Please enter a value of x 3 x=3;y=2 Please enter a value of x 4 x=4;y=-1
[Solution and Project name: Lesson_4ExTask1
, file name L4ExTask1.cs
]
To do: The coordinates of the chess board field x
and y
(integers in the range 1-8) are given. It is known that the lower left square of the Board ((1, 1)) is black, check if it is a truth that: "This square is white" (using entered coordinates). Do not use the conditional operator.
Note: Include the following libraries not to print console
class and math
class:
using static System.Console; using static System.Math; |
Expected output:
Please enter x (1-8) 3 Please enter y (1-8) 4 This square is white: true
Please enter x (1-8) 3 Please enter y (1-8) 5 This square is white: false
[Solution and Project name: Lesson_4ExTask2
, file name L4ExTask2.cs
]
To do: Create the appropriate nested looping structure to output the characters in an 8 x 8
grid on the screen using Console.Write()
or Console.WriteLine()
as appropriate. Include a decision structure to ensure that alternate rows start with opposite characters as a real chess board alternates the colors among rows.
Expected output:
XOXOXOXO OXOXOXOX XOXOXOXO OXOXOXOX XOXOXOXO OXOXOXOX XOXOXOXO OXOXOXOX
[Solution and Project name: Lesson_4ExTask3
, file name L4ExTask3.cs
]