CSI 2290 - Chapter 3: Arrays

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

What is significant to remember about initializing arrays during declaration?

*It is a compiler error to specify more values than there are elements in the array *Can omit the size of the array during init --> compiler will allocate enough space for all the init elements *If number of values provided is less than number of elements in the array, the un-assigned elements are filled with zeros.

What operations can be performed on arrays?

- Traversing an array - Inserting an element into the array - Searching an element in an array - Deleting an element from an array - Merging two arrays - Sorting an array in ascending or descending order

When must an array be declared? What does declaring an array mean?

-An array must be declared before being used - Declaring an array means specifying: - Data type: kind of values it can store - Name: to identify the array - Size: maximum number of values that the array can hold

Array indices start at ______.

0

What is the algorithm used to delete an element from the end of an array?

1. Decrement the value of the upper bound (upper bound = upper bound - 1)

What is the algorithm used to add an element to the end of an array?

1. Increment the value of the upper bound (upper bound = upper bound + 1) 2. New value is stored at new position pointed by upper_bound (A[upper_bound] = val)

What are the 3 ways used to store values in an array?

1. Initialize the array elements during declaration 2. Input values for individual elements from the keyboard 3. Assign values to individual elements

What is the process you need to follow in order to traverse elements of an array?

1. Initialize the index to the lower bound of the array. 2. Execute a while loop 3. Process the individual array element as specified by the array name and index value. 4. Increment the index value so that the next array element can be processed 5. While loop is executed until all elements in the array are processed - until index is less than or equal to upper bound

In what ways can you pass a 2D array to a function? How does this compare to the methods used to pass a 1D array to a function?

1. Pass individual elements of the array --> same as passing element of 1D array 2. Pass a single row of the 2D array --> equivalent to passing the entire 1D array to a function 3. Pass the entire 2D array to the function

In the case of a 2D array, in order to evaluate the expression, *(*(mat + i) + j), what values must you know?

1. The address of the first element of the array, which is given by the name of the array, i.e. mat. 2. The size of the type of the elements of the array, i.e.,size of integer s in this case. 3. The specific index value for the row 4. The specific index value for the column

What does the merged array contain?

Contains the contents of the first array followed by the contents of the second array

What is an array?

A collection of similar data elements where data elements have the same type, elements are stored in consecutive memory locations, and elements are referenced by an index.

What is the different between a for loop and a while loop?

A for loop executes a block of code over and over again until a certain condition is met. A while loop will execute as long as a certain condition remains true. As soon as it becomes false, the loop is exited.

How do you pass a row of a 2D array to a function?

A row of 2D array can be passed by indexing the array name with the row number

What does traversing an array mean?

Accessing each and every element of the array for a specific purpose. Processing each array element sequentially from first to last

How do you insert an element at the end of an existing array?

Add 1 to upper bound and assign the value, assuming that the memory space allocated for the array is still available *Can't add element to it if all elements of the array are already declared

What is the formula used to calculate the address of other elements based on the base address?

Address of data element, A[k] = BA(A) + w(k-lower_bound) -A is the array - k is the index of the element of which we have to calculate the address - BA is the base address of the array A - w is the size of one element in memory

How do you calculate the address of the other elements if the array elements are stored in column major order?

Address(A[I][J]) = Base_Address + w{M (J - 1) + (I - 1)} *w is the number of bytes required to store 1 element *N is the number of columns *M is the number of rows *I and J are the subscripts of the array element

How do you calculate the address of the other elements if the array elements are stored in row major order?

Address(A[I][J]) = Base_Address + w{N (I - 1) + (J - 1)} *w is the number of bytes required to store 1 element *N is the number of columns *M is the number of rows *I and J are the subscripts of the array element

What is a two-dimensional array?

An array that contains mxn data elements and each element is accessed using 2 subscripts, i and j. i<= m and j<= n. *The first subscript denotes the row and the second denotes the column

How does C know where an individual element of an array is located in the memory?

Array name is a symbolic reference to address of the first byte of the array. When we use the array name, we are actually referring to the first byte of the array.

How do you initialize arrays by assigning values to individual elements?

Assign values of indv elements of array using the assignment operator. Any value that evaluates to the data type as that of the array can be assigned to the individual array element. ex) marks[3] = 100

What is the base address and why is storing just the base address sufficient?

Base address is the address of the first element in the array. It is sufficient to only store the base address since an array stores all its data elements in consecutive memory.

Why is traversing the elements of an array simple and straight forward?

Because an array is a linear data structure meaning all its elements form a sequence

When we pass an entire array to a function, why can we simply pass the name of the array?

Because the array name refers to the first byte of the array in the memory. The address of the remaining elements in the array can be calculated using the array name and the index value of the element.

Why can you write ptr = arr and not arr = ptr?

Because while ptr is a variable, arr is a constant. The location at which the first element of arr will be stored cannot be changed once arr[] has been declared.

How do you copy an array?

By copying the value of every element in the first array into the elements of the second array ex) int i, arr1[10], arr2[10]; arr1[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} for (i=0; i<10 ; i++) arr2[i] = arr1[i];

How do you pass a sub array to a function?

By declaring the element in the array that you want to start from and the size of the sub array. EX) If there are 10 elements in the array and we want to pass the array starting from the third element, then only 8 elements would be part of the sub-array. func(&arr[2], 8);

How do you initialize arrays with input from the keyboard?

By executing a while, do-while, or for loop to input the value for each element of the array ex) int i, marks[10]; for (i=0; i<10; i++) scanf("%d", &marks[i]);

How can individual elements of an array be passed?

By passing either their data values or addresses.

How do you initialize the entire 2D array to zeroes?

By specifying the first value as zero EX) int marks[2][3] = {0};

How do you delete an element from the end of an existing array?

By subtracting 1 from the upper bound

How do you access all elements of the array with the pointer variable?

By using the expression : array_name + index

If a pointer variable holds the address of the first element in the array, how is the address of the successive elements calculated?

By writing p++ int *ptr = &arr[0]; ptr++;

What is the syntax used to pass a row of a 2D array to a function?

Calling function: main() { int arr[2][3] = ({1,2,3}, {4,5,6}); func(arr[1]); } Called function: void func(int arr[]) { int i; for (i=0; i<3; i++) printf("%d", arr[1] *10); )

What is the code used to pass individual elements by their addresses?

Calling function: main() { int arr[5] = {1, 2, 3, 4, 5} func(&arr[3]); } Called function: void func(int *num) { printf("%d", *num); }

What is the code used to pass the entire array to a function?

Calling function: main() { int arr[5] = {1, 2, 3, 4, 5}; func(arr) } Called function: void func(int arr[5]) { int i; for (i=0; i<5; i++) printf("%d", arr[i]); }

What is the code used to pass individual elements by their data values?

Calling function: main() { int arr[5] = {1., 2, 3, 4, 5}; func(arr[3]); } Called function: void func (int num) { printf("%d", num); )

What is the general algorithm followed to merge two sorted arrays into a third array that also needs to be sorted?

Compare the first element of array1 with the first element of array2 and put the smaller element in the merged array. Continue systematically comparing each element of the first array to the elements of the second array until elements of both arrays are placed in the right location in the merged array.

What is the algorithm used to delete an element from the middle of any array?

DELETE(A, N, POS) A - array from which element has to be deleted N - number of elements in the array Pos - position from which element has to be deleted. 1. Initialize I with position from which the element has to be deleted. 2. While loop is executed which will move all the elements having an index greater than POS one space towards the left to occupy space vacated by deleted element. 3. Decrement total number of elements in array by 1

How are arrays declared? What data types can an array be?

Declared using: type name[size] Type can be either int, float, double, char, or any other valid data type. Number in bracket specifies the size of the array (max number of elements that can be stored in the array)

What happens when you declare a 2D array?

Declaring a 2D array only reserves space for the array in memory. No values are stored in it.

What does it mean when you say that a 2D array is treated as a collection of 1D arrays?

Each row of a 2D array corresponds to a 1D array consisting of n element, where n is the number of columns

What is the algorithm used to insert an element into the middle of any array?

INSERT(A, N, POS, VAL) 1. Initialize I with the total number of elements in the array 2. While loop is executed which will move all the elements having an index greater than POS one position to the right to create space for the new element. 3. Increment total number of elements in array by 1 after the while loop. 4. New value is inserted at the desired position

When is merging arrays very simple? Why?

If the arrays are unsorted, then merging the arrays is very simple, as one just needs to copy contents of one array into another.

How do you access the elements of 2D array in comparison to accessing elements in a 1D array?

In the case of 1D arrays, you use a single for loop to vary the index i in every pass so that all elements could be scanned. In the case of 2D arrays, you use 2 for loops to scan the elements since the 2D array contains 2 subscripts. The first for loop will scan each row in the 2D array and the second will scan individual columns for every row in the array

How can individual elements of an array be passed by data values?

In the same manner as we pass variables of any other data type. The condition is just that the data type of the array element must match with the type of the function parameter.

What happens when you increment a pointer using the unary operator?

Increments the address it stores by the amount of sizeof(type) where type is the data type of the variable it points to

What does merging two arrays into a third mean?

Means first copying the contents of the first array into the third array and then copying the contents of the second array into the third array.

What does deleting an element from an array mean?

Means removing a data element from an already existing array

Is there index out of bound checking in C?

NO

Can you assigned one array to another array?

No, not even if the two arrays have the same type and size

Why is it not a trivial task to insert an element into the middle of an array?

On an average, we might have to move as much as half of the elements from their positions in order to accommodate space for the new element. Considering an array whose elements are in ascending order, if a new element is to be added, it will have to be added probably somewhere in the middle of the array. To do this, we must first find the location where the new element will be inserted and then move all the elements that have a value greater than that of the new element one position to the right.

Why is it not a trivial task do delete an element from the middle of an array?

On an average, we might have to move as much as half of the elements from their positions in order to occupy the space of the deleted element. Considering an array whose elements are in ascending order, suppose an element has to be deleted, probably from somewhere in the middle of the array. To do this, we must first find the location from where the element has to be deleted and then move all elements having a value greater than that of the element, one position to the left so that space vacated by deleted element can be occupied

What is the difference between a one-dimensional array and a two-dimensional array?

One-dimensional arrays are organized linearly in only one direction Two-dimensional arrays stores data in the form of grids or tables

What is the difference between a pointer and a variable?

Pointer - container to hold address. Need to reserve a spot in the memory (heap) Variable - container to hold value. Program automatically reserves space in memory (Stack)

What can traversing the elements of an array include?

Printing every element, counting total number of elements, or performing any process on these elements.

How do you initialize a 2D array?

Row by row EX) int marks[2][3] = {90, 87, 78, 68, 62, 7} EX) int marks[2][3] = {{90, 87, 78} , {68, 62, 71}}

What are the 2 ways of sequentially storing a 2D array in memory?

Row major order and column major order

In the case of 1D arrays, if an array is completely initialized, you can omit the size of the array. How does this apply in the case of 2D arrays?

Same concept applies for 2D arrays, but only the size of the first dimension can be omitted. EX) int marks[][3] = {{80, 87, 78}, {68, 62, 71}}

How can the address of any element in the array be calculated?

Since the subscript/index represents the offset from the beginning of the array to the element being referenced, C can calculate the address of an element with just the array name and the index.

Sum of two 2D arrays

Two matrices that are compatible with each other can be added together, storing the result in the third matrix. Two matrices are said to be compatible when they have the same number of rows and columns Cij = Aij + Bij

Difference of two 2D arrays

Two matrices that are compatible with each other can be subtracted, storing the result in the third matrix. Two matrices are said to be compatible when they have the same number of rows and columns. Cij = Aij - Bij

What does the array declaration statement tell the compiler?

Tells the compiler the name of the array, the data type of each element in the array, and the size of each dimension.

What happens when you pass the name of an array to a function?

The address of the zeroth element of the array is copied to the local pointer variable in the function.

True or False: In C, it is not a compiler error to initialize an array with more elements than the specified size.

True

True or False: With 2D arrays, the computer stores the base address and the address of the other elements of the array are calculated.

True

Product of two 2D arrays

Two matrices can be multiplied with each other if the number of columns in the first matrix is equal to the number of rows in the second matrix. Therefore, mxn matrix A can be multiplied with pxq matrix B if n=p. The dimension of the product matrix is mxq. Cij = Sum of Aik Bkj for k=1 to n

Column Major Order

The elements of the first column are stored before the elements of the second and third column. That is, the elements of the array are stored column by column where the m elements of the first column will occupy the first m locations

Row Major Order

The elements of the first row are stored before the elements of the second and third rows. That is, elements of array are stored row by row where n elements of the first row will occupy the first n locations

Why is array notation a form of pointer notation?

The name of the array is actually a pointer that points to the first element of the array. *Base address is address of first element in array or address of arr[0].

How do you access all elements of an array?

There is no single statement that can read, access, or print all the elements of an array. You can access all elements of an array by varying the value of the subscript into the array using a loop. *Subscript must be an integral value or an expression that evaluates to an integral value

Transpose a 2D array

Transpose of an mxn matrix A given as nxm matrix B where Bij = Aji

What operations can be performed on 2D arrays?

Transpose, sum, difference, and product

True or False: ++ptr and ptr++ are both equivalent to ptr + 1

True

When do you use a for loop instead of a while loop?

Use a for loop when you know exactly how many times the loop should execute or how many times you want it to execute. Use a while loop if you don't know exactly when a condition will be true or how long it will take to become true.

How do you pass a 2D array to a function?

Use the array name as the actual parameter. However, the parameter in the called function must indicate that the array has two dimensions. EX) int main() { int mat1[5][5]; read_matrix(mat1, row); } void read_matrix(int mat[5][5])

What syntax can be used to access or refer to a single element of an array?

Use the index to retrieve data or access an element arr[i], where i is the index of the element to be accessed. ex) arr[3] accesses the 4th element of the array (array indices start at 0)

What happens when you declare an array?

We are just allocating space for its elements. No values are stored in the array.

How do you initialize arrays during declaration? What is the syntax used to initialize arrays during declaration?

When an array is initialized, you need to provide a value for every element in the array. type array_name [size] = {list of values}; ex) int marks[5] = {90, 82, 78, 95, 88}

When is merging not a trivial task?

When the two arrays are sorted and the merged array also needs to be sorted.

When is it allowed to add and subtract pointers?

When they point to the same array

What are we actually doing when we say that we are deleting an element?

When we say that we are actually deleting an element, we are actually overwriting the element with the value of its successive element

When can you use the following declaration? #define ARRAY_SIZE 12

When you have multiple arrays with the same size

Do arrays have a definite size?

Yes

What are the 2 different situations that you may encounter when you want to pass an array to a function?

You can pass individual elements of an array or the entire array

How do you pass the address of an individual array element?

You can pass the address of an individual array element by preceding the indexed array element with the address operator, &. However, in the called function, the value of the array element must be accessed using * operator. EX) To pass address of the fourth element of the array to the called function --> &arr[3]

When a formal parameter is declared in a function header as an array, it is interpreted as _______________________.

a pointer to a variable and not as an array

Since all pointers have the same size, the address of ptr + i can be calculated as?

addr(ptr + i) = addr(ptr) + [sizeof(int*)*1]

In C, we can add or subtract ________________________ to get a new pointer, pointing somewhere other than the original position. C also permits addition and subtraction of _________________________.

an integer from a pointer ; two pointer variables

What is the golden rule to access an element of a 2D array?

arr[i][j] = (*(arr+i))[j] = *((*arr+i))+j) = *(arr[i]+j)

What is the difference between arrop[i] and *arrop[i]?

arrop[i] prints the address *arrop[i] prints the value

Array name is often known to be a _____________ pointer.

constant

The name of an array is a _________________.

constant pointer to the array

How do you declare a two-dimensional array?

data_type array_name[row_size][column_size]; *row size and column size do not have to be the same ex) int marks[3][3];

What is the syntax of the for loop used to access the elements of an array?

for (int counter = 1; counter <= 10; counter++) -counter: control variable name - 1: starting value of control variable - counter<=10: the actual loop - 10: final value for which the condition is true - counter++: increment the control variable *For loops execute blocks of code over and over again until a certain condition is met

How can a function that accepts an array declare the formal parameter?

func(int arr[]); or func(int *arr);

The length of an array is _________________. What is the general formula used to calculate the length of the array?

given by the number of elements stored in it. Formula: length = upper_bound - lower_bound + 1 -upper_bound: index of last element -lower_bound: index of first element

Create a pointer pointing to the first element of the array.

int *ptr; ptr = &arr[0];

How can you declare an array of pointers?

int *ptr[10]; *Declares an array of 10 pointers where each of the pointers points to an integer variable

How do you find the length of an integer array?

int length = sizeof(arr) / sizeof(arr[0])

How do you declare a pointer to a 2D array?

int mat[5][5]; --> 2D array int **ptr; --> array of pointers to 1D arrays THEY ARE NOT THE SAME TYPE AND AREN'T INTERCHANGEABLE

What is the difference between int(*ptr)[10] and int *ptr[10];

int(*ptr)[10] --> declares ptr to be a pointer to an array of 10 integers int *ptr[10] --> ptr is the name of an array of 10 pointers to type int

How do you initialize individual elements of a 2D array?

marks[1][2] = 79; marks[1][2] = marks [1][1] + 10;

When you declare a pointer to a 2D array, how can individual elements of an array be accessed?

mat[i][j] *(*(mat + i) + j) or *(mat[i] + j)

When you write ptr + i, adding i gives a pointer that _______________________

points i elements further along an array than the original pointer

Elements in an array are stored __________________________

sequentially


Ensembles d'études connexes

failure is closer than you think

View Set

7C. Attitude and Behavior Change

View Set

The Tokugawa Period: Politics, Society and Culture (1600-1868)

View Set

Nursing Fundamentals Chapter 31.

View Set

Chapter 7 financing and accounting

View Set

Catholic Social Teaching - Ch. 3 Test Review

View Set