C#
Lecture 4
3rd Class
Prepared by Dr. Yousif A. Hamad
Contents
C# Arrays- Create an Array ........................................................................................................................ 2
Array Length ............................................................................................................................................ 3
Loop Through an Array .......................................................................................................................... 4
C# Sort Arrays ............................................................................................................................................. 5
[Link] Namespace ........................................................................................................................ 6
C# Multidimensional Arrays ...................................................................................................................... 7
Loop Through a 2D Array ...................................................................................................................... 8
C# Arrays- Create an Array
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for
each value.
To declare an array, define the variable type with square brackets:
string[] cars;
We have now declared a variable that holds an array of strings.
To insert values to it, we can use an array literal - place the values in a comma-separated list, inside
curly braces:
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
To create an array of integers, you could write:
int[] myNum = {10, 20, 30, 40};
Access the Elements of an Array
You access an array element by referring to the index number.
This statement accesses the value of the first element in cars:
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
[Link](cars[0]);
// Outputs Volvo
Note: Array indexes start with 0: [0] is the first element. [1] is the second element,
Change an Array Element
To change the value of a specific element, refer to the index number:
Example
cars[0] = "Opel";
Example
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
[Link](cars[0]);
// Now outputs Opel instead of Volvo
Array Length
To find out how many elements an array has, use the Length property:
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
[Link]([Link]);
// Outputs 4
Other Ways to Create an Array
If you are familiar with C#, you might have seen arrays created with the new keyword, and perhaps
you have seen arrays with a specified size as well. In C#, there are different ways to create an array:
// Create an array of four elements, and add values later
string[] cars = new string[4];
// Create an array of four elements and add values right away
string[] cars = new string[4] {"Volvo", "BMW", "Ford", "Mazda"};
// Create an array of four elements without specifying the size
string[] cars = new string[] {"Volvo", "BMW", "Ford", "Mazda"};
// Create an array of four elements, omitting the new keyword, and
without specifying the size
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
It is up to you which option you choose. In our tutorial, we will often use the last option, as it is faster
and easier to read.
However, you should note that if you declare an array and initialize it later, you have to use
the new keyword:
// Declare an array
string[] cars;
// Add values, using new
cars = new string[] {"Volvo", "BMW", "Ford"};
// Add values without using new (this will cause an error)
cars = {"Volvo", "BMW", "Ford"};
Loop Through an Array
You can loop through the array elements with the for loop, and use
the Length property to specify how many times the loop should run.
The following example outputs all elements in the cars array:
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < [Link]; i++)
[Link](cars[i]);
The foreach Loop
There is also a foreach loop, which is used exclusively to loop through elements
in an array:
Syntax
foreach (type variableName in arrayName)
// code block to be executed
}
The following example outputs all elements in the cars array, using
a foreach loop:
Example
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
foreach (string i in cars)
{
[Link](i);
}
Output
Volvo
BMW
Ford
Mazda
The example above can be read like this: for each string element (called i - as
in index) in cars, print out the value of i.
If you compare the for loop and foreach loop, you will see that
the foreach method is easier to write, it does not require a counter (using
the Length property), and it is more readable.
C# Sort Arrays
There are many array methods available, for example Sort(), which sorts an array
alphabetically or in an ascending order:
// Sort a string
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
[Link](cars);
foreach (string i in cars)
[Link](i);
}
// Sort an int
int[] myNumbers = {5, 1, 8, 9};
[Link](myNumbers);
foreach (int i in myNumbers)
[Link](i);
[Link] Namespace
Other useful array methods, such as Min, Max, and Sum, can be found in
the [Link] namespace:
Example
using System;
using [Link];
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int[] myNumbers = {5, 1, 8, 9};
[Link]([Link]()); // returns the largest value
[Link]([Link]()); // returns the smallest value
[Link]([Link]()); // returns the sum of elements
}
C# Multidimensional Arrays
In the previous chapter, you learned about arrays, which is also known as single
dimension arrays. These are great, and something you will use a lot while
programming in C#. However, if you want to store data as a tabular form, like a
table with rows and columns, you need to get familiar with multidimensional
arrays.
A multidimensional array is basically an array of arrays.
Arrays can have any number of dimensions. The most common are two-
dimensional arrays (2D).
Two-Dimensional Arrays
To create a 2D array, add each array within its own set of curly braces, and insert
a comma (,) inside the square brackets:
int[,] numbers = { {1, 4, 2}, {3, 6, 8} };
Good to know: The single comma [,] specifies that the array is two-
dimensional. A three-dimensional array would have two commas: int[,,].
numbers is now an array with two arrays as its elements. The first array element
contains three elements: 1, 4 and 2, while the second array element contains 3,
6 and 8. To visualize it, think of the array as a table with rows and columns:
Access Elements of a 2D Array
To access an element of a two-dimensional array, you must specify two indexes:
one for the array, and one for the element inside that array. Or better yet, with
the table visualization in mind; one for the row and one for the column (see
example below).
This statement accesses the value of the element in the first row (0) and third
column (2) of the numbers array:
Example
int[,] numbers = { {1, 4, 2}, {3, 6, 8} };
[Link](numbers[0, 2]); // Outputs 2
Remember that: Array indexes start with 0: [0] is the first element. [1] is the
second element, etc.
Change Elements of a 2D Array
You can also change the value of an element.
The following example will change the value of the element in the first row
(0) and first column (0):
Example
int[,] numbers = { {1, 4, 2}, {3, 6, 8} };
numbers[0, 0] = 5; // Change value to 5
[Link](numbers[0, 0]); // Outputs 5 instead of 1
Loop Through a 2D Array
You can easily loop through the elements of a two-dimensional array with
a foreach loop:
Example
int[,] numbers = { {1, 4, 2}, {3, 6, 8} };
foreach (int i in numbers)
[Link](i);
}
You can also use a for loop. For multidimensional arrays, you need one loop for
each of the array's dimensions.
Also note that we have to use GetLength() instead of Length to specify how many
times the loop should run:
Example
int[,] numbers = { {1, 4, 2}, {3, 6, 8} };
for (int i = 0; i < [Link](0); i++)
{
for (int j = 0; j < [Link](1); j++)
{
[Link](numbers[i, j]);
}
}
Example
using System;
using [Link];
namespace CarDemo
{
class Program
{
static void Main(string[] args)
{
int[] std = { 55, 60, 77, 82, 47, 60 };
foreach (int i in std)
[Link](i + " ");
[Link]("\n============================");
[Link]("\n the sum of 2nd and 4th ele is :" + (std[1] +
std[3]));
std[4] = 50;
[Link]("the Max of array is "+[Link]());
float avg = [Link]() / 6;
[Link]("the Avg of 4th ele is : " + avg);
[Link]("the Sum of array is " + [Link]());
[Link]("the Min of array is " + [Link]());
[Link]("the value of 4th ele is : "+ std[3]);
//[Link]("the value of 4th ele is : " +
std[7]);
[Link](std);
[Link]("============================");
foreach (int i in std)
[Link](i + " ");
[Link](std);
[Link]("\n============================");
foreach (int i in std)
[Link](i + " ");
}
}
}
Example
using System;
using [Link];
namespace CarDemo
{
class Program
{
static void Main(string[] args)
{
// array declarations
int[] st = { 2, 4, 6, 12, 15, 22, 40 };
//for (int i = 0; i < 7; i++)
// [Link](st[i] + " ");
//******************************** print the array elements
foreach(int i in st)
[Link](i+ " ");
[Link]("\n****************************");
//******************************
[Link]("\n the sum of 3rd and 5th ele is: "+(st[2]+st[4]));
st[5] = 55;
[Link]("the last ele is : " + st[6]);
[Link]("the sum of all ele : " + [Link]());
[Link]("the Max ele : " + [Link]());
[Link]("the Min ele : " + [Link]());
[Link]("the length of array is : " + [Link]);
[Link](st);
[Link]();
[Link]("\n****************************");
foreach (int i in st)
[Link](i + " ");
[Link]("\n****************************");
[Link](st);
foreach (int i in st)
[Link](i + " ");
}
}
}
Q/ Write a C# program of the following requirements (2D Array of 3 x
4) type int
1- Print the sum of (2,2), (0,3)
2- Print the average of array
3- Print the sum of array
4- Change the elements of 1st row 2nd column
5- Print the length of array
6- Print the last row of array
7- Print the 2nd column of array
8- Print the sorted array
9- Print the reverse array
10- Print the sum of elements ((2,3), (1,0),( 2,2))
Q/ Write the output of the following C# Program
using System;
using [Link];
namespace CarDemo
{
class Program
{
static void Main(string[] args)
{
int[,] st = { { 2, 3 ,7,8}, { 4, 9,12,22 }, { 5, 11, 40, 55 } };
int s = 0;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
[Link](st[i, j]+" ");
[Link]();
}
[Link]("************************");
for (int i = 0; i < 3; i++)
for (int j = 0; j < 4; j++)
s += st[i, j];
//foreach (int i in st)
// s += i;
[Link]("The Sum of array is : " + s);
[Link]("The average is : " + (s / 12));
st[1, 2] = 50;
[Link]("The length of the array is : "+[Link]);
[Link]("\n************************");
for (int j = 0; j < 4; j++)
[Link](st[2, j] + " ");
[Link]("\n************************");
for (int i = 0; i < 3; i++)
[Link](st[i, 3] + " ");
[Link]("\n************************");
} } }
Example // 2D array of 3 x 4 type int
using System;
namespace Demo
{
class Program
{
static void Main(string[] args)
{// 2D array of 3 x 4 type int
int[,] ary = { {1,2,3,9 }, {2,4,6,10 }, {3,5,7,12 } };
int s = ary[2, 2] + ary[0, 3];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
[Link](ary[i, j] + " ");
[Link]();
}
[Link]("\n ---------------");
[Link]("The sum of ary[2, 2] + ary[0, 3]= " +
s);
[Link]("\n ---------------");
int s1 = 0;
foreach (int i in ary)
s1 += i;
[Link]("The sum of ary= " + s1);
[Link]("\n ---------------");
[Link]("The AVG of ary= " + (s1/12));
[Link]("\n ---------------");
ary[0, 1] = 40;
[Link]("The length of ary= " +[Link]);
[Link]("\n ---------------");
for (int j = 0; j < 4; j++)
[Link](ary[1,j]+ " ");
[Link]("\n ---------------");
for (int j = 0; j < 3; j++)
[Link](ary[j, 3] );
}
}
}
Example using Array of string with 4 elements
using System;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
string [] cars = { "Volvo", "BMW", "Ford", "Mazda" };
//Print the elements of an array
for (int i = 0; i < [Link]; i++)
[Link](cars[i] + " , ");
[Link]("\n-------------------------------");
//Print the last element of array
[Link]("The last element is : "+cars[3]);
[Link]("\n-------------------------------");
//Change the 2nd elements to Opel
cars[1] = "Opel";
//Print the elements of an array using Foreach
foreach (string i in cars)
[Link](i + " , ");
[Link]("\n-------------------------------");
// Sort and print the array
[Link](cars);
for (int i = 0; i < [Link]; i++)
[Link](cars[i] + " , ");
[Link]("\n-------------------------------");
//Print the length of the array
[Link]("The Array length is : " + [Link]);
[Link]("\n-------------------------------");
//Print the Reverse of the array
[Link](cars);
for (int i = 0; i < [Link]; i++)
[Link](cars[i] + " , ");
}
}
}