You are on page 1of 26

Programming II - CMP1025

Lecture Five Arrays By David W. White dwwhite@utech.edu.jm University of Technology, Jamaica February 12, 2013

Expected Outcome
At the end of this lecture, the student should be 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) using the character handling library and string functions in a computer program

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

Atomic data types


Revision:

Data types are used to declare what type of data a variable will be allowed to store Atomic data types are the primitive data types in a language Atomic data types are the simplest, most basic data types in a language they cant be broken down into any smaller data types

Atomic data types

Atomic data types only store one item of data at a time 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 atomic and/or composite data types, Can potentially store more than one value at a time

Atomic data types


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

char : represents individual characters int : represent an integer in the range -2,147,483,648 to 2,147,483,647 float : represents a single precision floating point number in the range 3.4 x 1038 double : represents a double precision floating point number in the range 1.7 x 10308

Atomic data types

Modifiers for atomic data types:


short, long, signed, unsigned

Qualifiers for atomic data types:


const, volatile

Array data types

An array is a collection or list of elements of the same 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 the list, starting from 0 for the first element Array elements are always stored consecutively, so the element at index 1 is beside index 0, etc

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

Declaring and defining array 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.

Declaring and defining array variables


//arrays declaration example int 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 declared here, but it is not initialized

Initialization done separately here

Declaring and defining array 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};

Declaring and defining array variables

//arrays declaration example int 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 the array and display them

Declaring and defining array variables


//arrays declaration example 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]); } }

Use a loop to display the contents of the array

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

Use a loop to redisplay the contents of the array

Using array variables


Examples

int A[5]={1,2,3,4,5}; //initializes elements to A[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'};

Passing array variables to a module

To pass an array to a function, specify the name of 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, specify the array name and element's index e.g.: PrintTopScore(Score[3]); //only element 4 passed

Passing array variables to a module


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

#include <stdio.h> 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 <stdio.h> 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]); } }

Passing array variables to a module


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

#include <stdio.h> 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 <stdio.h> 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]); }

Passing array variables to a module


Note how the array is represented in the function prototype. The array name Is optional #include <stdio.h> 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]); }

However, in the function header, the array name and the name of the size argument are mandatory

Unlike normal variables, arrays are passed by reference so any change made to the contents of the array in the function are reflected in the original array Address-of operator needed in scanf to read single integer into array

Arrays of characters

C doesn't have an explicit string data type Instead, it uses an array of characters to represent a 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 always placed at the end of a character array to mark the end of a string

Arrays of characters
char string1[ ]="hi class";

The '\0' is automatically placed at the end of the string in this 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 and separated by comma, placed inside { }

Arrays of characters
//character string example #include <stdio.h> 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 of the first two, then accepts a string from the user using scanf, and stores it in the third array. It then flushes the input stream and accepts another string into string3 using gets, and then displays it on the screen using puts. Note: gets is not safe to use as is can cause buffer overflow. Use getline Instead. Also fflush has some quirks.

Arrays of characters
//character string example #include <stdio.h> 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 so will contain garbage values Display string1 and string2 using printf Read a word from the user Into string3 using scanf. Notice address of operator (&) is not placed in front of the array Name, as done with other variables fflush clears the input buffer and gets reads a string from the user puts displays a string on the standard output device

Character string handling library functions

A wealth of string handling functions are found in the string.h library, included with C #include <string.h> 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

Character string handling library functions

strlen(str) returns the size/length of a character string not including the null character at the end of the string strcmp(s1,s2) compares two strings and returns 0 if s1 is equal to s2, negative number if s1 < 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 the contents of s2 are copied into s1

Character string handling library functions


#include <stdio.h> #include <string.h> 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 this program in your mind to determine what it will output, then actually run the program to see if the results are what you expected

You might also like