1.1k likes | 1.12k Views
Lecture 10. Arrays. Introduction. Suppose, you need to store years of 100 cars. Will you define 100 variables?. Introduction. Algorithms usually work on large data sets Sort a set of numbers Search a specific number in a set of numbers How to read and store a set of data? To read
E N D
Lecture 10 Arrays
Introduction • Suppose, you need to store years of 100 cars. Will you define 100 variables?
Introduction • Algorithms usually work on large datasets • Sort a set ofnumbers • Search a specific number in a set ofnumbers • How to read and store a set ofdata? • Toread • Repeat the scanfstatement • Use the loopstatements • To store thedata • Save each data in a singlevariable?? • 3000 int variables! ! !!
Example • Write a program that get 10 number from user, then sort them. Finally write sorted numbers.
Array • An ordered collection of same typevariables • A vectorof • Integers, chars, floats,… • Example • An array of 8integer 0 1 2 6 7 3 4 5 • An array of 5chars
Arrays inC • Array declaration inC • <Elements’ Type><identifier>[<size>] • <Elements’ Type>: int, char, float,… • <size> • Old compilers (standard): it should beconstant • New compilers (standard): it can be variable • Elements inarray • From 0 to (size –1) • Usage <identifier>[index]
One-Dimensional Arrays • Suppose, you need to store years of 100 cars. Will you define 100 variables? int y1, y2,…, y100; • An array is an indexed data structure to represent several variables having the same data type: int y[100]; y[0] y[1] y[2] … y[k-1] y[k] y[k+1] … y[98] y[99]
One-Dimensional Arrays (cont’d) • An element of an array is accessed using the array name and an index or subscript, for example: y[2] which can be used like a variable • In C, the subscripts always start with 0 and increment by 1, so y[5] is the sixth element • The name of the array is the address of the first element y[0] y[1] y[2] … y[k-1] y[k] y[k+1] … y[98] y[99]
Example • intnum[20]; • numis array of 20 integers • num[0]is the first integer variable • num[19]is the last integer • floatfarr[100]; • farris array of 100 floats • farr[0]is the first float • farr[49]is the 50th float • farr[99]is the last float
Array Arrays and structures are “static” entities in that they remain the same size throughout program execution.
Example intnumber[10]; inti, j =3; i= 5; //-1 < i<10 number[i] =0; number[i+ j] =1; j =number[i]; j = number[i+1]; j= number[i] +1; //6th number is0 //?? //? //? //?
Array in memory • For example : int a[10]; • Defines an array of ints with subscripts ranging from 0 to 9 • There are 10*sizeof(int) bytes of memory reserved for this array. • You can use a[0]=10; x=a[2]; a[3]=a[2]; etc. • You can use scanf("%d",&a[3]);
Array Representation All elements of same type – homogenous Last element (index size - 1) First element (index 0) array[0] = 3; array[2] = 4; array[10] = 5; array[-1] = 6; No bounds checking!
Array-Bounds Checking • C, unlike many languages, does NOT check array bounds subscripts during: • Compilation (some C compilers will check literals) • Runtime (bounds are never checked) • It is the programmer’s responsibility to ensure that their programs are correctly written and debugged!
No Index Out of bound Checking: There is no index out of bound checking in C, for example the following program compiles fine but may produce unexpected output when run.
Using Constants to Define Arrays • It is useful to define arrays using constants: #define MONTHS 12 floata [MONTHS]; • What is #define advantages? • We can use const instead of #define.
Initializing Arrays • Initialization of arrays can be done by a comma separated list following its definition • For example: int array [4] = { 100, 200, 300, 400 }; • This is equivalent to: int array [4]; array[0] = 100; array[1] = 200; array[2] = 300; array[3] = 400; • You can also let the compiler figure out the array size for you: intarray[] = { 100, 200, 300, 400};
ArrayInitialization • When the size if known in compiletime • If defined as a local variable (automatic storageclass) • It is not initialized to anyvalue • If defined as a global variable (external storageclass) • All elements are initialized to0
Array Initialization(cont’d) • Remember that objects with static storage duration will initialize to 0 if no initializer is specified:
4 list[0] 3 list[1] 2 list[2] 1 list[3] 0 list[4] Assigning values to an array Give a for loop to assign the below values to list
Accessing Array Elements Array elements are accessed by using an integer index. Array index starts with 0 and goes till size of array minus 1.
Array Elements • An Example to show that array elements are stored at contiguous locations
Find Maximum • Find maximum value in data array
Find average • Find average of values in data array
Number of elements greater than average • After finding the average as shown in previous slide, use the following code
Find pair sum • Find sum of every pair in data and write into pair array } } . . . }
Reverse an array 0 1 2 3 4 5 6 3 1 9 7 2 2 7 9 1 3 6
Print sum of top-bottom pairs + + + ….
} Group avg • Suppose we have a sorted array of hundred grades. • We want to find the average of top ten, second top ten students etc. } }
#include<stdio.h> #define SIZE 20 voidmain(void){ intnumber[SIZE]; doubleaverage; int sum, large_size, small_size,i; 9 ﻭ ﺩﺮﻴﮕﺑﺍﺭﺩﺪﻋ20 ﻪﻛﻱﺍﻪﻣﺎﻧﺮﺑ ﺯﺍﺮﺘﻜﭼﻮﻛﻭ ﺮﺘﮔﺭﺰﺑﺩﺍﺪﻋﺍﺩﺍﺪﻌﺗ .ﺪﻨﻛﺏﺎﺴﺣﺍﺭﻦﻴﮕﻧﺎﻴﻣ sum = large_size = small_size = 0; for(i = 0; i < SIZE;i++){ int tmp; scanf("%d",&tmp); number[i] = tmp; sum +=number[i]; } average for(i= = (1.0 * sum) / SIZE; 0; i < SIZE;i++) if(number[i] >= average) large_size++; else small_size++; printf("average = %f\n", average); printf("Small Size = %d, LargeSize = %d\n", small_size,large_size); }
#include<stdio.h> voidmain(void){ intn; printf("Enter n: ",n); scanf("%d",&n); int number[n]; doubleaverage; int sum, large_size, small_size,i; 10 ﻪﺘﺷﺭ ﻚﻳ ﻭ ﺩﺍﺪﻋﺍ ﺩﺍﺪﻌﺗ ﻪﻛﻱﺍﻪﻣﺎﻧﺮﺑ ﻭ ﺮﺘﮔﺭﺰﺑ ﺩﺍﺪﻋﺍ ﺩﺍﺪﻌﺗ ﻭ ﺩﺮﻴﮕﺑ ﺍﺭﺩﺪﻋ .ﺪﻨﻛ ﺏﺎﺴﺣ ﺍﺭ ﻦﻴﮕﻧﺎﻴﻣ ﺯﺍﺮﺘﻜﭼﻮﻛ sum = large_size = small_size = 0; for(i = 0; i < n;i++) scanf("%d",&(number[i])); for(i= sum average for(i= 0; i < n;i++) +=number[i]; = (1.0 * sum) /n; 0; i < n;i++) if(number[i] >=average) large_size++; else small_size++; printf("average = %f\n",average); printf("Small Size = %d, LargSize = %d\n", small_size,large_size); }
Array Elements inFunctions • intnumber[20]; • number[i]is an integer variable • Array element can be used for call by valueinput • Array element can be use foroutput
Arrays in Functions(cont’d) • Array cannot be used as output type of function • int [] f(int x, int y); //compileerror • Arrays can be used in input list offunctions • Arrays are not passed by Call ByValue • Arrays are passed by Call ByReference • If we change array elements in afunction • The element is changed in the callerfunction
تابعی که یک ارایه به طول 10 را می گیرد و اعضای آن را با اعداد 0 تا 9 مقداردهی میکند.
Array Size inFunctions • If array is an input parameter of afunction • It cannot find out the size of thearray • Array size should be passed from caller function to calledfunction • Usingdefinitions
Array Size in Functions(cont’d) • If array is declared in afunction • It knows the size of thearray • It can find out the size of the array usingsizeof
ﻞﺤﻣ ﻭ ﺩﺮﻴﮕﺑ ﺍﺭ ﻪﻳﺍﺭﺁ ﻚﻳ ﻪﻛﻲﻌﺑﺎﺗ .ﺪﻧﺍﺩﺮﮔﺮﺑ ﺍﺮﻧﺁ ﻮﻀﻋ ﻦﻳﺮﺘﮔﺭﺰﺑ
Search function • Liner search • Binary search