Будь умным!


У вас вопросы?
У нас ответы:) SamZan.net

Dimensionl rry n rry with rnk greter thn one is clled multidimensionl rry

Работа добавлена на сайт samzan.net: 2015-07-05

Поможем написать учебную работу

Если у вас возникли сложности с курсовой, контрольной, дипломной, рефератом, отчетом по практике, научно-исследовательской и любой другой работой - мы готовы помочь.

Предоплата всего

от 25%

Подписываем

договор

Выберите тип работы:

Скидка 25% при заказе до 30.4.2024

Lesson 5: Arrays

An array is a data structure that contains a number of variables, which are accessed through computed indices. The variables contained in an array, also called the elements of the array, are all of the same type, and this type is called the element type of the array.

An array has a rank that determines the number of indices associated with each array element. The rank of an array is also referred to as the dimensions of the array. An array with a rank of one is called a single-dimensional array. An array with a rank greater than one is called a multi-dimensional array. Specific sized multidimensional arrays are often referred to as two-dimensional arrays, three-dimensional arrays, and so on.

Each dimension of an array has an associated length that is an integral number greater than or equal to zero. The dimension lengths are not part of the type of the array, but rather are established when an instance of the array type is created at run-time. The length of a dimension determines the valid range of indices for that dimension: For a dimension of length N, indices can range from 0 to N–1 inclusive. The total number of elements in an array is the product of the lengths of each dimension in the array. If one or more of the dimensions of an array have a length of zero, the array is said to be empty.

The element type of an array can be any type, including an array type.

Array creation

Array instances are created by array-creation-expressions or by field or local variable declarations that include an array-initializer.

When an array instance is created, the rank and length of each dimension are established and then remain constant for the entire lifetime of the instance. In other words, it is not possible to change the rank of an existing array instance, nor is it possible to resize its dimensions.

An array instance is always of an array type. The System.Array type is an abstract type that cannot be instantiated.

Elements of arrays created by array-creation-expressions are always initialized to their default value.

Single-Dimensional Arrays

You can declare a single-dimensional array of five integers as shown in the following example:

int[] array = new int[5];

This array contains the elements from array[0] to array[4]. The new operator is used to create the array and initialize the array elements to their default values. In this example, all the array elements are initialized to zero.

An array that stores string elements can be declared in the same way. For example:

string[] stringArray = new string[6];

Array Initialization

It is possible to initialize an array upon declaration, in which case, the rank specifier is not needed because it is already supplied by the number of elements in the initialization list. For example:

int[] array1 = new int[] { 1, 3, 5, 7, 9 };

A string array can be initialized in the same way. The following is a declaration of a string array where each array element is initialized by a name of a day:

string[] weekDays = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

When you initialize an array upon declaration, you can use the following shortcuts:

int[] array2 = { 1, 3, 5, 7, 9 };

string[] weekDays2 = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

It is possible to declare an array variable without initialization, but you must use the new operator when you assign an array to this variable. For example:

int[] array3;

array3 = new int[] { 1, 3, 5, 7, 9 };   // OK

//array3 = {1, 3, 5, 7, 9};   // Error

Multidimensional Arrays

Arrays can have more than one dimension. For example, the following declaration creates a two-dimensional array of four rows and two columns.

int[,] array = new int[4, 2];

The following declaration creates an array of three dimensions, 4, 2, and 3.

int[, ,] array1 = new int[4, 2, 3];

Array Initialization

You can initialize the array upon declaration, as is shown in the following example.

// Two-dimensional array.

int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };

// Same array with dimensions specified.

int[,] array2Da = new int[4, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };

// Three-dimensional array.

int[, ,] array3D = new int[,,] { { { 1, 2, 3 }, { 4, 5, 6 } }, { { 7, 8, 9 }, { 10, 11, 12 } } };

// Same array with dimensions specified.

int[, ,] array3Da = new int[2, 2, 3] { { { 1, 2, 3 }, { 4, 5, 6 } }, { { 7, 8, 9 }, { 10, 11, 12 } } };

// Three-dimensional array.

int[, ,] array_3D = new int[,,] { { { 1, 2 }, { 3, 4 }, { 5, 6 } },

                                 { { 7, 8 }, { 9, 10 }, { 11, 12 } } };

// Same array with dimensions specified.

int[, ,] array_3Da = new int[2, 3, 2] { { { 1, 2 }, { 3, 4 }, { 5, 6 } },

                                       { { 7, 8 }, { 9, 10 }, { 11, 12 } } };

You also can initialize the array without specifying the rank.

int[,] array4 = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };

If you choose to declare an array variable without initialization, you must use the new operator to assign an array to the variable. The use of new is shown in the following example.

int[,] array5;

array5 = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };   // OK

//array5 = {{1,2}, {3,4}, {5,6}, {7,8}};   // Error

The following example assigns a value to a particular array element.

array5[2, 1] = 25;

Similarly, the following example gets the value of a particular array element and assigns it to variable elementValue.

int elementValue = array5[2, 1];

The following code example initializes the array elements to default values (except for jagged arrays).

int[,] array6 = new int[10, 10];

Jagged Arrays

A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array of arrays." The following examples show how to declare, initialize, and access jagged arrays.

The following is a declaration of a single-dimensional array that has three elements, each of which is a single-dimensional array of integers:

int[][] jaggedArray = new int[3][];

Before you can use jaggedArray, its elements must be initialized. You can initialize the elements like this:

jaggedArray[0] = new int[5];

jaggedArray[1] = new int[4];

jaggedArray[2] = new int[2];

Each of the elements is a single-dimensional array of integers. The first element is an array of 5 integers, the second is an array of 4 integers, and the third is an array of 2 integers.

It is also possible to use initializers to fill the array elements with values, in which case you do not need the array size. For example:

jaggedArray[0] = new int[] { 1, 3, 5, 7, 9 };

jaggedArray[1] = new int[] { 0, 2, 4, 6 };

jaggedArray[2] = new int[] { 11, 22 };

You can also initialize the array upon declaration like this:

int[][] jaggedArray2 = new int[][]

{

   new int[] {1,3,5,7,9},

   new int[] {0,2,4,6},

   new int[] {11,22}

};

You can use the following shorthand form. Notice that you cannot omit the new operator from the elements initialization because there is no default initialization for the elements:

int[][] jaggedArray3 =

{

   new int[] {1,3,5,7,9},

   new int[] {0,2,4,6},

   new int[] {11,22}

};

A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null.

You can access individual array elements like these examples:

// Assign 77 to the second element ([1]) of the first array ([0]):

jaggedArray3[0][1] = 77;

// Assign 88 to the second element ([1]) of the third array ([2]):

jaggedArray3[2][1] = 88;

It is possible to mix jagged and multidimensional arrays. The following is a declaration and initialization of a single-dimensional jagged array that contains three two-dimensional array elements of different sizes. For more information about two-dimensional arrays, see Multidimensional Arrays.

int[][,] jaggedArray4 = new int[3][,]

{

   new int[,] { {1,3}, {5,7} },

   new int[,] { {0,2}, {4,6}, {8,10} },

   new int[,] { {11,22}, {99,88}, {0,9} }

};

You can access individual elements as shown in this example, which displays the value of the element [1,0] of the first array (value 5):

System.Console.Write("{0}", jaggedArray4[0][1, 0]);

The method Length returns the number of arrays contained in the jagged array. For example, assuming you have declared the previous array, this line:

System.Console.WriteLine(jaggedArray4.Length);

returns a value of 3.

Example. This example builds an array whose elements are themselves arrays. Each one of the array elements has a different size.

class ArrayTest

{

static void Main()

{

// Declare the array of two elements:

int[][] arr = new int[2][];

// Initialize the elements:

arr[0] = new int[5] { 1, 3, 5, 7, 9 };

arr[1] = new int[4] { 2, 4, 6, 8 };

// Display the array elements:

for (int i = 0; i < arr.Length; i++)

{

System.Console.Write("Element({0}): ", i);

for (int j = 0; j < arr[i].Length; j++)

{

System.Console.Write("{0}{1}", arr[i][j], j == (arr[i].Length - 1) ? "" : " ");

}

System.Console.WriteLine();            

}

// Keep the console window open in debug mode.

System.Console.WriteLine("Press any key to exit.");

System.Console.ReadKey();

}

}

/* Output:

   Element(0): 1 3 5 7 9

   Element(1): 2 4 6 8

*/

Arrays

An array is a data structure that contains several variables of the same type. An array is declared with a type:

type[] arrayName;

The following examples create single-dimensional, multidimensional, and jagged arrays:

class TestArraysClass

{

   static void Main()

   {

       // Declare a single-dimensional array

       int[] array1 = new int[5];

       // Declare and set array element values

       int[] array2 = new int[] { 1, 3, 5, 7, 9 };

       // Alternative syntax

       int[] array3 = { 1, 2, 3, 4, 5, 6 };

       // Declare a two dimensional array

       int[,] multiDimensionalArray1 = new int[2, 3];

       // Declare and set array element values

       int[,] multiDimensionalArray2 = { { 1, 2, 3 }, { 4, 5, 6 } };

       // Declare a jagged array

       int[][] jaggedArray = new int[6][];

       // Set the values of the first array in the jagged array structure

       jaggedArray[0] = new int[4] { 1, 2, 3, 4 };

   }

}

Using foreach with Arrays

C# also provides the foreach statement. This statement provides a simple, clean way to iterate through the elements of an array. For example, the following code creates an array called numbers and iterates through it with the foreach statement:

int[] numbers = { 4, 5, 6, 1, 2, 3, -2, -1, 0 };

foreach (int i in numbers)

{

   System.Console.Write("{0} ", i);

}

// Output: 4 5 6 1 2 3 -2 -1 0

With multidimensional arrays, you can use the same method to iterate through the elements, for example:

int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } };

// Or use the short form:

// int[,] numbers2D = { { 9, 99 }, { 3, 33 }, { 5, 55 } };

foreach (int i in numbers2D)

{

   System.Console.Write("{0} ", i);

}

// Output: 9 99 3 33 5 55

VARIANTS

Task 1. One-dimensional arrays

1) Write a program that fills in an array of 8 elements with numbers in the decreasing order.

2) Write a program that a program that fills in an array of 8 elements with numbers in the ascending order.

3) Write a program that a asks user to type in elements of an array and deletes all numbers that are equal to 0 from the array.

4) Write a program which will ask a user to enter numbers for A array and which will output all negative numbers and numbers that are less than 50.

5) Write a program which will ask a user to enter numbers for B array and which will output all even numbers and numbers ending with 0.

6) Write a program that asks a user to type 10 integers and writes how many times the biggest value occurred.

7) Write a program that asks a user to type n integers and prints out a number of negative numbers and all of the negative numbers in the next line.

8) Write a program that shows the output array of 10 numbers. It must ask which numbers you want to delete and then print out a new array.

9) Write a program that asks a user to type n integers and prints out a number of positive numbers and all of the positive numbers in the same line in brackets.

10) Write a program that asks a user to enter two arrays A and B and outputs A∩B.

11) Write a program that asks a user to enter two arrays A and B and outputs AUB.

12) Write a program that searches an array of ten integers for duplicate values. Make the program display each duplicate found.

13) Aerosvit Airlines provides flights from Kyiv to six other cities in Ukraine. The cities are referred to by number, 1 to 6. The price of a round-trip ticket to each city is shown here.

City

1

2

3

4

5

6

Price

56.79

105.69

93.49

155.99

87.49

73.99

Write a program that computes the total price of tickets ordered by a customer. The program should prompt the user for the number of the destination city and the number of tickets desired. If the user enters an invalid city number, the program should display an error message and terminate. The program should display the total price of the ticket order. Use an array to store the ticket price table.

14) Write a program that prompts the user to enter a ten-element array and displays the array. Then, the program must use the bubble sort to sort the array in the increasing order and display the sorted array.

15) Write a program that finds roots of the equation Ax + Bsin = 0, where  = 1.3, A = {1.1, 2.5, 3.9, 8.1, 4.5, 12.1, 11.9, 15.5}.

  (i = 1..8).

16) Write a program that calculates the following array: , where is positive root of the equation Ax + Bcos = 0, with А = 0.75, B = 4.5,  = -1.5 .. 2.5, .

17) Write  a  program  that  sums  of  all  positive  elements  of an  array  A = {-1.2, 3.5, 4.1, 8.5, 5.3, -6.1, 3.4, 2.7}.

18) Write a program that finds product of elements of an array A = {1, 3.5, 4, -0.8, 1.9, 5, 13} which satisfies the following condition , if  С = 2, D = 10.

19) . Write a program that calculates

with Y = -5.5, X = {-1.8, -1.6, ... , 1.2}. The result should be presented in the form of an array.

20) Write a program that finds numbers of the first odd and the last even numbers of an array N = {10, 8, 4, 3, 6, 15, 2}.

21) Write a program that prompts a user to enter a ten-element array and displays the array. Then, the program must use the bubble sort to sort the array in the decreasing order and display the sorted array.

22) Write a program that  finds the difference between the maximum and K-th element of an array А = {-1.1, 2.5, -2.9, 8.8, 14.5, 2.2, -1.3, 5.9} if К = 4.

23) Write a program that calculates the element of an array

 

where x – the roots of a series of equations Аx + sin(i) = 0, ,

А = 5.5.

24) Write a program that sums of the first К positive elements of an array А = (2.8, -3.5, -2.1, 4, 6, 8.1, 6.2, 9.5, 1.1). К = 5.

25) Write a program that  finds a product of the last N negative elements of an array  А = (-5, 6.1, -9.2, 4, 5, -2, 7, -1, 5, 4, 1.9, -3, 5); N = 3.

26) Create an array , even elements of the array are equal to the elements of an array А = (-5.1, 2.3, 4.6, 5.8, -2.9), odd ones to the elements of an array В = (2.8, 3, 5.4, -1.9, -4.1).

27) Find the amount of positive, negative elements and elements equal to 0 of an array М = (-5, 0.1, 2.8, 0.64, 3, -5.1, 0, -7.5, 4.6, 10).

28) Calculate where х = , an array, its elements are the remainders of the division of the entire array N = (156, 18, 72, 10, 95, 100) into an integer number К = 9.

29) Calculate , where and are maximum and minimum elements of an array А = (5.5, -6, 8, 9.1, -3.5, 4.1, 10, -1, 2.5) respectively; – arithmetic mean of and .

30) A survey organization telephones 20 homes and records the household income of each family surveyed. Write a program that inputs the 20 incomes into an array and then sorts the array in the decreasing order. The program should display the following statistics: the maximum income, the minimum income, the average income, and the median income. The median of a set of sorted numbers is the middle number, if there is an odd number of numbers. If there is an even number of numbers, the median is the average of the two middle numbers.

Task 2. Multidimensional array

1) Write a program that reads in a real matrix 10x10 and finds the smallest element in the main diagonal and the smallest element in the secondary diagonal.

2) Write your own C program that transposes matrix. Program stores given matrix dimensions. Every single matrix element must be entered. Transposed matrix is the one with rows and columns switched.

3) Write your own C program that stores a real matrix 10x10, and finds the sum of elements in every column and product of elements in every row. The program prints the smallest sum (including parent column’s index), and the biggest product (including parent row’s index). Sums and products should be stored in one-dimensional arrays.

4) Maximal numbers of rows and columns of a matrix is predefined. Write your own main program which reads in a given number of rows and columns and, additionally, given elements. The main program prints: sum on the elements of the elements of the matrix (calls upon a function that calculates sum of elements)

5) Maximal numbers of rows and columns of a matrix is predefined. Write your own main program which reads in a given number of rows and columns and, additionally, given elements. Main program prints the maximal value of every row of a matrix (calls upon a function that finds the biggest element in a row)

6) Write a program that adds two matrices those dimensions and elements are input by a user, and then prints out the result.

7) An array A(m,n) is given. Write a program that creates an array В of the smallest elements of each row of the array.

8) An array В(m,n) is given. Write a program that creates an array C(n) of the sums of each column of the array B.

9) An array E(m,n) is given. Write a program that changes places of elements in the i-th and k-th rows:

10) Write a program that divides all elements of an array Р(m,n) into the maximum number of k-th column:

11) An array A(m,n) is given. Create an array С of elements of even columns and an array В of elements of odd rows of the array А:

12) An array A(m,n) is given. Create one-dimentional arrays В and С containing odd and even elements of the array A respectively:

13) Create an array В of element products of the columns of an array Z:

14) Create an array Т of the sum of elements situated in rows with negative elements on the main diagonal of the original array Z:

15) Create an array NS of rows’ numbers of an array R, where duplicated values are:

16) An array Q(m,n) is given. Replace negative elements of the array by the number of the column where they are situated:

17) Create a one-dimensional array B of elements of an array A that are smaller than Е:

18) Create a one-dimensional array B of elements that are situated below the main diagonal of an original array К:

19) An array V(n,n) is given. Replace the greatest elements of each row by s:

20) An array H(n,n) is given. Convert the array by dividing of all elements by the maximum element of K-th row:

21) Find the difference R between the maximum and minimum elements of an array W:

22) An array A(m,n) is given. Create an array B of positive elements of an array A:

, m = 2, n = 3.

23) An array G(m,n) is given. Convert the array by replacing elements of K-th and (К+1)-th columns:

24) An array D(m,n) is given. Add the value S to negative elements of the array and subtract value X out of positive elements:

25) Replace all positive elements in an array F(n,m) by their squares and all negative – by their cubes.

26) Create an array R of numbers of rows of an array Y(m,n) (those rows which have maximum element):

27) Create an array K of positive proportions of elements of n-th and s-th columns of the array:

28) Create a one-dimensional array B of the elements of А(n,n) array that are greater then C:

29) Create a one-dimensional array T of the elements of W(n,n) array that are smaller then D:

30) Create a one-dimensional array T of elements of an array A that are smaller than G:




1. Str Prestige Goldбазовая комплектация 1 шт
2. Полная конвертируемость рубля за два года
3. реферат дисертації на здобуття наукового ступеня кандидата педагогічних наук Лу
4. Конституционный Суд РФ в системе органов государственной власти
5. Червона могила Начало формы Було то вже дуже давно
6. опера Історія розвитку
7. Отчет о прибылях и убытках 2
8. География ЮАР
9. ДОСКА- РАССКАЗ УСТНО- Права доступа к информации совокупность правил регламентирующих порядок.
10. он уверяет что это не так утомительно как по городским улицам
11. выделяемые монопольно используемые неперераспределяемые ресурсы характеризуются тем что выделяю
12. тематику и историю что ему дало прочный фундамент знаний для работы в области теоретической экономии
13. Сетевое распространение товара
14. А Антуан ldquo;маленький принцrdquo; Б Полеты Антуана Творчество писателя А Повести о крылатых лю
15. История Акушерства
16. Тема 17 Охоронна діяльність Правове регулювання охоронної діяльності в Україні Департамент УДСО т
17. ЛЕКЦИЯ 33 Ведущие капиталистические страны Превращение США в ведущую мировую державу
18. на тему- ПОРТФЕЛЬ ИНВЕСТИЦИЙ МЕТОДЫ ЕГО ФОРМИРОВАНИЯ И ОЦЕНКА Выполнила- студентка 4 курса фин
19. Тема 5 УПРАВЛІНСЬКЕ КОНСУЛЬТУВАННЯ І БІЗНЕС Специфіка найму і роботи штатних та зовнішніх управлінськ
20. Соціологія релігії