Storing List of Data
Suppose we want to store the grade of each student in a class
Need a varitable for each?
int bod, mary, tom, ...;
Easier to have a variable that stores the grandes for all students
An array is a contiguous piece of memory that can contain multiple values
The values within the contiguous chunk can be addressed individually
Address in memory | 0x7f340 | 0x7f344 | 0x7f348 | 0x7f34c | 0x7f350 | 0x7f354 | 0x7f358 | 0x7f35c | 0x7f360 |
Grades | 74 | 59 | 95 | 85 | 71 | 45 | 99 | 82 | 76 |
Physycal address | 0x7f340 | 0x7f344 | 0x7f348 | 0x7f34c | 0x7f350 | 0x7f354 | 0x7f358 | 0x7f35c | 0x7f360 |
Grades | 74 | 59 | 95 | 85 | 71 | 45 | 99 | 82 | 76 |
index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
Use an index to access individual elements of the array: grades[0] is 74, grades[1] is 59, grades[2] is 95, and so on
Syntax for declaring array variable:
type array_name[capacity]
Type can be any type (int, float, char, ...)
array_name is an identifier
Capacity is the number of values it can store (indexing starts at 0)
int x[3]; //an array of 3 integers double y[7]; //an array of doubles
Assigment
x[0] = 6; //Assign 6 to element x[0] y[2] = 3.1; //Assign 3.1 to element y[2]
Access
m = x[2]; p = y[0];
Input/Output
The elements are handled as their types, e.g
scanf("%d %ld", &x[2], &y[3]); printf("%d %lf\n", x[0], y[2]); //output 6 and 3.1
void main(){ double x[5]; x[0] = 1; x[1] = 2; x[2] = x[0] + x[1]; x[3] = x[2] / 2; x[4] = x[3] * x[2]; }
"for" loops are ideal for processing elements in the array
int i; double values[] = {3.14, 1.0, 2.61, 5.3}; double sumValues = 0.0; for( i = 0; i < 4; i++){ sumValues += values[i]; } printf("%lf\n", sumValues);
Systax: int a[] = {2, 4, 7, 9}
Behavior: initialize elements starting with leftmost i.e: element 0. Remaining elements are initialized to zero
X | 2 | 4 | 7 | 9 |
0 | 1 | 2 | 3 |
Initialize all to 0: int x[4] = { 0 };
Good programming practice:
use #define for constants in you program
For example:
#define MAX_LIMIT 25 int grades[MAX_LIMIT]; for(int i = 0; i < MAX_LIMIT; i++){ }
If size need to be changed, only the capacity "MAX_LIMIT" needs to be changed
double sumValues(double x[], int numElements){ double result = 0; for(int i = 0; i < numElements; i++){ result += result + x[i]; } return result; } void main(){ double values[] = { 3.14, 1.0, 2.61, 5.3 }; printf("Sum = %lf\n", sumValues(values, 4)); }
"[]" flags the parameters as an array
Always passed by reference
Array size is passed separately (as numElements)
Program Behavior
void randomArray(double elements[], int numElements); void printArray(double elements[], int numElements); void sortArray(double elements[], int numElements); void swap(double a, double b);