PPS
Unit 4Array Q1) What is an array? Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index. Q2) How do we initialize arrays? Initialize an array in C either one by one or using a single statement as follows −double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};The number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ].If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write −double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};You will create exactly the same array as you did in the previous example. Following is an example to assign a single element of the array –
balance[4] = 50.0;The above statement assigns the 5th element in the array with a value of 50.0. All arrays have 0 as the index of their first element which is also called the base index and the last index of an array will be total size of the array minus Q3) Explain array elements in memory? Two pieces of information are needed to specify the memory of an ordinary variable:an address in memory giving the location of the first byte for that variable, and the type of the variable, which tells the compiler how many bytes of memory the variable requires, and enables it to correctly interpret the data. When an array of a given size, say N, and of a given type is declared, the compiler allocates enough memory to hold all N pieces of data. If M bytes of memory is required for each piece of data of the type specified, then a total of N*M bytes of contiguous memory are allocated to that array.The data for the first element is stored in the first M bytes, the data for the second element is stored in the next M bytes, etc.The compiler remembers the address of the first byte of an array only. In fact the address of the first byte is considered as the memory address for the entire array.Knowing the address of the first byte the computer can easily calculate to find the memory address for any other element of the array. For example given an array A, to retrieve the data stored in A[n], the computer goes to the address of the array plus n*M and retrieves the next M bytes of data. To illustrate, consider an integer array exam_score that is declared for use to store the exam score for a class of 12 students.:const int CLASS_SIZE = 12;int exam_score[CLASS_SIZE];Suppose the 12 scores have been assigned to the array, and the following code is used to compute the class average:float average;int sum = 0, n;for (n = 1; n <= CLASS_SIZE; n++) sum += exam_score[n];average = double(sum)/double(CLASS_SIZE);This code when embedded in a suitable program will compile and run on most systems. However, the result for the average is almost always wrong. The reason is that the element exam_score[12] is referenced in the last iteration of the loop. The 12 elements of the array are indexed from 0 to 11, and the index of 12 is out-of-range. Q4) What is bound checking? Array bound checking refers to determining whether all array references in a program are within their declared ranges. This checking is critical for software verification and validation because subscripting arrays beyond their declared sizes may produce unexpected results, security holes, or failures. Q5) Write a program to reverse an array? #include <stdio.h>#include<conio.h> void main(){ int n, i, j, a[100], b[100];// a is original array and b is reversed array printf("Enter the number of elements in array\n"); scanf("%d", &n); printf("Enter the array elements\n"); for (i= 0; i < n ; i++) scanf("%d", &a[i]); /* * Copying elements into array b starting from end of array a */ for (i = n - 1, j = 0; i >= 0; i--, j++) b[j] = a[i]; /* Printing reversed array b. */ printf("Reverse array is\n"); for (i = 0; i < n; i++) printf("%d\n", a[i]); getch();}output:Enter the number of elements in an array:5Enter the elements 9 18 27 36 45 Reverse of an array45 6 27 18 9 Q6) Explain initialization of two- dimensional array? In C, two dimensional arrays can be initialized in different number of ways. Specification of no. of columns in 2 dimensional array is mandatory while no of rows is optional.int a[2][3]={{1,3,0}, // Elements of 1st row {-1,5,9}}; // Elements of 2nd row OR int a[][3]={{1,3,0}, // Elements of 1st row {-1,5,9}}; // Elements of 2nd row OR int a[2][3]={1,3,0,-1,5,9}; Fig. 3 gives general storage representation of 2 dimensional array
Eg 4. int a[2][3]={1,3,0,-1,5,9}
Accessing Two-Dimensional Array Elements:An element in 2-dimensional array is accessed by using the subscripts i.e. row index and column index of the array. For example:int val = A[1][2];The above statement will access element from the 2nd row and third column of the array A i.e. element 9. Q7) Explain passing array elements to functions? Array is a data structure which stores the collection of similar types of element in consecutive memory locations. Indexing of array always start with ‘0’ where as non-graphical variable ‘\0’ indicates the end of array. Syntax for declaring array is data type array name[Maximum size];Data types are used to define type of element in an array. Data types are also useful in finding the size of total memory locations allocated for the array. All the rules of defining name of variable are also applicable for the array name. Maximum size indicates the total number of maximum elements that array can hold. Total memory allocated for the array is equal to the memory required to store one element of the array multiply by the total element in the array. In array, memory allocation is done at the time of declaration of an array. Q8) Write a program to swap two values ? #include <stdio.h>#include<conio.h>/* function declaration goes here.*/void swap( int p1, int p2 );int main(){int a = 10;int b = 20;printf("Before: Value of a = %d and value of b = %d\n", a, b );swap( a, b );printf("After: Value of a = %d and value of b = %d\n", a, b );getch();}void swap( int p1, int p2 ){int t;t = p2;p2 = p1;p1 = t;printf("Value of a (p1) = %d and value of b(p2) = %d\n", p1, p2 );}Output :Before: Value of a = 10 and value of b = 20Value of a (p1) = 20 and value of b (p2) = 10After: Value of a = 10 and value of b = 20Note: In the above example the values of “a” and “b” remain unchanged before calling swap function and after calling swap function. Q9) Write a program to find the sum of n elements in array using pointers? #include <stdio.h>int main() { int i, x[6], sum = 0; printf("Enter 6 numbers: "); for(i = 0; i < 6; ++i) { // Equivalent to scanf("%d", &x[i]); scanf("%d", x+i); // Equivalent to sum += x[i] sum += *(x+i); } printf("Sum = %d", sum); return 0;}When you run the program, the output will be:Enter 6 numbers: 2 3 4 4 12 4Sum = 29 Q10) Explain two dimensional arrays?Multidimensional arrays follow the same rules as single-dimensional arrays when passing them to a function. However, the combination of decay-to-pointer, operator precedence, and the two different ways to declare a multidimensional array (array of arrays vs array of pointers) may make the declaration of such functions non-intuitive. The following example shows the correct ways to pass multidimensional arrays.#include <assert.h>#include <stdlib.h>/* When passing a multidimensional array (i.e. an array of arrays) to a function, it decays into a pointer to the first element as usual. But only the top level decays, so what is passed is a pointer to an array of some fixed size (4 in this case). */void f(int x[][4]) { assert(sizeof(*x) == sizeof(int) * 4);}/* This prototype is equivalent to f(int x[][4]). The parentheses around *x are required because [index] has a higher precedence than *expr, thus int *x[4] would normally be equivalent to int *(x[4]), i.e. an array of 4 pointers to int. But if it's declared as a function parameter, it decays into a pointer and becomes int **x, which is not compatable with x[2][4]. */void g(int (*x)[4]) { assert(sizeof(*x) == sizeof(int) * 4);} Q11) Explain memory map of two- dimensional array?The array arrangement shown in Figure is only conceptually true. This is because memory doesn’t contain rows and columns. In memory whether it is a one-dimensional or a two-dimensional array the array elements are stored in one continuous chain. The arrangement of array elements of a two-dimensional array in memory is shown below:
We know that the expressions s[0] and s[1] would yield the addresses of the zeroth and first one-dimensional array respectively. From Figure 8.6 these addresses turn out to be 65508and 65512.Suppose we want to refer to the element s[2][1] using pointers. s[2] would give the address 65516, the address of the second one-dimensional array. Obviously ( 65516 + 1 ) would give the address 65518. Or ( s[2] + 1 ) would give the address 65518.And the value at this address can be obtained by using the value at address operator, saying *( s[2] + 1 ). But, we have already studied while learning one-dimensional arrays that num[i] is same as *( num + i ). Similarly, *( s[2] + 1 ) is same as, *( *( s + 2 ) + 1 ). Thus, all the following expressions refer to the same element, s[2][1]* ( s[2] + 1 )* ( * ( s + 2 ) + 1 )Using these concepts the following program prints out each element of a two-dimensional array using pointer notation. Q12) Explain pointers and multi-dimensional arrays? In multidimensional array all the elements of the array are stored in multiple stacks of rows. Two dimensional array has two stacks of rows, it looks like two dimensional matrix containing rows and columns. Three dimensional array has three stacks of rows and it looks like a rubik’s cube. Like single dimensional array, all the elements of multidimensional array are of same type and C language does not allow user to store elements of two or more different data type in a single multidimensional array. Suppose user wants to store string ‘Hello Raushan’ in two dimensional array, minimum size of an array to store above strings is 13 as it contains 12 alphabets and one space. Two dimensional arrays are built with rows and columns. For the above string we need to divide total array size into rows and columns. A pointer variable can store the address of only one array variable at a single instant of time. Similar to array, pointer can also hold the address of only respective type of element. For the above string user required character type of pointer. Following is the syntax of declaring two dimensional array and a pointer to array. char arr[2][7]= {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ’, ‘R’, ‘a’, ‘u’, ‘s’, ‘h’, ‘a’, ‘n’}; char *p; p=&arr[0][0];In the above syntax, First line represents the syntax of declaring and defining two dimensional array. Here we declare the character type of array of size 14, which is divided into two rows and seven columns. Total memory allocated to the ‘arr’ array is 14. This array can hold 14 elements having data type ‘char’ and all these elements are stored in the consecutive memory location. Out of 14 elements the first 7 elements are stored in the first row whereas remaining elements are stored in the second row. The index of first element (ie ‘H’) is arr[0][0] where as the last element (ie ‘n’) is having index arr[1][5]. At the last position of the array ie arr[1][6] contains garbage value. Q13) Write a program to display the elements of two -dimensional array?#include<stdio.h>#include<conio.h>void main(){ int arr[2][3],i,j,*p; clrscr(); printf("enter the elements of array"); for(i=0;i<2;i++) { for(j=0;j<3;j++) { scanf("%d",&arr[i][j]); } } printf("Two dimensional array is\n"); for(i=0;i<2;i++) { for(j=0;j<3;j++) { printf("\t %d",arr[i][j]); } printf("\n"); } for(i=0;i<2;i++) { for(j=0;j<3;j++) { p=&arr[i][j]; printf("\n address is %d and value is %d",p,*p); } } getch();}Output: Enter the elements of array 4 5 6 1 2 3 Two dimensional array is 4 5 6 1 2 3 address is -24 and value is 4 address is -22 and value is 5 address is -20 and value is 6 address is -18 and value is 1 address is -16 and value is 2 address is -14 and value is 3 Q14) Explain pointer to an array?Pointer is a special variable that can hold the address of another variable whereas arrays are the special type of linear data structure in which elements are stored in contiguous memory locations. Pointers to array are used to retrieve the values of array element from their location. Pointer to array means that a variable which is meant to hold the address of array element. Following is the syntax of assigning the address of array element to pointer.pointer-name = & array-name[element]; For example:
User can access the elements of array by using pointer variable. If we want to store value 7 at the second position then we need to write*p= 7;
Q15) Explain passing 2D array to function? 2-D is passed to a function it is optional to specify the size of the left most dimensions. So if we have an array of 2 rows and 3 dimensions then it can be passed to a function in the following two ways:int two_d[2][3] = { {99,44,11}, {4,66,9} };1st way:void function(int a[][3]){ // statements;} 2nd way:void function(int a[2][3]){ // statements;}Recall that 2-D arrays are stored in row-major order i.e first row 0 is stored, then next to it row 1 is stored and so on. Therefore in C, a 2-D array is actually a 1-D array in which each element is itself a 1-D array. Since the name of the array points to the 0th element of the array. In the case of a 2-D array, 0th element is an array. Hence, we can also declare a function where the formal argument is of type pointer to an array. 3rd way:void function(int (*a)[3]){ // statements; }Essentially in all the three cases discussed the type of the variable a is a pointer to an array of 3 integers, they differ only in the way they are represented. Q16) Explain three- dimensional array?A 3D array is a multi-dimensional array(array of arrays). A 3D array is a collection of 2D arrays. It is specified by using three subscripts:Block size, row size and column size. More dimensions in an array means more data can be stored in that array.int shows that the 3D array is an array of type integer.arr is the name of array.first dimension represents the bl ock size(total number of 2D arrays).second dimension represents the rows of 2D arrays.third dimension represents the columns of 2D arrays.i.e; int arr[3][3][3], so the statement says that we want three such 2D arrays which consists of 3 rows and 3 columns.int arr[3][3][3]; //3D arrayblock(1) 1 2 3 block(2) 10 11 12 block(3) 19 20 21 4 5 6 13 14 15 22 23 24 7 8 9 16 17 18 25 25 27 3x3 3x3 3x3Declaring a 3D array:To declare 3D array:Specify data type, array name, block size, row size and column size.Each subscript can be written within its own separate pair of brackets.Syntax: data_type array_name[block_size][row_size][column_size];example:int arr[2][3][3]; //array of type integer //number of blocks of 2D arrays:2 |rows:3 |columns:3 //number of elements:2*3*3=18block(1) 11 22 33 block(2) 12 13 14 44 55 66 21 31 41 77 88 99 12 13 14 3x3 3x3
int arr[4];
int *p;
p= &arr[1];
In the above example, pointer variable ‘p’ is pointing the address of second variable of the array ‘arr’. Following figure depict the pictorial representation of above code.Declaring Pointer to array
|
Assigning value to second position of an array
|
0 matching results found