200 likes | 402 Views
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
E N D
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]; TDBA66, VT-04, Lecture Ch7
example /* * Example of a simple list of integers */ #include <stdio.h> 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; } TDBA66, VT-04, Lecture Ch7
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 0int 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 */ Initialization 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]); 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 <stdio.h> #include <math.h> #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]); 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); } 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 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]; } 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 <stdlib.h> 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 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 <stdlib.h> 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); } 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 <math.h> #include <stdlib.h> 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; } TDBA66, VT-04, Lecture Ch7
Result from run 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 TDBA66, VT-04, Lecture Ch7
Sorting A list of n integers list1, list2, list3, …, listn . The elements should be ordered such that listi <= listi+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 > listi+1 then begin exchange values bytt = true end end last = last - 1 until not bytt 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); TDBA66, VT-04, Lecture Ch7
Strings • An array of characters (char) • Simple initializationchar course_name[]= ’’Programmeringsteknik’’; the same aschar 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 TDBA66, VT-04, Lecture Ch7
Strings voidmain(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); } 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()? TDBA66, VT-04, Lecture Ch7
include <string.h> 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) copiesstring2 to string1 , a pointer to string1 is returned strlen(string) number of characters before \0 is returned String functions TDBA66, VT-04, Lecture Ch7
strcat #include <string.h> 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"); } TDBA66, VT-04, Lecture Ch7
Run ----------- example 2 ----------- -->First stringSecond!<-- -->First stringSecond!<-- -->ThirdFirst stringSecond!<-- -->ThirdFirst stringSecond!<-- --------- concatenating --------- TDBA66, VT-04, Lecture Ch7