Presentation is loading. Please wait.

Presentation is loading. Please wait.

Arrays in C.

Similar presentations


Presentation on theme: "Arrays in C."— Presentation transcript:

1 Arrays in C

2 Topics Covered Arrays Declaring and initialising arrays
what are they how are they used Declaring and initialising arrays Multiple dimension arrays Strings and string processing Internal representation of arrays Common array operations

3 Introduction to Arrays
Single variables are ok for simple programs, if data requirements are small, and well known program always does the same thing, with the same data program is not expected to grow larger over time Most ‘real-world’ problems don’t meet these criteria Need some sort of large data storage facility to handle increased information needs Arrays are one way of accomplishing this! they are not the only way

4 What is an Array? An array is a mechanism whereby a single variable name refers to multiple pieces of data int a ; int ar[] ; 6 3 -1 7 14 ‘normal’ variable array

5 How are Arrays Used? Arrays are declared and accessed in C using the [] operator Declaration: int ar[10] ; Usage: ar[0] = 3 ; ar[5] = 7 ; size of array type of variable name of array element to be accessed

6 Array Sizes Arrays of any size can be declared
up to limits of memory! The valid indices of an array run from 0 to size – 1 eg, an array declared as: int ar[10] valid indices are 0..9, NOT 10!

7 Initialising Arrays Arrays, like other variables, can be initialised when declared Syntax: int integer_array[10] = { 3, 5, 1, -1, 0, 7, 10, 2, 9, 2 }; OR int integer_array[] = { 3, 5, 1, -1, 0, 7, 10, 2, 9, 2 } ; size of array >= # of values size of array is determined by initialisation values, in this case 10

8 Array Example Simple program to read and store 10 numbers, then display them back to the screen int main ( void ){ int i, ar[10] ; for ( i = 0 ; i < 10 ; i++ ){ scanf ( “%d”, &ar[i] ) ; } printf ( “%d\n”, ar[i] ) ;

9 Size of Arrays There is no easy way to tell how big an array is
unlike other languages, no size function, etc, to tell you If you pass an array to a function, you should always pass a second variable to let the function know how big the array is int process_array ( int ar[], int size ) ; Often, the total size of the array is of little interest, more important is how many values are actually in use

10 Size of Arrays int main ( void ){ int size = 0, num = 1, ar[50], i ;
while ( size < 50 && num != 0 ){ printf ( “Please enter a number (0 to quit): “ ) ; scanf ( “%d”, &num ) ; if ( num != 0 ){ ar[size++] = num ; } printf ( “The user entered %d numbers before 0\n”, size ) ; for ( i = 0 ; i < size ; i++ ){ printf ( “%d: %d\n”, i+1, ar[i] ) ;

11 Strings C has no special type for strings, they are simply arrays of chars each character is one element of the array, with an extra character for the ‘end of string’ character ‘\0’ (or just 0) Declaring a string: char str[20] ; // 20 character long string Initialising is done somewhat differently than ‘normal’ arrays char str[] = “Hello world” ; note this allocates 12 bytes, not 11, as one is required for the “end of string” character

12 Manipulating Strings Strings are somewhat different to other variables
cannot be directly assigned or compared do not require the & prefix with scanf special library functions are available <string.h> Individual characters can be accessed and modified like any other array, eg: str[5] = ‘a’ ; // set the 6th character to ‘a’ printf ( “The 1st character is %c\n”, str[0] ) ; The C compiler will recognise literal strings enclosed in double quotes (“ “) and store them accordingly

13 Manipulating Strings INCORRECT CORRECT #include <stdio.h>
int main ( void ){ char str1[20], str2[20] ; str1 = “Hello world!” ; scanf ( “%s”, &str2 ) ; if ( str2 == “quit” ){ printf ( “all done!” ) ; } #include <stdio.h> #include <string.h> int main ( void ){ char str1[20], str2[20] ; strcpy(str1,“Hello World!”); scanf ( “%s”, str2 ) ; if (strcmp(str2,“quit”)==0){ printf ( “all done!” ) ; }

14 The ‘null’ Character Strings need to have a character so the computer knows where they end remember, there’s no way to tell the size of an array! This special character is known as the ‘null’ character, and can be written in a few ways ‘\0’ the backslash indicates an actual value 0 the actual value itself, in ASCII To get an idea of how this works, consider the following example..

15 The ‘null’ Character int main ( void ){ char string[10] ; strcpy ( string, “hello” ); printf ( “%s\n”, string ); // should print hello string[3] = 0 ; printf ( “%s\n”, string ) ; // what will it print now?! } Remember, printf() uses the null character as its cue to stop printing the string! strcpy, strcmp, do exactly the same thing.. ? ? ? ? ? ? ? ? ? ? ‘h’ ‘e’ ‘l’ ‘l’ ‘o’ ? ? ? ? ‘h’ ‘e’ ‘l’ ‘o’ ? ? ? ?

16 Common String Functions
The following string functions are very commonly used, remember them! strcpy ( char dest[], char src[] ) ; copies the string src into dest, overwriting whatever is there. ASSUMES that dest is big enough! strcmp ( char str1[], char str2[] ) ; compares str1 and str2 which are null terminated strings of characters. Returns 0 if they are equal, otherwise a non-zero value strlen ( char str[] ) ; calculates the length of the null terminated string str and returns this value. strcat ( char dest[], char src[] ) ; appends the null terminated src to the end of dest There are many more functions in <string.h>, you might like to have a look…

17 Multidimensional Arrays
C supports the use of higher dimensional arrays, which are declared with the syntax: int m_dim_array[10][20] ; // a 10x20 array of ints When initialising such arrays, only the size of the first dimension can be left blank! char names[][50] = { “Fred”, “Mary”, “Joe” } ; this is also true of functions that accept N-D arrays as arguments – all dimensions except the 1st MUST be supplied!

18 Multidimensional Arrays
You can think of 2D arrays as being like a grid of values In reality, they are actually stored as a 1D array of size 3x4 = 12 ar[2][2] is the same as ar[0][10], is the same as ar[1][6], since 2*4+2 = 0*4+10 = 1*4+6 they are all at index 10 of the ‘equivalent’ 1D array int ar[3][4] ; Imagined layout ar[0][0] ar[0][1] ar[0][2] ar[0][3] ar[1][0] ar[1][1] ar[1][2] ar[1][3] ar[2][0] ar[2][1] ar[2][2] ar[2][3] Actual physical layout ar[0][0] ar[0][1] ar[0][2] ar[0][3] ar[1][0] ar[1][1] ar[1][2] ar[1][3] ar[2][0] ar[2][1] ar[2][2] ar[2][3]

19 Common Array Operations
‘for’ loops and arrays are almost inevitably linked, and are used when: reading values into arrays processing arrays displaying arrays The most common syntax is: for ( i = 0 ; i < size ; i++ ){ … where size is the number of elements in the array (not necessarily the total size!)

20 Examples Function to calculate the average of an array of floats:
float avg ( float ar[], int size ){ // note the SIZE variable in the declaration! int i ; float total = 0 ; for ( i = 0 ; i < size ; i++ ){ total += ar[i] ; } return ( total / size ) ;

21 Examples Function to calculate the maximum of an array of ints:
int max ( int ar[], int size ){ // note the SIZE variable in the declaration! int i, m = ar[0] ; // the FIRST value starts as the max for ( i = 1 ; i < size ; i++ ){ if ( ar[i] > m ){ m = ar[i] ; } return ( m ) ;

22 Examples Function to calculate the maximum of a 2D array of ints:
int max ( int ar[][10], int size ){ // the size of the second dimension MUST be given! // the size variable refers to the first dimension only int i, j ; int m = ar[0][0] ; // the FIRST value starts as the max for ( i = 0 ; i < size ; i++ ){ for ( j = 0 ; j < 10 ; j++ ){ if ( ar[i][j] > m ){ m = ar[i][j] ; } return ( m ) ;

23 Examples An array of STRINGS is really a 2D array.. int main ( void ){
char names[][50] = { “Fred”, “Mary”, “John”, “Katherine” } ; // second dimension size MUST be supplied – first is automatically // set to 4 as four strings are given.. int longest = 0 ; // this is the INDEX of the longest name, // NOT the length, or the name itself! int i ; for ( i = 0 ; i < 4 ; i++ ){ printf ( “Name %d: %s\n”, i+1, names[i] ) ; if ( strlen ( names[i] ) > strlen ( names[longest] ){ longest = i ; } printf(“The longest name is (%d) %s\n”,longest+1,names[longest]);

24 Final Thoughts.. Arrays are actually addresses which are the location of the first element in memory when you access an element of the array it adds the index value to this address and accesses that piece of memory ar[2] really means: get the data at the address ar+2 when performing these calculations, the size of each element is taken into account, so for an integer array, ar[2] is actually ar+(2*4) This is why we don’t need the & (address) operator when reading strings – they array is ALREADY an address! This property of arrays can be used to do some pretty handy things..

25 Using Arrays as Addresses
Consider: int main ( void ){ char str[20] = “Hello world!” ; printf ( “%s\n”, &str[3] ) ; } What will the output be!?!


Download ppt "Arrays in C."

Similar presentations


Ads by Google