Download presentation
Presentation is loading. Please wait.
1
1 TDBA66, VT-04, Lecture Ch7 One dimensional Arrays A data structure (vector) with many elements of the same type A common name where individual elements are accessed by an index inside [ ] Declartion int list[25], a[10]; /* 10 elements in a referenced by a[0], a[1],……., a[9] */ double x[20];
2
2 TDBA66, VT-04, Lecture Ch7 example /* * Example of a simple list of integers */ #include int main(void) { int res[10]; /* Note! index = 0..9 */ int i; for (i=0;i<=9;i++) { res[i] = 10-i; printf("res[%d]=%d\n",i,res[i]); } return 0; }
3
3 TDBA66, VT-04, Lecture Ch7 Initialization The elements can be initialized at declaration int res[10]={10,9,8,7,6,5,4,3,2,1}; If the initializing list is shorter, the rest of the elements are 0 int res[10]={0}; /* all elements are initialized to 0 */ The number of elements can be omitted if all elements in the array are initialized at declaration int res[]={10,9,8,7}; /* 4 elements with index 0..3 */
4
4 TDBA66, VT-04, Lecture Ch7 Indexing arrayname[integral expression] Where integral expression is evaluated to an integer value (int or char) Important to keep the integral expression inside the range of the indeces ( see Table 7.2 on page 310) An array element can be used wherever it is legal to use a variable of the data type in question Ex. 1 double x[10]; int n; printf(”How many elements should you type (<11): ”); scanf(”%d”, &n); /* should be validated! */ fflush(stdin); for (i=0; i<n; i++) scanf(”%lf”, &x[i]);
5
5 TDBA66, VT-04, Lecture Ch7 Figure 7.2 Program to Print a Table of Differences /* * Computes the mean and standard deviation of an array of data and * displays the difference between each value and the mean. */ #include #define MAX_ITEM 8 /* maximum number of items in list */ int main(void) { double x[MAX_ITEM], /* data list*/ mean, /* mean (average) of the data*/ st_dev, /* standard deviation of the data*/ sum, /* sum of the data*/ sum_sqr; /* sum of the squares of the data*/ int i; /* Gets the data*/ printf("Enter %d numbers separated by blanks\n> ", MAX_ITEM); for (i = 0; i < MAX_ITEM; ++i) scanf("%lf", &x[i]);
6
6 TDBA66, VT-04, Lecture Ch7 /* Computes the sum and the sum of the squares of all data*/ sum = 0; sum_sqr = 0; for (i = 0; i < MAX_ITEM; ++i) { sum += x[i]; sum_sqr += x[i] * x[i]; } /* Computes and prints the mean and standard deviation*/ mean = sum / MAX_ITEM; st_dev = sqrt(sum_sqr / MAX_ITEM - mean * mean); printf("The mean is %.2f.\n", mean); printf("The standard deviation is %.2f.\n", st_dev); /* Displays the difference between each item and the mean */ printf("\nTable of differences between data values and mean\n"); printf("Index Item Difference\n"); for (i = 0; i < MAX_ITEM; ++i) printf("%3d%4c%9.2f%5c%9.2f\n", i, ' ', x[i], ' ', x[i] - mean); return (0); }
7
7 TDBA66, VT-04, Lecture Ch7 Array names as formal parameters in functions Single subscripted arrays as formal parameters to a function are declared as in Fig. 7.4 (HOW TO CALL IT?) Figure 7.4 Function fill_array /* * Sets all elements of its array parameter to in_value. */ void fill_array (int list[], /* output - list of n integers*/ int n, /* input - number of list elements*/ int in_value) /* input - initial value*/ { int i; /* array subscript and loop control*/ for (i = 0; i < n; ++i) list[i] = in_value; } Introduce the concept of int *list
8
8 TDBA66, VT-04, Lecture Ch7 Returning an Array Result A function can’t return a complete array but it can return a pointer to an array Another solution is to use an array name as output parameter (see Fig. 7.8) Figure 7.8 Function to Add Two Arrays /* * Adds corresponding elements of arrays ar1 and ar2, storing the * result in arsum. Processes first n elements only. */ void add_arrays(const double ar1[], /* input -*/ const double ar2[], /* arrays being added*/ double arsum[], /* output - sum of corresponding elements of ar1 and ar2 */ int n) /* input-number of element pairs summed */ { int i; /* Adds corresponding elements of ar1 and ar2*/ for (i = 0; i < n; ++i) arsum[i] = ar1[i] + ar2[i]; }
9
9 TDBA66, VT-04, Lecture Ch7 Dynamic allocation of arrays We can allocate space (memory cells) for an array by using calloc() Syntax: double *num_list; ……… num_list = (double *) calloc(list_size, sizeof (double)); Calloc() returns a pointer to void: that value should be cast to a pointer which points to the data type in question Normally the allocated space should be freed before the program is ended. Use function free(pointername) Include to get access to calloc() and free() Ex. 1: write function add_arrays() such that it returns a pointer to the new array that contains the sum of the two arrays which are pointed to by the two input parameters
10
10 TDBA66, VT-04, Lecture Ch7 Figure 7.8 revised Function to Add Two Arrays /* * Adds corresponding elements of arrays ar1 and ar2, storing the * result in ar_sum. Processes first n elements only. */ #include double * add_arrays2(const double ar1[], /* input -*/ const double ar2[], /* arrays being added*/ int n) /* input-number of element pairs summed */ { int i; double *ar_sum; ar_sum = (double *) calloc(n, sizeof(double)); /* Adds corresponding elements of ar1 and ar2*/ for (i = 0; i < n; ++i) ar_sum[i] = ar1[i] + ar2[i]; return (ar_sum); }
11
11 TDBA66, VT-04, Lecture Ch7 How to call add_arrays() and add_arrays2() void add_arrays(const double ar1[],const double ar2[], double arsum[], int n); double * add_arrays2(const double ar1[],const double ar2[],int n); #include int main(void){ double list1[20], list2[20], add_lists[20], *sum_lists; int n=5, i; /* generate 10 random numbers, 5 in each array list1 and list2 */ for (i=0; i<5; i++){ list1[i]= (double) rand()/(double)RAND_MAX*10; list2[i]= rand()/(double)RAND_MAX*10; } add_arrays(list1, list2, add_lists, n); sum_lists = add_arrays2(list1, list2, n); printf(”\nLIST1 LIST2 ADD_ARRAYS ADD_ARRAYS2\n”); for (i=0; i<5; ++i) printf(”%8.4f%8.4f%12.4f%15.4f\n”, list1[i],list2[i],*(add_lists+i),sum_lists[i]); free(sum_lists); return 0; }
12
12 TDBA66, VT-04, Lecture Ch7 LIST1 LIST2 ADD_ARRAYS ADD_ARRAYS2 5.1387 1.7573 6.8960 6.8960 3.0863 5.3453 8.4317 8.4317 9.4763 1.7173 11.1936 11.1936 7.0223 2.2642 9.2865 9.2865 4.9477 1.2470 6.1946 6.1946 Result from run
13
13 TDBA66, VT-04, Lecture Ch7 Sorting A list of n integers list 1, list 2, list 3, …, list n. The elements should be ordered such that list i <= list i+1 ; i=1,2,…n-1 Algoritm BubbelSort(lista,n) /*Lightest value bubbles to top*/ bytt = false last = n repeat for i=1 to last-1 do /* push the heaviest value to the bottom */ begin if list i > list i+1 then begin exchange values bytt = true end last = last - 1 until not bytt
14
14 TDBA66, VT-04, Lecture Ch7 Code void bubble_sort(int list[], int n) { int i, last, bytt, temp; do{ last = n; /* initialization */ bytt = 0; /* logical false */ for (i=0; i <= last-1; i++) { if (list[i] > list[i+1]) { temp = list[i]; list[i] = list[i+1]; list[i+1] = temp; bytt = 1; /* logical true */ } /* end of if */ }/* end of for */ last = last - 1; }while (bytt);
15
15 TDBA66, VT-04, Lecture Ch7 Strings An array of characters ( char ) Simple initialization char course_name[]= ’’Programmeringsteknik’’; the same as char course_name[]= {’P’,’r’,’o’,’g’,’r’,’a’,’m’,’m’,’e’,’r’, ’i’,’n’,’g’,’s’,’t’,’e’,’k’,’n’,’i’,’k’,’\0’}; Note: ’\0’ is automatically stored in the first form
16
16 TDBA66, VT-04, Lecture Ch7 Strings void main(void) { char strng[10]; /* Note! indeces = 0..9 */ int i; printf("--------- example 1 ---------\n\n"); printf("Type a string : "); scanf("%s", strng); fflush(stdin); printf("-->%s<--\n\n", strng); printf("Type another string : "); gets(strng); printf("-->%s<--\n", strng); }
17
17 TDBA66, VT-04, Lecture Ch7 Run ----------- example 1 ----------- Type a string : like this -->like<-- Type a string : like this -->like this<-- What will happen if we type more than 10 charcters? In the second scanf()?
18
18 TDBA66, VT-04, Lecture Ch7 String functions include strcat(string1, string2) concatenates two strings, resulting string is returned (also in string1) strcmp(string1, string2) compares string1 to string2, value (-,0,+) is returned if string1 is lexiographically string2 strcpy(string1, string2) copies string2 to string1, a pointer to string1 is returned strlen(string) number of characters before \0 is returned
19
19 TDBA66, VT-04, Lecture Ch7 strcat #include void main(void) { char str1[] = "First string"; char str2[] = "Second!"; char str3[] = "Third"; printf("--------- example 2 ---------\n\n"); printf("-->%s<--\n",strcat(str1,str2)); printf("-->%s<--\n",str1); printf("-->%s<--\n",strcat(str3,str1)); printf("-->%s<--\n",str3); printf("------- concatenating -------\n\n"); }
20
20 TDBA66, VT-04, Lecture Ch7 Run ----------- example 2 ----------- -->First stringSecond!<-- -->ThirdFirst stringSecond!<-- --------- concatenating ---------
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.