0% found this document useful (0 votes)
2 views

C#. Lecture No. 4

This document is a lecture on C# arrays, covering topics such as creating arrays, accessing and modifying elements, and looping through arrays. It also discusses sorting arrays, using the System.Linq namespace for additional array methods, and introduces multidimensional arrays with examples. The lecture includes practical coding examples and exercises to reinforce the concepts presented.

Uploaded by

yousif
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

C#. Lecture No. 4

This document is a lecture on C# arrays, covering topics such as creating arrays, accessing and modifying elements, and looping through arrays. It also discusses sorting arrays, using the System.Linq namespace for additional array methods, and introduces multidimensional arrays with examples. The lecture includes practical coding examples and exercises to reinforce the concepts presented.

Uploaded by

yousif
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

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
System.Linq 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"};

Console.WriteLine(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";

Console.WriteLine(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"};

Console.WriteLine(cars.Length);

// 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 < cars.Length; i++)

Console.WriteLine(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)
{
Console.WriteLine(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"};

Array.Sort(cars);

foreach (string i in cars)

Console.WriteLine(i);
}

// Sort an int

int[] myNumbers = {5, 1, 8, 9};

Array.Sort(myNumbers);

foreach (int i in myNumbers)

Console.WriteLine(i);

System.Linq Namespace
Other useful array methods, such as Min, Max, and Sum, can be found in
the System.Linq namespace:

Example
using System;

using System.Linq;

namespace MyApplication
{
class Program
{
static void Main(string[] args)
{

int[] myNumbers = {5, 1, 8, 9};

Console.WriteLine(myNumbers.Max()); // returns the largest value

Console.WriteLine(myNumbers.Min()); // returns the smallest value

Console.WriteLine(myNumbers.Sum()); // 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} };

Console.WriteLine(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

Console.WriteLine(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)

Console.WriteLine(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 < numbers.GetLength(0); i++)


{
for (int j = 0; j < numbers.GetLength(1); j++)
{
Console.WriteLine(numbers[i, j]);
}
}

Example

using System;
using System.Linq;

namespace CarDemo
{
class Program
{
static void Main(string[] args)
{
int[] std = { 55, 60, 77, 82, 47, 60 };

foreach (int i in std)


Console.Write(i + " ");
Console.WriteLine("\n============================");
Console.WriteLine("\n the sum of 2nd and 4th ele is :" + (std[1] +
std[3]));
std[4] = 50;
Console.WriteLine("the Max of array is "+std.Max());
float avg = std.Sum() / 6;
Console.WriteLine("the Avg of 4th ele is : " + avg);
Console.WriteLine("the Sum of array is " + std.Sum());
Console.WriteLine("the Min of array is " + std.Min());
Console.WriteLine("the value of 4th ele is : "+ std[3]);
//Console.WriteLine("the value of 4th ele is : " +
std[7]);
Array.Sort(std);
Console.WriteLine("============================");
foreach (int i in std)
Console.Write(i + " ");

Array.Reverse(std);
Console.WriteLine("\n============================");
foreach (int i in std)
Console.Write(i + " ");

}
}
}

Example
using System;
using System.Linq;
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++)


// Console.Write(st[i] + " ");
//******************************** print the array elements
foreach(int i in st)
Console.Write(i+ " ");
Console.WriteLine("\n****************************");
//******************************
Console.WriteLine("\n the sum of 3rd and 5th ele is: "+(st[2]+st[4]));
st[5] = 55;
Console.WriteLine("the last ele is : " + st[6]);
Console.WriteLine("the sum of all ele : " + st.Sum());
Console.WriteLine("the Max ele : " + st.Max());
Console.WriteLine("the Min ele : " + st.Min());
Console.WriteLine("the length of array is : " + st.Length);
Array.Sort(st);
Console.WriteLine();
Console.WriteLine("\n****************************");
foreach (int i in st)
Console.Write(i + " ");
Console.WriteLine("\n****************************");

Array.Reverse(st);

foreach (int i in st)


Console.Write(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 System.Linq;

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++)
Console.Write(st[i, j]+" ");
Console.WriteLine();
}
Console.WriteLine("************************");

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;

Console.WriteLine("The Sum of array is : " + s);


Console.WriteLine("The average is : " + (s / 12));
st[1, 2] = 50;
Console.WriteLine("The length of the array is : "+st.Length);
Console.WriteLine("\n************************");

for (int j = 0; j < 4; j++)


Console.Write(st[2, j] + " ");

Console.WriteLine("\n************************");
for (int i = 0; i < 3; i++)

Console.WriteLine(st[i, 3] + " ");

Console.WriteLine("\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++)
Console.Write(ary[i, j] + " ");
Console.WriteLine();
}

Console.WriteLine("\n ---------------");
Console.WriteLine("The sum of ary[2, 2] + ary[0, 3]= " +
s);
Console.WriteLine("\n ---------------");
int s1 = 0;
foreach (int i in ary)
s1 += i;
Console.WriteLine("The sum of ary= " + s1);
Console.WriteLine("\n ---------------");
Console.WriteLine("The AVG of ary= " + (s1/12));
Console.WriteLine("\n ---------------");
ary[0, 1] = 40;
Console.WriteLine("The length of ary= " +ary.Length);
Console.WriteLine("\n ---------------");
for (int j = 0; j < 4; j++)
Console.Write(ary[1,j]+ " ");
Console.WriteLine("\n ---------------");
for (int j = 0; j < 3; j++)
Console.WriteLine(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 < cars.Length; i++)
Console.Write(cars[i] + " , ");
Console.WriteLine("\n-------------------------------");
//Print the last element of array
Console.Write("The last element is : "+cars[3]);
Console.WriteLine("\n-------------------------------");
//Change the 2nd elements to Opel
cars[1] = "Opel";
//Print the elements of an array using Foreach
foreach (string i in cars)
Console.Write(i + " , ");
Console.WriteLine("\n-------------------------------");
// Sort and print the array
Array.Sort(cars);
for (int i = 0; i < cars.Length; i++)
Console.Write(cars[i] + " , ");
Console.WriteLine("\n-------------------------------");
//Print the length of the array
Console.Write("The Array length is : " + cars.Length);
Console.WriteLine("\n-------------------------------");
//Print the Reverse of the array
Array.Reverse(cars);
for (int i = 0; i < cars.Length; i++)
Console.Write(cars[i] + " , ");
}
}
}

You might also like