The basic also includes array. It is just an extension of our primitive data types. So basically, arrays are just collections of things. It can be a collection of integers, characters, etc.
There are some programming languages that aren't strict when it comes to data types (e.g. PHP). In these languages, array can be a collection of values with different data types (strings and integers, for example). But in C (and most of other PLs including Java), you can only store values of the same data type in one array.
In declaring an array, we need to first determine it's size. Let's say I need an array to store my grade in five of my different courses.
So we have,
int grades[5]; // {0, 0, 0, 0, 0}
Declaring an empty array initializes all of its values to 0. So now, we have an integer array containing five 0's. Values are access through their indices. Index starts at 0. That's why the meme programmers don't start counting by 1 but 0.
So let's say, my I got an 85 in my first course and I want to store it in my array.
grades[0] = 85;
Now, the first element (indexed 0 of array grades) is now equal to 85 while the rest of the elements remains 0.
Array Declaration
There are several ways of declaring/initializing an array in C.
This declares an array with 5 elements all initialized to 0.
int grades[5]; // {0, 0, 0, 0, 0}
Explicit initialization of all array elements
int grades[5] = {85, 95, 80, 100, 90};
Initializes particular array elements
// initializes the second and fifth element to 90 and 100, rescpectively int grades[5] = {[1] = 95, [4] = 90};
In this case all elements that are not explicitly defined are initialized to 0, making our array {0, 95, 0, 0, 90}.
// initializes the first two elements of the array, all succeeding ones are initialized to 0 int grades[5] = {85, 95};
Previous Topic Course Outline Next Topic
No comments:
Post a Comment