LECTURE 11: Arrays (Read Sections *.1-8.3, 8.4)
So
far, we covered simple data types (int, double, char) that
Often,
we would like to group similar data items together. For example, we want
to store and process exam scores of all students in the class. Arrays
address this requirement!
Array is a collection of two or more adjacent memory
locations, called array elements
Array declaration and use
double x[2]; // reserves two
memory locations to store two double values
x[0] = 5.0; // assigns value
5.0 to the first element of the array
x[1] = 3.0;
printf(“%f”,x[0]); // prints
out the value of the first element
x[1] = x[0] + x[1]; //
updates the value of the second array element to 8.0
Array initialization
int sum = 0; //
initialization of integer variable
double x[2] = {5.0, 3.0}; //
initialize values of the two array elements
Array subscripts
double x[100];
x[0] = 5.0;
x[1] = 3.0;
for (i=3; i<=100; i=i+1)
x[i] = x[i-1] + x[i-2];
Question:
what will be the value of element x[99] after the for loop is executed?
Example: Enter exam scores and find
maximum and average scores
-
DONE IN CLASS –
-
YOU CAN ALSO CHECK 8.6 IN THE TEXTBOOK –
Miltidimensional Arrays
char tictactoe[3][3]; //
declares two-dimensional array with 3 rows and 3 columns
tictactoe[0][2] = ‘x’; //
assigns value ‘x’ to the element in the
// first
row and third column of tictactoe