1 / 31

מערכים (arrays)

מערכים (arrays). Problems with simple variables. Hard to give up values for high number of variables. Complex to sort a high number of variables by value. Impossible to use loops. Arrays. A block of many variables of the same type. Array can be declared for any type.

brimmer
Download Presentation

מערכים (arrays)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. מערכים(arrays) Department of Computer Science-BGU

  2. Problems with simple variables • Hard to give up values for high number of variables. • Complex to sort a high number of variables by value. • Impossible to use loops . Department of Computer Science-BGU

  3. Arrays • A block of many variables of the same type. • Array can be declared for any type. • E.g. int A[10] is an array of 10 integers. • Examples: • list of students’ marks • series of numbers entered by user • vectors • matrices Department of Computer Science-BGU

  4. Arrays in Memory • Sequence of variables of specified type • The array variable itself holds the address in memory of beginning of sequence • Example: double S[10]; • The k-th element of array A is specified by A[k-1] (0 based) Constant integer type … 0 1 2 3 4 5 6 7 8 9 … S Department of Computer Science-BGU

  5. Example - reverse #include <stdio.h> void main() { int i, A[10]; printf("please enter 10 numbers:\n"); for(i=0; i<10; i++) scanf("%d",&A[i]); printf("numbers in reversed order:\n"); for(i=9; i>=0; i--) printf("%d\n",A[i]); } Constant integer type Department of Computer Science-BGU

  6. #define • #definedefines a symbolic name. • During preprocessing phase, symbolic names are replaced by the replacement text. Department of Computer Science-BGU

  7. Reverse with #define /* get 10 integers from the user and printing them in reversed order*/ #include <stdio.h> #define NUM 10 void main() { int i; int A[NUM]; printf(“Please enter %d numbers:\n",NUM); for(i=0; i<NUM; i++) scanf("%d",&A[i]); printf("numbers in reversed order:\n"); for(i=NUM-1; i>=0; i--) printf("%d\n",A[i]); } Department of Computer Science-BGU

  8. Will it work ? • Example : #include <stdio.h> #define NUM 10 void main() { int i = 10; int A[i]; … • NO !! Need a constant integer type , no variable ! Department of Computer Science-BGU

  9. Initialization • Like in the case of regular variables, we can initialize the array during declaration. • The number of initializers cannot be more than the number of elements in the array • But it can be lessin which case, the remaining elements are initialized to 0 • The next declarations: int array1[5] = {0}; int array2[8] = {2, 4, 6, 8}; meaning: int array1[5] = {0,0,0,0,0}; int array2[] = {2, 4, 6, 8,0,0,0,0}; Department of Computer Science-BGU

  10. Initialization (cont.) • If you like, the array size can be inferred from the number of initializers. • Leaving the square brackets empty . • So these are identical declarations : int array1 [8] = {2, 4, 6, 8, 10, 12, 14, 16}; int array2 [] = {2, 4, 6, 8, 10, 12, 14, 16}; Department of Computer Science-BGU

  11. Bubble Sort #include <stdio.h>   void main() {  int array[] = {78,73,63,62,58,45,34,11};  int i,temp, n = 8 , flag;  do { flag = 0; for ( i = 0 ; i < n-1 ; i++) { if ( array[i] > array[i+1] ) { temp = array[i]; array[i] = array[i+1]; array[i+1] = temp; flag = 1; } } } while (flag);  } Department of Computer Science-BGU

  12. Insertion Sort #include <stdio.h>  int main() { int array[]= {12 ,3,34,14,98,33,9,17};  inttemp,loops = 0 ,j, i, n = 8;  for ( i = 1 ; i < n ; i++) { temp = array[i]; j = i-1; loops++; while (( j >=0) && ( temp < array[j])) { array[j+1] = array[j]; j--; loops++; } array[j+1] = temp; }  } Department of Computer Science-BGU

  13. Selection Sort void selection_sort(int list[], int n) {    int i, j, min;   for (i = 0; i < n - 1; i++)   {      min = i;      for (j = i+1; j < n; j++)    {         if (list[j] < list[min]) {                      min = j;         }      }    temp = list[i]; list[i] = list[min]); list[min] = list[i]; } } Department of Computer Science-BGU

  14. Two Dimensional Arrays • We sometimes want to keep an inherent Two-Dimensional structure of data. • Example: We can define a two-dimensional 3x3 matrix by double A[3][3]; Department of Computer Science-BGU

  15. Two Dimensional Arrays • Array of arrays: int A[2][3] = { {1, 2, 3}, {4, 5, 6} }; • Means an array of 2 integer arrays, each of length 3. • Access: j-th element of the i-th array is A[i][j] Department of Computer Science-BGU

  16. Initialization Two Dimensional Arrays • When initializing the array, it is necessary to indicate the size of the second dimension: double B[][2] = {{1,2}, {2,3}, {3,4}}; • Filling with zeros (0) is similar to one dimension array. Department of Computer Science-BGU

  17. Write a program that defines 3 matrices A,B,C of size 3x3 with float elements; initialize the first two matrices (A and B) Compute the matrix multiplication of A and B and store it in C (i.e. C = A*B) Matrix Multiplication: Exercise • Print all the matrices on the screen Department of Computer Science-BGU

  18. Solution #include <stdio.h> #define N 3 void main(){ int a[N][N],b[N][N],c[N][N]={0}; int i,j,k; for(i=0;i<N;i++) for(j=0;j<N;j++) scanf("%d%d",&a[i][j],&b[i][j]); for(i=0;i<N;i++) for(j=0;j<N;j++) for(k=0;k<N;k++) c[i][j]+= a[i][k]*b[k][j]; printf("\n\n"); for(i=0;i<N;i++){ for(j=0;j<N;j++) printf("%4d",a[i][j]); printf("\n"); { for(i=0;i<N;i++){ for(j=0;j<N;j++) printf("%4d",b[i][j]); printf("\n"); } for(i=0;i<N;i++){ for(j=0;j<N;j++) printf("%4d",c[i][j]); printf("\n"); { { Department of Computer Science-BGU

  19. חיפוש במערך - Search • מערך מאפשר חיפוש של איבר בתוך המערך . • במידה שהאיבר קיים וגם במקרה שהאיבר לא קיים במערך. • ניתן להשתמש בכמה שיטות בתלות במצב האיברים במערך: • חיפוש סדרתי במערך לא לממויין • חיפוש סדרתי במערך ממויין • חיפש בינרי במערך ממויין המכללה האקדמית להנדסה סמי שמעון

  20. חיפוש בינרי void main(){ int a[]={3,5,8,12,23,34,56,78,99}; int left = 0, right = 8, middle; int x= 36; while (left <= right) { middle = (left + right)/2; if (a[middle] > x) right = middle - 1; else if (a[middle] < x) left = middle + 1; else break; { if (left > right) printf("The number %d is not in the array\n",x); else printf("The number %d is in the array\n",x); } המכללה האקדמית להנדסה סמי שמעון

  21. Strings in C Department of Computer Science-BGU

  22. String • A sequence of characters. • Stored, as might be expected, in an array of chars. • Another way to initialize: char A[]=“blabla”; • Problem : It may be much shorter than the array where it’s stored How can we know where a string end ?! Department of Computer Science-BGU

  23. The Terminator • Strings terminate with NULL character, signed by ‘\0’ (ASCII code 0). • This is a convention used to know where the string ends. • It means that in order to hold a string of 7 chars we need an array of length at least 8 • So the previous initialization : char A[]=“blabla”; • is equivalent to char A[] = {‘b’, ‘l’, ‘a’, ‘b’, ‘l’, ‘a’, ‘\0’}; Department of Computer Science-BGU

  24. Printing strings • printf allows printing whole strings at once using %s –char str[200];/* … */ printf(“%s\n”, str); • This will print the contents of str ,cell by cell, until a ‘\0’ is encountered • this may be less than 200, but also more Department of Computer Science-BGU

  25. The fool on the null #include <stdio.h> void main() { char str[]="I'm a full string"; printf("%s\n",str); str[7]='o'; str[8]='o'; printf("%s\n",str); str[11]='\0'; printf("%s\n",str); str[11] = ‘s’; printf("%s\n", str); } Department of Computer Science-BGU

  26. Reading-in strings • There are several ways of accepting strings as input from the user. • The obvious way to go is read character by character using getchar() Department of Computer Science-BGU

  27. Reading-in strings - scanf • A simpler way is to use scanf • To read in a string to a variable str we can use: • scanf(“%s”, str); • Note there’s no ‘&’ sign!!! • Scanf reads-in letters until a space or newline is encountered • The maximum length can be stated in the parentheses – • scanf(“%10s”, str); • This will read in 10 letters, plus the ‘\0’ sign (so str should have place for 11 characters) Department of Computer Science-BGU

  28. Reading-in strings – gets() • An other simpler way is to use gets() • To read in a string to a variable str we can use: • gets( str); • Note there’s no ‘&’ sign too!!! • gets reads-in letters until a newline (pressing enter on the keyboard) is encountered. • The maximum length can be stated for the array of characters declaration minus 1. • gets change the new line for the `\0` sign as last character in the string. Department of Computer Science-BGU

  29. Writing out strings – puts() • A simpler way to write out a string is to use puts() • To write out a string that is into variable str we can use: • puts( str); • puts write out letters until a `\0` sign is encountered. • puts change the `\0` sign for new line as the last character in the string. Department of Computer Science-BGU

  30. …. ‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘\0’ …. …. …. ‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘\0’ …. …. A B Comparing strings • We cannot just compare strings’ contents by char A[7]=“Hello”; char B[7]=“Hello”; if(A==B) { … } • Because A and B are addresses of A[0] and B[0] • A==B only if A and B are the same string in memory • In order to compare the contents we must scan char by char Department of Computer Science-BGU

  31. String library • Like in the case of stdio.h and math.h, we have a special library for handling strings • We should #include <string.h> • Functions: • strlen(s) – returns the length of s • strcmp(s1, s2) – compares s1 with s2 • strcpy(s1, s2) – copies to contents of s2 to s1 • strcat(s1 , s2) – add the s1 at the end of s2 • and more… Department of Computer Science-BGU

More Related