Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Programming Using C Arrays. 2 Contents Arrays Subscripting.

Similar presentations


Presentation on theme: "Introduction to Programming Using C Arrays. 2 Contents Arrays Subscripting."— Presentation transcript:

1 Introduction to Programming Using C Arrays

2 2 Contents Arrays Subscripting

3 3 Arrays All of the variables we have seen hold a single value For some problems, this is sufficient Other problems need to read a great many values and store them Consider the problem of calculating the marks for a class of students

4 4 Arrays Each student has marks for each assignment and test We want to calculate the average mark for each assignment and test as well as the final mark for each student To do this we need – A mark variable to sum up the individual marks for each student and print the result – A variable to hold the sum of all marks for each assignment so we can calculate the average

5 5 Arrays We cannot calculate the average mark for each assignment until we have read all of the marks, so the variables holding the sums need to be stored until the end of the data One solution is to create a series of variables – double item1Total, item2Total, item3Total, item4Total, item5Total, item6Total, item7Total; Now, when we read the data, all we have to do is add onto each total

6 6 Arrays for(i = 1; i <= numMarks; i++) { scanf(“%lf”, mark); studentTotal += mark; switch(i) { case 1: item1Total += mark; break; case 2: item2Total += mark; break; case 3: item3Total += mark; break; case 4: item4Total += mark; break; case 5: item5Total += mark; break; case 6: item6Total += mark; break; case 7: item7Total += mark; break; }

7 7 Arrays That’s a long piece of code to decide which variable to add onto In fact we do the same thing every time and just change the number in the variable name There must be a better way …

8 8 Arrays What we need is – A single variable with one name – That can hold several values – Where we can specify the value we want by its number That is exactly what an array is !

9 9 Arrays We can declare an array called itemTotal that can hold 10 marks like this – double itemTotal[10]; This lays out 10 storage locations, each of which can hold one number Each location is numbered from zero up 0123456789 itemTotal

10 10 Subscripting We can access any member of the array by enclosing its number in square brackets – itemTotal[1] accesses the second member – itemTotal[9] accesses the last member Accessing array members by specifying their position is called subscripting Now that we have arrays, we can rewrite the code to read and store the totals like this

11 11 Subscripting for(i = 1; i <= numMarks; i++) { scanf(“%lf”, mark); studentTotal += mark; itemTotal[i] += mark; } This code is – Shorter – Easier to read – Easier to write – Less prone to error * See arraysumdemo.c

12 12 Passing Arrays to Functions Passing an array by copying all of the values can be an expensive operation if the array is big A better way, is to pass the address of the first member of the array This is the way it is done and you don’t have to use the & operator or the * operator within the function

13 13 Passing Arrays to Functions Let’s say that we want to create a function to fill an array with a single value void fill(int ar[], int value, int size) { int i; for(int i = 0; i < size; i++) { ar[i] = value; }

14 14 Passing Arrays to Functions Things to note – We can indicate an array is being passed using empty square brackets int ar[] You might also see this written as a pointer to an integer int *ar – We cannot determine the size of the array and must pass this as a parameter – We don’t have to dereference the array to access the value, just subscript it – All changes made by the function really affect the original array, not a copy of it

15 15 Passing Arrays to Functions We can call this function as follows #include void fill(int ar[], int value, int size) ; #define SIZE 10 main() { int i, totals[SIZE]; fill(totals, 0, SIZE); for(i = 0; i < SIZE; i++) printf(“%d “, totals[i]); }

16 16 Initializing Arrays Arrays can be initialized by supplying them with values in curly brackets when they are declared – int x[5] = {10, -2, 4, 88, 91}; This is the same as if we had typed – x[0] = 10; – x[1] = -2; – x[2] = 4; – x[3] = 88; – x[4] = 91; * See arrayfinddemo.c

17 17 Initializing Arrays If you – Supply too many values, the extra are discarded – If you don’t supply enough, the remaining elements are set to zero If you do not initialize any variable, you have no idea what its value is This assignment of values to the entire array can only be done once, at initialization time

18 18 Character Strings It is common to want to store strings in your programs A string is stored as – An array of characters of a fixed length – A special character ‘\0’ that marks the end of the string, which might be shorter than the array in which it is stored

19 19 Character Strings We can declare a character array to hold a string like this – char name[10]; – Which will allow us to store up to 9 letter names plus the string terminator ‘\0’ String constants are always enclosed in double quotes – “Fred”

20 20 Character Strings What is actually generated is – “Fred\0” – Since the ‘\0’ terminator is automatically appended to all string constants Assigning a string constant to an array is not straight-forward and requires that we use a function called strcpy()

21 21 Character Strings To assign our name to the array we type – strcpy(name, “Fred”); – This has the effect of copying the value of the 2 nd parameter to the 1 st parameter – The direction of the assignment is right-to-left just like the assignment operator After the assignment, out array looks like this 0123456789 name Fred\0

22 22 Character Strings The string terminator is actually the null character and has the numeric value 0 If you look at an ASCII table, you will see it as the first value in the table Since it does not print as anything, we cannot type it, so use the special notation – ‘\0’

23 23 strcpy To see how strcpy works, let’s write our own void mystrcpy(char to[], char from[]) { int i; for(i = 0; from[i] != ‘\0’; i++) { to[i] = from[i]; } to[i] = ‘\0’; }

24 24 strcpy As you can see, this is just regular code which copies characters one-by-one from one array to another Note how it watches for the string terminator and how it adds one to the destination string Remember, strcpy cannot determine the size of the destination array and you should be careful not to copy a string which is too big to it

25 25 Assigning Strings A lot of students tell me this works – name = “Fred”; /* wrong, wrong, wrong !! */ – What it does is copy the address of the first letter of “Fred” to the variable name – Now, the compiler stores “Fred” in a temporary location, which can be reused at any time – So, for a while it might seem to work, but it’s a disaster waiting to happen

26 26 strlen This is another commonly used function which returns the length of a string It returns all of the characters before the string terminator char address[20]; int len; strcpy(address, “21 Main St.”); len = strlen(address); printf(“The length is %d\n”, len);/* prints 11 */

27 27 strcmp We cannot compare strings with the relational operators – if(“dog” > “cat”)/* wrong ! */ To compare strings we use strcmp – int strcmp(char first[], char second[]) Which returns – <0 if first is smaller than second – 0 if first equals second – >0 if first is larger than second

28 28 strcmp So, what do we mean by larger and smaller It is almost the same as alphabetical order but is based on the ASCII table rather than just the 26 letters in the alphabet Therefore – ‘A’ < ‘a’ – ‘1’ < ‘A’ – ‘0’ < ‘1’ – ‘A’ < ‘B’ – ‘a’ < ‘b’ * See stringfuncdemo.c

29 29 String Input and Output You could write a function to output a string like this void printString(char s[]) { int i; for(I = 0; s[i] != ‘\0’; i++) printf(“%c”, s[i]); }

30 30 String Input and Output But this capability is builtin to printf – printf(“%s\n”, “Hello, World!”); As with the other format specifications, you can control the width of the field You can also control the maximum number of characters which will be printed using a decimal notation

31 31 String Input and Output The following prints a maximum of 10 characters, right justified is a field 15 characters wide – printf(“%-15.10s”, mystring); The %s format can also be used with scanf with the following caveats – You do not need an & in front of the array which will receive the string – It will read text until it finds whitespace and stop

32 32 String Input and Output For example char name[31]; printf(“Enter your name: “); scanf(“%s”, name); There is another notation that lets you specify a list of valid characters and stop reading when any other character is found

33 33 String Input and Output The following will read Y or N in either case – scanf(“%[yYnN]”, answer); This will read any string containing alphabetic characters and the space – scanf(“%[ a-zA-Z]”, name); The ^ symbol indicates everything except the characters shown The following will read everthing until the end of line – scanf(“%[^\n]”, line);

34 34 String Input and Output You can also indicate a maximum field width so that it will not read more data than your string can hold – scanf(“%30[^\n]”, name); – This will not read more than 30 characters To read an entire line and discard the newline – scanf(“%[^\n]%*c”, line); – This action is also done by the function gets() – gets() will work with an empty line whereas the scanf will not

35 35 Reading a Line All of the library functions have drawbacks – Can overflow the buffer – Do not all handle empty lines the same Therefore, let’s write our own void get_a_line(char line[], int max) { int n = 0; char c; while(‘\n’ != (c = getchar())) { if(n < max) line[n++] = c; } line[n] = ‘\0’; }

36 36 2-D Arrays So far, the arrays we have seen look like lists We can also have arrays which look like tables Rather than just having a position for each value, they have a row and column for each value

37 37 2-D Arrays ill\0B hristine C arlene D om T lice A char names[5][11]; rows 0 1 2 3 4 columns 012345678910

38 38 2-D Arrays You can subscript a 2-D array by specifying the row and column numbers – names[0][3]/* c */ One of the common uses of 2-D arrays is to store arrays of strings This is just like an array of integers, except each member of the array is a complete string

39 39 2-D Arrays One of the differences between a 1-D array and a 2-D array is how it is passed to a function – void somefunc(char names[][11]); – When passed as a parameter, you must indicate the number of columns in the array Another useful technique is that you can treat each row in the array as if it was a string

40 40 Arrays of Strings Accessing a string in a 2-D array involves a trick – When you subscript a 2-D array with only 1 subscript, it accesses an entire row – Thus, if we use names[1], it accesses the name “Bill” To read into a row in our 2-D array – gets(names[i]); * See string_sorter.c


Download ppt "Introduction to Programming Using C Arrays. 2 Contents Arrays Subscripting."

Similar presentations


Ads by Google