LECTURE-06 ARRAYS - KUET · 2021. 1. 24. · LECTURE-06 ARRAYS PINGKI DATTA, LECTURER, DEPARTMENT...

66
LECTURE - 06 ARRAYS PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET. 1

Transcript of LECTURE-06 ARRAYS - KUET · 2021. 1. 24. · LECTURE-06 ARRAYS PINGKI DATTA, LECTURER, DEPARTMENT...

  • LECTURE-06ARRAYS

    PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    1

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    2

    Arrays• In this lecture we will get familiar with one of the

    C’s most essential data structures called arrays.Arrays are data structures consisting of related dataitems of the same type. You can also say that it is agroup of memory locations related by the fact thatthey all have the same name and same type.

    • Arrays a kind of data structure that can store afixed-size sequential collection of elements of thesame type. An array is used to store a collection ofdata, but it is often more useful to think of an arrayas a collection of variables of the same type.

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    3

    Instead of declaring individual variables, suchas number0, number1, ..., and number99, youdeclare one array variable such as numbersand use numbers[0], numbers[1], and ...,numbers[99] to represent individual variables.A specific element in an array is accessed byan index.All arrays consist of contiguous memorylocations. The lowest address corresponds tothe first element and the highest address tothe last element.

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    4

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    5

    Why ArraysFor understanding the arrays properly, let usconsider the following program:

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    6

    No doubt, this program will print the value of xas 10. Why so? Because when a value 10 isassigned to x, the earlier value of x, i.e. 5, islost. Thus, ordinary variables (the ones whichwe have used so far) are capable of holdingonly one value at a time (as in the aboveexample). However, there are situations inwhich we would want to store more than onevalue at a time in a single variable.

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    7

    For example, suppose we wish to arrange thepercentage marks obtained by 100 students inascending order. In such a case we have twooptions to store these marks in memory:

    Construct 100 variables to store percentagemarks obtained by 100 different students, i.e.each variable containing one student’s marks.Construct one variable (called array orsubscripted variable) capable of storing orholding all the hundred values.

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    8

    Obviously, the second alternative is better. Asimple reason for this is, it would be mucheasier to handle one variable than handling100 different variables. Moreover, there arecertain logics that cannot be dealt with,without the use of an array.

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    9

    One Dimensional ArrayA list of items can be given in one variable nameusing only one subscript and such a variable iscalled a single-subscripted variable or a one-dimensional array.In C, a one dimensional array is a list of variablesthat are all of the same type and accessedthrough a common name. An individualelement in an array is called array element.Array is helpful to handle a group of similartypes of data.

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    10

    Before using the array in the program it mustbe declaredSyntax:data_type array_name[size];data_type represents the type of elementspresent in the array. array_name representsthe name of the array. Size represents thenumber of elements that can be stored in thearray.

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    11

    Example:int age[100];float sal[15];char grade[20];

    Here age is an integer type array, which canstore 100 elements of integer type. The arraysal is floating type array of size 15, can holdfloat values. The grade is a character type arraywhich holds 20 characters.

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    12

    Declaring ArraysTo declare an array in C, a programmerspecifies the type of the elements and thenumber of elements required by an array asfollows:type arrayName [ arraySize ];This is called a single-dimensional array.

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    13

    The arraySize must be an integer constantgreater than zero and type can be any validC data type. For example, to declare a 10-element array called balance of typedouble, use this statement:

    double balance[10];Here, balance is a variable array which issufficient to hold up to 10 double numbers.

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    14

    Initializing ArraysYou can initialize an array in C either one byone 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 ofelements that we declare for the arraybetween square brackets [ ]. If you omit thesize of the array, an array just big enough tohold the initialization is created.

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    15

    Therefore, if you write:double balance[] = {1000.0, 2.0, 3.4, 7.0,

    50.0};You will create exactly the same array asyou did in the previous example. Followingis an example to assign a single element ofthe array: You will create exactly the samearray as you did in the previous example.Following is an example to assign a singleelement of the array:

    double balance[4] = 50.0;

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    16

    The above statement assigns the 5th elementin the array with a value of 50.0. All arrays have0 as the index of their first element which isalso called the base index and the last index ofan array will be total size of the array minus 1.Shown below is the pictorial representation ofthe array we discussed above:

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    17

    To declare a one dimensional array, we use-data_type array_name [size];

    Here, data_type is a valid C data type,array_name is the name of tha array andfollows the convention of naming a variable,and size specifies the number of elements inthe array.

    int my_array[20];-Declares an array name my_array of typeinteger that contains 20 elements.

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    18

    An array element is accessed by indexingthe array using the number of element. InC, all arrays begin at zero. This means thatif you want to access the first element inan array, use zero for the index.To index an array, specify the index of theelement you want inside square brackets.The second element of my_array will be-my_array [1]

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    19

    To assign an array element a value, put thearray on the left side of the assignmentoperator. The example gives the first elementof my_array the value 200.

    my_array [0]=200;C stores one dimensional array in onecontiguous memory location with firstelement at the lower address.

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    20

    For example, an array named a of 10elements can occupy the memory asfollows-

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    21

    Now, let us consider a program that declares an arrayof 10 elements and initializes every element of thatarray with 0main(){

    int a[10], i;for (i=0;i

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    22

    main(){int a[10]={1,2,3,4,5,6,7,8,9,10},int i;printf (“Element \t Value”);for (i=0;i

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    23

    If you put more values than the array canhold, there will be a syntax error-main(){

    int a[5]={1,2,3,4,5,6,7,8,9,10},int i;printf (“Element \t Value”);for (i=0;i

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    24

    If array size is omitted during declaration, thenumber of values during array initialization willbe the number of elements the array can hold.For example, the following array willautomatically have space for 5 elements.main(){

    int a[]={1,2,3,4,5},int i;printf (“Element \t Value”);for (i=0;i

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    25

    Initialization:An array can be initialized at either of thefollowing stages:1. At complie time2. At run time

    Compile Time InitializationWe can explicitly initialize arrays at the time ofdeclaration.Syntax:data_type array_name[size]={value1,value2,……..valueN};

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    26

    value1, value2, valueN are the constantvalues known as initializers, which areassigned to the array elements one afteranother.Example:int marks[5]={10,2,0,23,4};The values of the array elements after thisinitialization are:marks[0]=10, marks[1]=2, marks[2]=0,marks[3]=23, marks[4]=4

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    27

    Run Time InitializationAn array can be explicitly initialized at run time. This approach is usually applied for initializing large arrays. For example, consider the following segment of a C program.…………..…………..for ( i = 0; i < 100; i = i+1){if i < 50sum[i] = 0.0;else sum[i] = 1.0; }……………..

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    28

    The first 50 elements of the array sum areinitialized to zero while the remaining 50elements are initialized to 1.0 at run time.

    Note:In 1-D arrays it is optional to specify the sizeof the array. If size is omitted duringinitialization then the compiler assumes thesize of array equal to the number ofinitializers.

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    29

    Example:int marks[]={10,2,0,23,4};Here the size of array marks is initialized to 5.You can’t copy the elements of one array to anotherarray by simply assigning it.

    Example:int a[5]={9,8,7,6,5};int b[5];b=a; //not validwe have to copy all the elements by using for loop.for(a=i; i

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    30

    Accessing Array ElementsAn element is accessed by indexing the arrayname. This is done by placing the index of theelement within square brackets after the nameof the array. For example:

    double salary = balance[9];The above statement will take the 10thelement from the array and assign the value tosalary variable. The following example showshow to use all the three above-mentionedconcepts viz. declaration, assignment, andaccessing arrays:

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    31

    main (){int n[ 10 ]; /* n is an array of 10 integers */int i,j;/* initialize elements of array n to 0 */for ( i = 0; i < 10; i++ ){n[ i ] = i + 100; /* set element at location i to i + 100 */}/* output each array element's value */for (j = 0; j < 10; j++ ){printf("Element[%d] = %d\n", j, n[j] ); }

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    32

    When the above code is compiled and executed, itproduces the following result:

    Element[0] = 100Element[1] = 101Element[2] = 102Element[3] = 103Element[4] = 104Element[5] = 105Element[6] = 106Element[7] = 107Element[8] = 108Element[9] = 109

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    33

    A Simple Program Using ArrayThe following program declares an arrayto hold the marks of 30 students. Firstly,the program with the help of a loop takesmarks of 30 students inside the array.Then, again with the help of another loop,the program calculates their total marks.Finally, it delivers the average mark bydividing the total mark by numberstudents (30)-

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    34

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    35

    Character ArraysCharacter arrays have several uniquefeatures. A character array can beinitialized using a string literal.

    char string1[ ] = “first”;this declaration initialized the elements ofarray string1 to the individual characters inthe string literal “first”. The size of arraystring1 is determined by the compilersbased on the string.

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    36

    Note-“first” string literal contains five charactersplus a special string termination charactercalled null character (\0). Thus, string1 arrayactually has 6 elements-f, i, r, s, t and \0. Acharacter array representing a string shouldalways have declared large enough to hold thenumber of characters in the string plus theterminating null character.Character arrays can be initialized as follows aswell-

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    37

    char string1 [ ]= {‘f’, ‘i’, ‘r’, ‘s’, ‘t’, ‘\0’};This is because string is really an array ofcharacters. We can access individual charactersin a string directly using array subscriptnotation. For example, string1 [3] is thecharacter ‘s’.We can also input a string directly from thekeyboard using scanf () function and %sspecifier.

    char string1 [20];scanf (“%s”, string1);

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    38

    Note- the name of the array is passed to scanf() without the preceding & used with othervariables. The & is normally used to providescanf () with a variable’s location in a memoryso a value can be stored there. Array name isthe address of the start of the array, therefore,& is not necessary.Note- scanf () reads characters from thekeyboard until the first whitespace character isencountered- it does not care how large thearray is. scanf () takes upto the first whitespace.

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    39

    main(){char string1 [20], string2 [ ] = “Hello There”;

    int i;printf (“Enter a string with white spaces: ”);scanf (“%s”, string1);printf (“\nString 2 is %s”, string2);printf (\n String 1 is );for (i=0;string1 [i]!=’\0’;i++)

    printf (“%c”, string1 [i]);}

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    40

    The output of the program is-Enter a string with white spaces: Hello ThereString 2 is Hello ThereString 1 is Hello

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    41

    TWO DIMENSIONAL

    ARRAY

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    42

    Arrays in DetailArrays are important to C and should need a lotmore attention.

    Multidimensional ArraysC programming language allowsmultidimensional arrays. Here is the generalform of a multidimensional array declaration:

    type name[size1][size2]...[sizeN];For example, the following declaration creates athree-dimensional integer array:

    int threedim[5][10][4];

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    43

    The following important concepts related to array should be clear to a C programmer:

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    44

    Two-dimensional ArraysThe simplest form of multidimensionalarray is the two-dimensional array. A two-dimensional array is, in essence, a list ofone-dimensional arrays. To declare a two-dimensional integer array of size [x][y], youwould write something as follows:

    type arrayName [ x ][ y ];

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    45

    Where type can be any valid C data type andarrayName will be a valid C identifier. A two-dimensional array can be considered as a tablewhich will have x number of rows and y numberof columns. A two-dimensional array a, whichcontains three rows and four columns can beshown as follows:

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    46

    Thus, every element in the array a isidentified by an element name ofthe form a[ i ][ j ], where ‘a’ is thename of the array, and ‘i' and ‘j’ arethe subscripts that uniquely identifyeach element in ‘a’.

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    47

    Initializing Two-Dimensional ArraysMultidimensional arrays may be initialized byspecifying bracketed values for each row.Following is an array with 3 rows and each rowhas 4 columns.int a[3][4] = {{0, 1, 2, 3} , /* initializers for row indexed by 0*/{4, 5, 6, 7} , /* initializers for row indexed by 1*/{8, 9, 10, 11} /* initializers for row indexed by 2*/ };

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    48

    The nested braces, which indicate theintended row, are optional. Thefollowing initialization is equivalent tothe previous example:int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    49

    Accessing Two-Dimensional Array ElementsAn element in a two-dimensional array isaccessed by using the subscripts, i.e., rowindex and column index of the array. Forexample:

    int val = a[2][3];The above statement will take the 4th elementfrom the 3rd row of the array. You can verify itin the above figure. Let us check the followingprogram where we have used a nested loop tohandle a two-dimensional array:

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    50

    int main (){/* an array with 5 rows and 2 columns*/int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};int i, j;/* output each array element's value */for ( i = 0; i < 5; i++ ){for ( j = 0; j < 2; j++ ){printf("a[%d][%d] = %d\n", i,j, a[i][j] );} }

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    51

    When the above code is compiled andexecuted, it produces the following result:a[0][0]: 0a[0][1]: 0a[1][0]: 1a[1][1]: 2a[2][0]: 2a[2][1]: 4a[3][0]: 3a[3][1]: 6a[4][0]: 4a[4][1]: 8

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    52

    • As explained above, you canhave arrays with any number ofdimensions, although it is likelythat most of the arrays youcreate will be of one or twodimensions.

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    53

    To understand more deeply how the values are storedin a two dimensional array, let us consider anotherexample-main(){

    int a [4][5];int i, j;for(i=0;i

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    54

    The output of the program is-

    0 0 0 0 00 1 2 3 40 2 4 6 8

    0 3 6 9 12

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    55

    Passing Arrays to FunctionsArray elements can be passed to afunction by calling the function by value,or by reference. In the call by value wepass values of array elements to thefunction, whereas in the call by referencewe pass addresses of array elements tothe function. As we did not see call byreference yet, we will see that later.

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    56

    Way-1Formal parameters as a pointer:void myFunction(int *param){...}

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    57

    Way-2Formal parameters as a sized array:void myFunction(int param[10]){...}

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    58

    Way-3Formal parameters as an unsized array:void myFunction(int param[]){...}

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    59

    Return Array from a FunctionC programming does not allow toreturn an entire array as anargument to a function. However,you can return a pointer to anarray by specifying the array'sname without an index.

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    60

    If you want to return a single-dimension arrayfrom a function, you would have to declare afunction returning a pointer as in thefollowing example:int * myFunction(){. . . .}Second point to remember is that C does notadvocate to return the address of a localvariable to outside of the function, so youwould have to define the local variable asstatic variable.

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    61

    int main (){/* a pointer to an int */int *p;int i;p = getRandom();for ( i = 0; i < 10; i++ ){printf( "*(p + %d) : %d\n", i, *(p + i));}return 0; }

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    62

    When the above code is compiled together andexecuted, it produces the following result:r[0] = 313959809r[1] = 1759055877r[2] = 1113101911r[3] = 2133832223r[4] = 2073354073r[5] = 167288147r[6] = 1827471542r[7] = 834791014r[8] = 1901409888r[9] = 1990469526

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    63

    *(p + 0) : 313959809*(p + 1) : 1759055877*(p + 2) : 1113101911*(p + 3) : 2133832223*(p + 4) : 2073354073*(p + 5) : 167288147*(p + 6) : 1827471542*(p + 7) : 834791014*(p + 8) : 1901409888*(p + 9) : 1990469526

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    64

    Pointer to an ArrayIt is most likely that you would notunderstand this section until you arethrough with the chapter ‘Pointers’.Assuming you have some understanding ofpointers in C, let us start: An array name isa constant pointer to the first element ofthe array. Therefore, in the declaration:double balance[50];

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    65

    balance is a pointer to &balance[0], which is theaddress of the first element of the array balance.Thus, the following program fragment assigns p asthe address of the first element of balance:

    double *p;double balance[10];

    p = balance;It is legal to use array names as constant pointers,and vice versa. Therefore, *(balance + 4) is alegitimate way of accessing the data at balance[4].

  • PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

    66

    Thanks to AllSEE YOU IN NEXT

    CLASS.