+ All Categories
Home > Documents > ECS ICT Week9 Slides

ECS ICT Week9 Slides

Date post: 01-Oct-2015
Category:
Upload: masterarvin
View: 223 times
Download: 1 times
Share this document with a friend
Description:
ECS ICT Week9 Slides
40
Week 9, 10 Arrays (one-dimensional and two- dimensional) 1
Transcript
  • Week 9, 10

    Arrays (one-dimensional and two-

    dimensional)

    1

  • ONE-DIMENSIONAL ARRAYS

    2

  • Arrays An array is like a large data variable that can store multiple data items of

    the same type. Arrays are a series of elements (variables) of the same type placed

    consecutively in memory that can be individually referenced by addingan index to a unique name.

    3

    X

    X[0]

    Each individual

    element is referred to by

    the array name and the

    subscript (or index).

    Index starts with 0 and ends

    with is the size-1;

    The ith element is referred to by X[i-1]

  • Arrays We can store 5 values of type int without having to declare 5 different

    variables each one with a different identifier. Instead of that, using anarray we can store 5 different values of the same type, int for example,with an unique identifier.

    Example: Use an array called Arr to contain 5 integer values of type int.

    4

    Arr0 1 2 3 4

    int

    The cells are numbered from 0 to 4 since in arrays the first index is

    always 0, independently of its length .

  • Declaration of Array variables A typical array declaration in C is as follows:

    type name [elements]; Example:

    int X[10]; //

    5

    Array X will contain 10 elements of integer type. The elements will be X[0] to X[9]

    We can have arrays of any type and dimension:

    Example: char X[20]

    float Y[50]

    double Z[10] NOTE: The elements field within brackets [] when declaringan array must be a constant value, since arrays are blocks ofstatic memory of a given size and the compiler must be able todetermine exactly how much memory must assign to the arraybefore any instruction is considered.

  • Initialising Arrays (1)

    6

    When declaring an array of local scope (within a function), if we

    do not specify otherwise, it will not be initialized. So, its content is

    undetermined until we store some values in it.

    If we declare a global array (outside any function) its contents will

    be initialized with all its elements filled with zeros. Thus, if in the

    global scope we declare int billy [5] :

    0 0 0 0 0billy0 1 2 3 4

    int But additionally, when we declare an Array, we have the possibility to assign initialvalues to each one of its elements using curly brackets { }.Example:int billy [5] = { 16, 2, 77, 40, 12071 };

  • Initialising Arrays (2)

    7

    The number of elements in the array that we initialized within

    curly brackets { } must match the length in elements that we

    declared for the array enclosed within square brackets [ ].

    Example: int array1 [5] = { 16, 2, 77, 40, 12071};

    Because this can be considered an useless repetition, C++ includes

    the possibility of leaving empty the brackets [ ], being the size of the

    Array defined by the number of values included between curly

    brackets { }:

    Example: int array2 [] = { 16, 2, 77, 40, 12071};

  • Input/Output of array elements (1) Exercise: Write a program to input values into all elements of an

    integer array A of size 10 and display back the values.

    8

    #include

    int main()

    {

    int A[10];

    int i;

    printf("Enter 10 integer values: ");

    for (i=0; i

  • Input/Output of array elements (2) Exercise: Write a program to input values into all elements of an

    integer array A of size 10 and display back the values in reverseorder.

    9

  • Solution#include int main(){

    int A[10];int i;printf("Enter 10 integer values: ");for (i=0;i

  • Input/Output of array elements (3)

    Exercise: Write a program to input an integer n (n

  • Solution

    12

    #include

    int main()

    {

    int i;

    float A[10];

    int maxposn;

    float max;

    printf("Input 10 integer numbers:

    ", n);

    maxposn=0;

    max=0;

    for (i=0;imax)

    {

    max=A[i];

    maxposn=i;

    }

    }

    printf("largest is %.2f at posn

    %d\n", max, maxposn);

    }

  • Array of characters (1)

    Character arrays can be treated in a similar way to arrays of integers and real numbers.

    Example: char x[20] Each element can be input as follows:

    for (i=0; i

  • Arrays of characters (2)

    With the declaration char x[20], the arrayx can contain a string of characters. But a string contains \0 as the last character Reading a string:

    char x[20];scanf("%s",x);After reading the characters (must be less than 20), a \0 will be

    appended at the end.NOTE: It will stop input when a space is encountered or end of line is

    encountered.

    Displaying the value of x:printf(%s,x);

    14

  • Exercise - Write a program to input the name of a personand display the number of vowels in the name.

    15

  • Solution#include int main(){

    char name[20];char ch;int i,count;count = 0;printf("Input name: ");scanf("%s", name);

    i=0;while ((name[i]!='\0') && (i

  • 17

    Strings/Array of characters (2)

    Initialization of strings:

    char mystring[] = { 'H', 'e', 'l', 'l', 'o', '\0' };

    The above example shows a string of characters (array) of 6

    elements of type char initialized with the characters that compose

    Hello plus a null character '\0'.

    Nevertheless, string of characters have an additional way to

    initialize its values: using constant strings:

    Example:

    char mystring [] = { 'H', 'e', 'l', 'l', 'o', '\0' };

    char mystring [] = "Hello";

    In both cases the Array or string of characters mystring is

    declared with a size of 6 characters (elements of type char): the 5

    characters that compose Hello plus a final null character ('\0')

    which specifies the end of the string. However, in the second case,

    when using double quotes ("), the null character it is

    automatically appended.

  • 18

    Strings/Array of characters (3)

    Note:

    We can "assign" a multiple constant to an Array only at the

    moment of initializing it, that is, at the moment it is being

    declared.

    The following examples are invalid:

    astring = "Hello";

    astring[] = "Hello";

    astring = { 'H', 'e', 'l', 'l', 'o', '\0' };

    However, the following is valid:

    char astring[10] ;

    astring[0] = 'H';

    astring[1] = 'e';

    astring[2] = 'l';

    astring[3] = 'l';

    astring[4] = 'o';

    astring[5] = '\0;

  • Strings/Array of characters (4): string.h#include

    can be used to access string manipulation functions e.g char name[]=John, x[5]; Useful functions are:

    strlenInt L;L=strlen(name);

    strcpystrcpy(x,name);

    strcmpif(strcmp(name,x)==0)

    printf(same\n);else

    printf(not same\n);

    19

  • Strings/Array of characters (5): string.h#include #include int main(){

    char name1[20], name2[20], tmp[20];

    int i,L1,L2;

    printf("Input name1: ");scanf("%s",name1);L1=strlen(name1);

    printf("Input name2: ");scanf("%s",name2);L2=strlen(name2);

    20

    printf("name1=%s, length is %d\n", name1,L1);

    printf("name2=%s, length is %d\n", name2,L2);

    strcpy(tmp,name1);

    printf("tmp=%s, length is %d\n",

    name1,strlen(tmp));

    if(strcmp(name1,tmp)==0)

    printf("same\n");

    else

    printf("not same\n");

    return 1;

    }

  • Arrays as Parameters to functions (1)

    Arrays can also be parameters to functions

    The following should however be noted: The dimension of the array should not be included

    in the function declaration and the prototype When a whole array is a parameter it always

    behaves as a reference parameter. Example: void procedure (int arg[])

    Example: int myarray [40];A typical function call for where this array is being passed as parameter is:

    procedure (myarray);

    21

  • Arrays as Parameters to functions (2)

    22

    // Example of using arrays as parameters#include void printarray (int arg[], int length);int main (){

    int firstarray[] = {5, 10, 15};int secondarray[] = {2, 4, 6, 8, 10};printarray (firstarray,3);printarray (secondarray,5);return 0;

    }

    void printarray (int arg[], int length){int n;for (n=0; n

  • TWO-DIMENSIONAL ARRAYS

    23

  • Two-Dimensional Arrays (1)

    Two dimensional arrays can be used tomanipulate tables, and are defined asfollows: [dimesion1][dimension2];

    Exampleint a[3][4];

    We have defined a table with 3 rows and 4columns

    24

  • Two-dimensional arrays (2)

    The elements of a may be shown as a table, as followsa[0][0] a[0][1] a[0][2] a[0][3]a[1][0] a[1][1] a[1][2] a[1][3]a[2][0] a[2][1] a[2][2] a[2][3]

    25

  • Two-dimensional arrays (3) - Rows

    26

    a[0][0] a[0][1] a[0][2] a[0][3] row 0a[1][0] a[1][1] a[1][2] a[1][3] row 1a[2][0] a[2][1] a[2][2] a[2][3] row 2

  • Two-dimensional arrays (4) - Columns

    27

    a[0][0] a[0][1] a[0][2] a[0][3]a[1][0] a[1][1] a[1][2] a[1][3]a[2][0] a[2][1] a[2][2] a[2][3]

    column 0 column 1 column 2 column 3

  • Two-dimensional arrays (5) - Example

    Considerint M[5][3];

    Inputting values in array table:for(row=0;row

  • Two-Dimensional Arrays (2)

    Outputting values of array table:for (x=0; x

  • Two-dimensional arrays as parameters to functions (1)

    When we pass a two dimensional array asa parameter to a function, the value of thefirst dimension is ignored(as for one-dimensional arrays) but the value of thesecond dimension has to be specified

    30

  • Two-dimensional arrays as parameters to functions (2)

    void printarray (int arg[][3], int rows){

    int x, y;for (x=0; x

  • Two-dimensional arrays as parameters to functions (3) A program calling a function that takes as parameter a two-dimensional array

    #include void printarray (int arg[][3], int rows);int main (){

    int M[5][3];int row,col;for(row=0;row

  • Arrays An additional note

    Since arrays are always passed asreference parameters to functions, We can write functions to input values in an

    array

    33

  • Arrays A simple program with functions to input and

    output elements in one-dimensional arrays#include void inputarray(int arg[], int length);void printarray (int arg[], int length);int main (){

    int firstarray[3];int secondarray[5];

    printf("Input details for firstarray\n");inputarray(firstarray,3);

    printf("Input details for secondarary\n");inputarray(secondarray,5);

    printf("firstarray contains: ");printarray (firstarray,3);

    printf("secondarray contains: ");printarray (secondarray,5);return 0;

    }

    34

    void inputarray(int arg[], int length){

    int i;printf("\tInput %d values: ", length);for(i=0;i

  • Arrays A simple program with functions to input and

    output elements in a two-dimensional array#include void inputarray(int arg[][3], int rows);oid printarray (int arg[][3], int rows);int main (){

    int M[5][3];

    inputarray(M,5);printarray(M,5);return 1;

    }

    void inputarray(int arg[][3], int rows){

    int row,col;for(row=0;row

  • Class Exercise Write a program that declares a 2-

    dimensional array to store marks for 15students, in 6 modules for each student. Theprogram also declares a 1-dimensional arrayto store average marks (in 6 modules) for 15students.

    Make use of functions: To input marks of 15 students in six modules To output marks of 15 students in six modules To output average marks of students

    In the function main(), calculate the averagemarks and store in corresponding array.

    36

  • void input(float M[][6], int num){

    int row,col;for(row=0;row

  • void output(float M[][6], int num){

    int row,col;for(row=0;row

  • void output_average(float A[], int num){

    int x;for(x=0;x

  • # include

    void input(float M[][6], int num);void output(float M[][6], int num);void output_average(float A[], intnum);

    int main(){

    float Marks[15][6];float Avg[15];int x,y;float sum;

    input(Marks,15);output(Marks,15);

    40

    for(x=0;x


Recommended