Programming Two Lecture 5 - Arrays 2013feb12
Programming Two Lecture 5 - Arrays 2013feb12
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
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 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.
Are new data types formed by combining other atomic and/or composite data types, Can potentially store more than one value at a time
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
const, volatile
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 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
//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]); } }
A loop is used here to iterate through the elements of the array and display them
Use a loop to allow the user to enter 5 values for the array
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'};
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
#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]); } }
#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]); }
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
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
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