+ All Categories
Home > Documents > Programming Two Lecture 5 - Arrays 2013Feb12

Programming Two Lecture 5 - Arrays 2013Feb12

Date post: 03-Apr-2018
Category:
Upload: stephan-smith
View: 221 times
Download: 0 times
Share this document with a friend

of 26

Transcript
  • 7/28/2019 Programming Two Lecture 5 - Arrays 2013Feb12

    1/26

    Programming II - CMP1025

    Lecture Five Arrays

    By David W. [email protected]

    University of Technology, Jamaica

    February 12, 2013

  • 7/28/2019 Programming Two Lecture 5 - Arrays 2013Feb12

    2/26

    Expected Outcome

    At the end of this lecture, the student shouldbe able to:

    Appreciate the concept of an array data type

    Declare, define and use array variables

    Demonstrate how arrays are passed to modules(C functions)

    Manipulate arrays of characters (strings) usingthe character handling library and stringfunctions in a computer program

  • 7/28/2019 Programming Two Lecture 5 - Arrays 2013Feb12

    3/26

    Topics

    Atomic data types

    Array data types

    Declaring and defining array variables Using array variables

    Passing array variables to a module

    Arrays of characters Character string handling library functions

  • 7/28/2019 Programming Two Lecture 5 - Arrays 2013Feb12

    4/26

    Atomic data types

    Revision:

    Data types are used to declare what type ofdata a variable will be allowed to store

    Atomic data types are the primitive data typesin a language

    Atomic data types are the simplest, most basic

    data types in a language they cant bebroken down into any smaller data types

  • 7/28/2019 Programming Two Lecture 5 - Arrays 2013Feb12

    5/26

    Atomic data types

    Atomic data types only store one item of data at atime e.g.

    int j = 10;

    In this example j can only hold one value at a time e.g.10. If 11 is placed in j the old value of 10 is erased.

    Opposite of composite data types:

    Are new data types formed by combining other atomicand/or composite data types,

    Can potentially store more than one value at a time

  • 7/28/2019 Programming Two Lecture 5 - Arrays 2013Feb12

    6/26

    Atomic data types

    There are only four (4) atomic data types in the Cprogramming language:

    char : represents individual characters

    int : represent an integer in the range -2,147,483,648to 2,147,483,647

    float : represents a single precision floating pointnumber in the range 3.4 x 1038

    double : represents a double precision floating pointnumber in the range 1.7 x 10308

  • 7/28/2019 Programming Two Lecture 5 - Arrays 2013Feb12

    7/26

    Atomic data types

    Modifiers for atomic data types:

    short,

    long,

    signed,

    unsigned

    Qualifiers for atomic data types: const,

    volatile

  • 7/28/2019 Programming Two Lecture 5 - Arrays 2013Feb12

    8/26

    Array data types

    An array is a collection or list of elements of thesame data type

    The entire array is referenced by a single

    identifier name the name of the array Individual elements in the array can be accessed

    via its index or subscript

    This index is the position of the element in thelist, starting from 0 for the first element

    Array elements are always stored consecutively,so the element at index 1 is beside index 0, etc

  • 7/28/2019 Programming Two Lecture 5 - Arrays 2013Feb12

    9/26

    Array data types

    Array can have multiple dimensions, for example,a n x m matrix

    This lecture will focus on single dimension arrays

    (which have only a single row of data) A later lecture will examine multiple dimension

    arrays

    For each dimension, the index starts from 0

    This is called zero-based indexing

  • 7/28/2019 Programming Two Lecture 5 - Arrays 2013Feb12

    10/26

    Declaring and definingarray variables

    Declaration Format:

    DataType ArrayName[ArraySize];

    e.g.

    int Score[10]; //declare array Score to hold

    //ten integers

    Definition/initialization:

    ArrayName[Index] = value;

    e.g.

    Score[0] = 50; //set the first element to 50.

  • 7/28/2019 Programming Two Lecture 5 - Arrays 2013Feb12

    11/26

    Declaring and definingarray variables

    //arrays declaration exampleint main(){

    int Score[5];

    int index;

    Score[0] = 51;Score[1] = 89;Score[2] = 63;Score[3] = 92;Score[4] = 75;

    for(index = 0; index < 5; ++index){

    printf("%d\n",Score[index]);}

    }

    Array Score is just declaredhere, but it is not initialized

    Initialization done separatelyhere

  • 7/28/2019 Programming Two Lecture 5 - Arrays 2013Feb12

    12/26

    Declaring and definingarray variables

    Declaration and Initialization Format:

    DataType ArrayName[ArraySize] = {element1,element2, , elementN};

    e.g.

    //declare array A to hold ten integers, and//initialized the array to 1,2,3...10 respectively

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

  • 7/28/2019 Programming Two Lecture 5 - Arrays 2013Feb12

    13/26

    Declaring and definingarray variables

    //arrays declaration exampleint main()

    {int Score[5] = {51,89,63,92,75};int index;

    for(index = 0; index < 5; ++index){

    printf("%d\n",Score[index]);}

    }

    Declaration and initialization

    done in the same line here

    A loop is used here to iterate

    through the elements of thearray and display them

  • 7/28/2019 Programming Two Lecture 5 - Arrays 2013Feb12

    14/26

    Declaring and definingarray variables

    //arrays declaration exampleint main(){

    int Score[5] = {0};int index;

    for(index = 0; index < 5; ++index){

    printf("%d\n",Score[index]);}

    for(index = 0; index < 5; ++index)

    { scanf("%d",&Score[index]);}

    for(index = 0; index < 5; ++index){

    printf("%d\n",Score[index]);

    }}

    Use a loop to display thecontents of the array

    Use a loop to allow the userto enter 5 values for the array

    Use a loop to redisplay thecontents of the array

  • 7/28/2019 Programming Two Lecture 5 - Arrays 2013Feb12

    15/26

    Using array variables

    Examples

    int A[5]={1,2,3,4,5}; //initializes elements toA[0]=1, a[1] =2, a[2]=3, a[3]=4, a[4]=5

    int A[5]={0}; //initializes all 5 elements to 0

    float FA[3] = {9.10f, 9.58f, 9.23f};

    scanf(%f, &FA[2]);

    printf(The third element is %f,FA[2]);

    double DA[3] = {9.10, 9.58, 9.23};

    char CA[4] = {'A', 'B', 'C', 'D'};

  • 7/28/2019 Programming Two Lecture 5 - Arrays 2013Feb12

    16/26

    Passing array variables to a module

    To pass an array to a function, specify the nameof the array and its size in the function call

    Consider the following array:

    int Score[5] = {51,89,63,92,75}; //Declaration

    To pass this array to a function Display()

    Display(Score, 5); //array passed to function

    To pass just a single element of the array, specifythe array name and element's index e.g.:

    PrintTopScore(Score[3]); //only element 4 passed

  • 7/28/2019 Programming Two Lecture 5 - Arrays 2013Feb12

    17/26

    Passing array variables to a module

    #include int main(){

    int Score[5] = {0};int index;

    for(index = 0; index < 5; ++index){

    printf("%d\n",Score[index]);}

    for(index = 0; index < 5; ++index)

    { scanf("%d",&Score[index]);}

    for(index = 0; index < 5; ++index){

    printf("%d\n",Score[index]);

    }}

    #include void Display(int [ ], int);

    int main(){

    int Score[5] = {51,89,63,92,75};int i;Display(Score, 5);for(i = 0; i < 5; ++i){

    scanf("%d",&Score[i]);}Display(Score, 5);

    }void Display(int Arr[], int Size){

    int index;for(index = 0; index < Size; ++index){

    printf("%d\n",Arr[index]);

    }}

    These two programs do the same task but in the 2nd version, the array is passed to a function

  • 7/28/2019 Programming Two Lecture 5 - Arrays 2013Feb12

    18/26

    Passing array variables to a module

    #include int main(){

    int Score[5] = {0};int index;

    for(index = 0; index < 5; ++index){printf("%d\n",Score[index]);

    }

    for(index = 0; index < 5; ++index){

    scanf("%d",&Score[index]);}

    for(index = 0; index < 5; ++index){

    printf("%d\n",Score[index]);}

    }

    #include void Display(int [ ], int);void InputScores(int [ ], int);int main(){

    int Score[5] = {51,89,63,92,75};Display(Score, 5);

    InputScores(Score, 5);Display(Score, 5);}void Display(int Arr[ ], int Size){

    int index;for(index = 0; index < Size; ++index)

    printf("%d\n",Arr[index]);}void InputScores(int Arr[ ], int Size){

    int index;

    for(index = 0; index < Size; ++index)

    scanf("%d",&Arr[index]);}

    These two programs do the same task but in the 2nd version, the array is passed to a function

  • 7/28/2019 Programming Two Lecture 5 - Arrays 2013Feb12

    19/26

    Passing array variables to a module

    #include void Display(int [ ], int);void InputScores(int [ ], int);int main(){

    int Score[5] = {51,89,63,92,75};Display(Score, 5);

    InputScores(Score, 5);Display(Score, 5);}void Display(int Arr[ ], int Size){

    int index;for(index = 0; index < Size; ++index)

    printf("%d\n",Arr[index]);}void InputScores(int Arr[ ], int Size){

    int index;

    for(index = 0; index < Size; ++index)

    scanf("%d",&Arr[index]);}

    Note how the array is represented in

    the function prototype. The array nameIs optional

    However, in the function header, the arrayname and the name of the size argumentare mandatory

    Unlike normal variables, arrays are passed

    by reference so any change made to thecontents of the array in the function arereflected in the original array

    Address-of operator needed in scanf toread single integer into array

  • 7/28/2019 Programming Two Lecture 5 - Arrays 2013Feb12

    20/26

    Arrays of characters

    C doesn't have an explicit string data type

    Instead, it uses an array of characters to representa string

    e.g. the string hi class can be represented as:

    char string1[ ]="hi class";

    char string2[ ]={'h', 'i', ' ', 'c', 'l', 'a', 's', 's', '\0'};

    char string3[9]={'h', 'i', ' ', 'c', 'l', 'a', 's', 's', '\0'};

    Note '\0'(known as the NULL character) is alwaysplaced at the end of a character array to mark the

    end of a string

  • 7/28/2019 Programming Two Lecture 5 - Arrays 2013Feb12

    21/26

    Arrays of characters

    char string1[ ]="hi class";

    The '\0' is automatically placed at the end of the string inthis format

    Size of string (8+1=9 chars) is automatically calculated

    char string2[ ]={'h', 'i', ' ', 'c', 'l', 'a', 's', 's', '\0'};

    The '\0' must be explicitly placed at the end of the string in

    this format

    Size of string (8+1=9 chars) is still automatically calculated

    Individual elements delimited by single quote andseparated by comma, placed inside { }

  • 7/28/2019 Programming Two Lecture 5 - Arrays 2013Feb12

    22/26

    Arrays of characters

    //character string example#include

    int main(){

    char string1[] = "hi class";char string2[] = {'h', 'i', ' ', 'c', 'l', 'a', 's', 's', '\0'};

    char string3[20];

    printf("String one has %s\n", string1);printf("String two has %s\n", string2);

    scanf("%s", string3);printf("String three has %s\n", string3);

    fflush(stdin);gets(string3);printf("String three now has %s\n", string3);

    puts("string three still contains ");puts(string3);

    }

    This program declares three

    character arrays: string1,String2 and string3.

    It displays the contents ofthe first two, then acceptsa string from the user usingscanf, and stores it in the

    third array.

    It then flushes the inputstream and accepts anotherstring into string3 usinggets, and then displaysit on the screen using puts.

    Note:gets is not safe to useas is can cause bufferoverflow. Use getlineInstead.

    Also fflush has some quirks.

  • 7/28/2019 Programming Two Lecture 5 - Arrays 2013Feb12

    23/26

    Arrays of characters

    //character string example#include

    int main(){

    char string1[] = "hi class";char string2[] = {'h', 'i', ' ', 'c', 'l', 'a', 's', 's', '\0'};

    char string3[20];

    printf("String one has %s\n", string1);printf("String two has %s\n", string2);

    scanf("%s", string3);printf("String three has %s\n", string3);

    fflush(stdin);gets(string3);printf("String three now has %s\n", string3);

    puts("string three still contains ");puts(string3);

    }

    Declaration of the 3 arrays.

    string3 in not initialized sowill contain garbage values

    Display string1 and string2using printf

    Read a word from the userInto string3 using scanf.Notice address of operator (&)is not placed in front of the arrayName, as done with othervariables

    fflush clears the input bufferand gets reads a string fromthe user

    puts displays a string on the

    standard output device

    h i h dli

  • 7/28/2019 Programming Two Lecture 5 - Arrays 2013Feb12

    24/26

    Character string handlinglibrary functions

    A wealth of string handling functions are found inthe string.h library, included with C

    #include

    Popular ones include:

    strlen returns the size of a character string

    strcmp compares two strings

    strcat concatenate two strings

    strcpy copies a string

    A lot more string functions are found in string.h

    Ch i h dli

  • 7/28/2019 Programming Two Lecture 5 - Arrays 2013Feb12

    25/26

    Character string handlinglibrary functions

    strlen(str) returns the size/length of a characterstring not including the null character at the endof the string

    strcmp(s1,s2) compares two strings andreturns 0 if s1 is equal to s2, negative number ifs1 < s2, and positive number if s1 > s2

    strcat(s1,s2) concatenate two strings, the

    result is s2 is joined to s1

    strcpy(s1,s2) copies a string, the result is thecontents of s2 are copied into s1

    Character string handling

  • 7/28/2019 Programming Two Lecture 5 - Arrays 2013Feb12

    26/26

    Character string handlinglibrary functions

    #include

    #include

    int main(){

    char string1[] = "hi class";char string2[] = {'h', 'i', ' ', 'c', 'l', 'a', 's', 's', '\0'};char string3[] = "bye class";

    printf("The length of string 1 is %d\n", strlen(string1));printf("The length of string 2 is %d\n", strlen(string2));printf("The length of string 3 is %d\n", strlen(string3));

    printf("Comparing string1 and string2 gives %d\n", strcmp(string1,string2));printf("Comparing string1 and string3 gives %d\n", strcmp(string1,string3));

    printf("Comparing string3 and string1 gives %d\n", strcmp(string3,string1));

    strcat(string2,string3);printf("Concatenting string2 and string3 gives %s\n", string2);

    strcpy(string2,string3);printf("Copying string3 to string2 gives %s\n", string2);

    }

    Trace through thisprogram in yourmind to determine

    what it will output,then actually run theprogram to see if theresults are what youexpected


Recommended