Wk10a Arrays
Wk10a Arrays
Programming I
Narendra Pershad
Centennial College
Topics
Multi-value variable
A set of values that shares the same name
Midterm marks of all the students in COMP100
Each value is called an item or element
The elements are referenced by using a subscript
Subscripts are integer and starts at 0
Used extensively in legacy code
The size of Array can change, but it is a potentially expensive
operation
Using arrays
Declaration Declaration
int mark; int[] marks;
char vowel; char[] vowels;
//declares a string array that containing the first line of the famous nursery
rhyme
string[] poem = {"Mary", "had", "a", "little", "lamb"};
int counter = 0;
do
{
Console.WriteLine(poem[counter]);
counter++;
}while (counter < poem.Length);
Updating all the items in an array
double[] marks = {50, 67, 73, 55, 89, 68, 66, 76, 49};
int counter = 0;
while (counter < marks.Length){
marks[counter] += 3;
counter++;
}
//now we can print the updates array
counter = 0;
while (counter < marks.Length){
Console.WriteLine(marks[counter]);
counter++;
}
Summing all the items in an array
int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 37,
41, 47};
int sum = 0;
for (int counter = 0; counter < primes.Length; counter++)
{
sum += primes[counter];
}
//now we can display the sum
Console.WriteLine($"the sum is {sum}");
Built-in Methods to return arrays