Содержание:
Lesson # 7. Theory
Lecture in pdf format
Arrays in Visual C# have the following features:
- Every element in the array contains a value.
- Arrays are zero-indexed, that is, the first item in the array is element 0.
- The size of an array is the total number of elements that it can contain.
- Arrays can be single-dimensional, multidimensional, or jagged.
- The rank of an array is the number of dimensions in the array.
Creating and Using Single-Dimensional Arrays
The following code example shows how to create a single-dimensional array of integers with elements zero through nine:
int[] arrayName = new int[10]; |
Accessing Data in an Array
The following code example uses an index to access the element at index two:
//Accessing Data by Index int[] oldNumbers = { 1, 2, 3, 4, 5 }; //number will contain the value 3 int number = oldNumbers[2]; |
The following code example shows how to use a for loop
to iterate through an array:
//Iterating Over an Array int[] oldNumbers = { 1, 2, 3, 4, 5 }; for (int i = 0; i < oldNumbers.Length; i++) { int number = oldNumbers[i]; ... } |
Samples
- Let’s look at the example of the initializing the array of five elements of byte type with random values:
- Create Console Application with the name
Lesson_7Lab1
. - In the Solution Explorer window find a file
Program.cs
and rename it intoL7Lab1.cs
. - In order not to print always the class
Console
, we can include its declaring right at the beginning of the editor window: - Within the
Main()
function create a single-dimensional array of integers with the namea
and assign the values for its elements: - Under the
Main()
function create a method with the namePrint
with one parameter:arr
parameter of int type to accept the values of the array elements. The function doesn’t return any value (void
): - Within the
Main
function call the method to output the elements. And run the code to see the output. - To collapse the code of the method for a while you can use
Ctrl+M (twice)
. To expand it again use the same shortcut snippetCtrl+M (twice)
. - Now you have to create the
CountOddPositive
function which accepts the array as a parameter and has two more ref parameters to pass the values of the counters for positive and odd elements (countPos
andcountOdd
) : - Within the function use
foreach
loop to iterate through the array and check the elements: - Ref parameters have to be initialized before the calling of the method. Let’s do it in the
Main
function: - After this, call this method within the
Main
function, passing the array to theCountOddPositive
function as one of the arguments: - Output the result:
- Run the program by pressing
CTRL+F5
to see the output. - Create Console Application with the name
Lesson_7Lab2
. In the Solution Explorer window find a fileProgram.cs
and rename it intoL7Lab2.cs
. - In order not to print always the class
Console
, we can include its declaring right at the beginning of the editor window: - Within the
Main()
function declare a single-dimensional array with a length of 10 elements: - Under the
Main()
function create a method with the nameFillRandomArray
with three parameters:arr
parameter of int type to accept the empty array,minValue
parameter of int type to set the lower bound for the functionRandom
, andmaxValue
parameter of int type to set the upper bound for the functionRandom
. The function doesn’t return any value (void
): - Within the created function instantiate random number generator using system-supplied value as seed:
- Generate and display random integer values of the array, using the boundaries (parameters
minValue
andmaxValue
) : - Call this method (
FillRandomArray
) within theMain
function, passing the array as one of the arguments, and boundaries -10 and 15 for the random as it is given in the task: - Create a method named
PrintArray
with one parameter:arr
parameter of int type to accept the values of the array elements. The function doesn’t return any value (void
) and displays the elements of the array : - Call this method (
PrintArray
) within theMain
function, passing the array as an argument: - To collapse the code of the method for a while you can use
Ctrl+M (twice)
. To expand it again use the same shortcut snippetCtrl+M (twice)
. - Now you have to create the function
DivisibleBy3
, that looks for the array elements that are divisible by 3 and displays them. - Call this method (
DivisibleBy3
) within theMain
function, after calling two previous methods: - Run the program by pressing
CTRL+F5
to see the output. - Add comments with the task and save the project. Download file
.cs
to the moodle system.
public static void Main() { //We declare the array variable in the same way as we previously declared variables of other types. //The type of the array of numbers is int[]. Similarly, there are types string[], double[], etc. int[] array; int number; //We initialize the variable array - the new array with a length 3. array = new int[3]; number = 10; // We get access to the elements of the array array[0] = 1; array[1] = 2; array[2] = 3; //An array, like other types, has its own properties and methods Console.WriteLine(array.Length); //Выведет 3 //Note that array.ToString() has not good results: Console.WriteLine(array.ToString()); // "System.Int32[]" will be outputted //The next code will arise an exception - going beyond array boundaries Console.WriteLine(array[100]); var array2 = new[] { 1, 2, 3 }; //how to use a for loop to iterate through an array: for (int i = 0; i < array2.Length; i++) Console.WriteLine($"{array2[i] }"); // but it is better to use foreach operator //foreach is recommended for c# foreach (var e in array2) Console.WriteLine(e); //But sometimes, in a case when assigning the values of an array, the foreach operator will be not suitable. for (int i = 0; i < array2.Length; i++) array2[i] = 2 * i; } |
Random function
1. Instantiate random number generator using system-supplied value as seed:
var rand = new Random(); |
2. Generate and display 5 random byte (integer) values:
var bytes = new byte[5]; rand.NextBytes(bytes); Console.WriteLine("Five random byte values:"); // output: foreach (byte byteValue in bytes) Console.Write("{0, 5}", byteValue); Console.WriteLine(); |
Labs and tasks
To do: An array of integers is given (the values of its elements: -1
, -2
, 3
, 4
, 5
, 6
, 7
). Output the array using a function. Create one more function to calculate the number of odd elements in this array, as well as the number of positive elements in it.
Note 1: Create a function named Print
to output the array’s elements.
Note: Create a function CountOddPositive
with foreach
loop and if
statements to check to see if an element is odd or positive.
Expected output:
Array: -1, -2, 3, 4, 5, 6, 7 number of odd elements: 5, number of positive elements 5.
[Solution and Project name: Lesson_7Lab1
, file name L7Lab1.cs
]
🎦
✍ How to do:
... using static System.Console; ... |
... -1, -2, 3, 4, 5, 6, 7 }; ...[] a = new [] {
static Print( [] arr) { WriteLine("Array:"); foreach (var x in arr) Write(x + " "); WriteLine(); }
... Print(a); |
... static CountOddPositive( [] arr, ref countOdd, ref countPos) { } ...
... static void CountOddPositive( int[] arr, ref int countOdd, ref int countPos) { foreach (var x in arr) { if (x % 2 != 0) countOdd++; if (x > 0) countPos++; } } ...
... 0; countOdd = 0; ...countPos =
... CountOddPositive(a, ref countPos, ref countOdd); ...
... WriteLine($"number of odd elements: {countOdd}, number of positive elements {countOdd}."); ...
To do: An array of doubles is given (the values of its elements: 1.1
, -2.3
, 3.7
, 4.1
, 5.6
, 6.1
, 7.1
).
1. Create a function to print the array.
2. Create one more function to find and print a minimum and maximum elements of this array. Note, that it is not allowed to use the standard min
and max
functions.
Note 1: To remember how to find a minimum and maximum, take a look at lab 4 of 5-th lesson.
Note 2: Create a function named Print
to output the array’s elements.
Note 3: Create a function FindMaxMin
with foreach loop and if statements to find maximum and minimum elements. The signature of the function should look like this:
static void FindMaxMin(double[] arr, ref double max, ref double min) { } |
Expected output:
Array: 1.1 -2.3 3.7 4.1 5.6 6.1 7.1 maximum element is: 7.1, minimum element is: -2.3
[Solution and Project name: Lesson_7Task1
, file name L7Task1.cs
]
To do:
1. Create a function with the name FillRandomArray
to fill an array of 10 elements with random numbers in the range from -10 to 15.
2. Create another function PrintArray
to output the array.
3. Create the function DivisibleBy3
to count and output the elements divisible by 3.
Expected output:
Array: -1, -2, 3, 4, 5, 6, 7, 12, 9, 10 elements divisible by 3: 3 6 12 9 number of elements divisible by 3: 4
[Solution and Project name: Lesson_7Lab2
, file name L7Lab2.cs
]
✍ How to do:
... using static System.Console; ... |
... new [10]; ...[] arr =
... static FillRandomArray( [] arr, minValue = -10, maxValue = 15) { //... } ...
Random rand = new Random();
... for ( i = 0; i < arr.Length; i++) { arr[i] = rand.Next(minValue, maxValue); }
... FillRandomArray(arr, -10, 15); ...
static void PrintArray(int[] arr) { for (int i = 0; i < arr.Length; i++) { Write($"{arr[i]} "); } }
PrintArray(arr);
static DivisibleBy3( [] arr) { counter = 0; WriteLine("elements divisible by 3:"); for ( i = 0; i < arr.Length; i++) { if (arr[i] % 3 == 0) { Write($"{arr[i]} "); counter++; } } WriteLine(); WriteLine($"number of elements divisible by 3: {counter}"); }
... DivisibleBy3(arr);
🎦
To do: An array of integers is given (15 elements with random values in the range from 1 to 10). Find if there is an element equal to N
in the array (N
is inputted). Output «yes» or «no» only once. To find the element use foreach
loop.
1. Create the functions to fill the array and output it’s elements.
2. Create one more function FindN
to find an element equal to N
(N is one of the parameters of the function).
Note 1: To stop a loop iterations the break
statement is required:
foreach (int x in arr) { if (...) { ... break; // exit loop } } |
Note 2: To check to see if the number was found you can create boolean variable:
bool f = false; |
Expected output:
Array: 9 5 1 3 7 7 8 1 4 4 input a number to look for: 6 result: no
Array: 2 6 2 6 8 1 9 1 7 2 input a number to look for: 2 result: yes
Extra task: Find the index of the found element.
[Solution and Project name: Lesson_7Task2
, file name L7Task2.cs
]
🎦
To do: An array of doubles is given (10 elements with random values in the range from -5.0
to 5.0
).
1. Create the functions to fill the array and output it’s elements.
2. Create one more function to calculate and print the sum of triples of adjacent elements: a[1]+a[2]+a[3]
, a[2]+a[3]+a[4]
, a[3]+a[4]+a[5]
, …… , a[8]+a[9]+a[10]
.
Note 1: To generate double values of the array, using the boundaries:
//For example, in the range from -20 to 20: Random rand = new Random(); ... a[i]=rand.NextDouble() * 40 - 20; |
Note 2: To output doubles with a number of signs after decimal point:
// two signs after point Write("{0:0.00} ",arr[i] ); // e.g. 1.21 |
Expected output:
Array: -3,54 0,51 3,79 1,85 -4,11 -2,32 -1,35 -0,78 0,63 4,31 sums of the triples: 0,76 6,15 1,53 -4,59 -7,79 -4,46 -1,50 4,16
[Solution and Project name: Lesson_7Task3
, file name L7Task3.cs
]