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

Intro To C# - Part 2

Arrays allow us to store and manage multiple values of the same type. We can declare arrays using the type name followed by square brackets. Arrays must be initialized before use and can contain one or more dimensions. Functions allow us to organize and reuse blocks of code. Functions have a return type, name, parameters and a body. Parameters can be passed by value, reference or as output parameters.

Uploaded by

world channel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Intro To C# - Part 2

Arrays allow us to store and manage multiple values of the same type. We can declare arrays using the type name followed by square brackets. Arrays must be initialized before use and can contain one or more dimensions. Functions allow us to organize and reuse blocks of code. Functions have a return type, name, parameters and a body. Parameters can be passed by value, reference or as output parameters.

Uploaded by

world channel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Introduction to C# - part 2

Kitaw A.
Arrays
An array stores a fixed-size sequential collection of elements of
the same type
An array is used to store a collection of data
We can think of an array as a collection of variables of the same
type stored at contiguous memory locations
Arrays
Declaring Arrays
Arrays are declared in the following way:
<baseType>[] <name>;
Here, <baseType> may be any variable type
E.g.
int[] array;
Arrays
Arrays must be initialized array
before we have access to them E.g.
Arrays can be initialized in int[] array={3,5,8,3};
two ways
Or
We can either specify the
contents of the array in a literal int[] array=new int[4];
form, or we can specify the array[0]=3;
size of the array and use the array[1]=5;
new keyword to initialize the array[2]=8;
array[3]=3;
Arrays
The foreach loop
The foreach loop repeats a group of embedded statements for each
element in an array.
foreach(<type> <identifier> in <list>) {
statement(s);
}
foreach(int x in array){
Console.WriteLine(x);
}
Arrays
Multi-dimensional Arrays
C# allows multidimensional arrays
Multidimensional arrays come in two varieties: rectangular and
jagged
Rectangular arrays represent an n-dimensional block of memory,
and jagged arrays are arrays of arrays.
Arrays
Rectangular arrays
Rectangular arrays are declared using commas to separate each dimension
The following declares a rectangular two-dimensional array, where the
dimensions are 3 by 3:
int[,] matrix = new int[2,3];
The GetLength method of an array returns the length for a given dimension
(starting at 0):
for (int i = 0; i < matrix.GetLength(0); i++)
for (int j = 0; j < matrix.GetLength(1); j++)
matrix[i,j] = i * 3 + j;
Arrays
Rectangular arrays
A rectangular array can be initialized as follows (to create an array
identical to the previous example):
int[,] matrix =
{
{0,1,2},
{3,4,5}
}
Arrays
Jagged arrays
Jagged arrays are declared using successive square brackets to
represent each dimension.
Here is an example of declaring a jagged two-dimensional array,
where the outermost dimension is 2:
int[][] matrix = new int[2][];
Arrays
Jagged arrays
The inner dimensions aren’t specified in the declaration because,
unlike a rectangular array, each inner array can be an arbitrary
length. for (int i = 0; i < matrix.GetLength(0); i++)
{
matrix[i] = new int[3];
for (int j = 0; j < matrix[i].Length; j++)
matrix[i][j] = i * 3 + j;
}
Arrays
The Array class
The Array class is the base class for all the arrays in C#
It is defined in the System namespace
The Array class provides various properties and methods to work with
arrays
Arrays
The Array class
Strings
In C#, you can use strings as array of characters
However, more common practice is to use the string keyword to
declare a string variable
The string keyword is an alias for the System.String class.
Strings
Creating a String Object
You can create string object using one of the following methods:
By assigning a string literal to a String variable
string country=”Ethiopia”;
By using a String class constructor
char[] letters={‘C’,’-’,’s’,’h’,’a’,’r’,’p’};
string lan=new String(letters);
Strings
Creating a String Object
By using the string concatenation operator (+)
string givenName=”Anders”;
string sureName=”Hejlsberg”;
string fullName=givenName+” “+sureName;
By retrieving a property or calling a method that returns a string
string givenName=”Anders”;
string givenNameUpper=givenName.ToUpper();
Strings
The String class
The String class define a number of properties and methods that
can be used to manipulate strings
The Length property gets the number of characters in the current
String object
Strings
The String class
Functions
Functions, also called methods, in C# are a means of providing
blocks of code that can be executed at any point in an application
For example, we could have a function that calculates the
maximum value in an array
We can use this function from any point in our code, and use the
same lines of code in each case
This function can be thought of as containing reusable code
Functions
E.g.
int GetMax(int[] a){
int max=a[0];
for(int i=1;i<a.Length;i++){
max=(a[i]>max)?a[i]:max;
}
return max;
}
Functions
Defining a function
<access specifier> <return type> method_name(parameter_list)
{
// method body
}
Functions
Access specifier: determines visibility of the method/function
from another class
The following access modifiers can be used in C#:
public: accessible to all other functions and objects
private: function can only be accessed with in the defining class
protected: accessible to child classes
internal: accessible for all classes with in the same project
Functions
Return type: A function may return a value. The return type is the data type
of the value the function returns. If the function is not returning any values,
then the return type is void
Method name: Method name is a unique identifier
Parameter list: Enclosed between parentheses, the parameters are used to
pass and receive data from a method. The parameter list refers to the type,
order, and number of the parameters of a method. Parameters are optional;
that is, a method may contain no parameters
Method body: This contains the set of instructions needed to complete the
required activity
Functions
E.g.
public int FindMax(ref int num1, ref int num2){
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Functions
Parameter Arrays
C# allows us to specify one (and only one) special parameter for a function
This parameter, which must be the last parameter in the function definition,
is known as a parameter array
Parameter arrays allow us to call functions using a variable amount of
parameters, and are defined using the params keyword.
Parameter arrays allow us to pass several parameters of the same type that
are placed in an array that we can use from within our function
Functions
Parameter Arrays
<returnType> <functionName>(<p1Type> <p1Name>, ... ,
params <type>[] <name>)
{
...
return <returnValue>;
}
We can call this function using code like:
<functionName>(<p1>, ... , <val1>, <val2>, ...)
Here <val1>, <val2>, and so on are values of type <type> that are used to
initialize the <name> array.
Functions
Parameter Arrays
int GetSum(params int[] a){
int sum = 0;
foreach(int n in a)
sum+=n;
return sum;
}
The following are all valid calls to the above function:
GetSum(2,3);
GetSum(1,2,3,4,5);
GetSum(1);
GetSum();
Functions
Passing Parameters to a Function
When function with parameters is called, you need to pass the parameters to
the function
There are three ways that parameters can be passed to a function:
Functions
Passing Parameters to a Function
Parameter modifiers are used to control how parameters are passed
Parameter modifier Passed by Variable must be assigned

(None) Value Going in


Ref Reference Going in
Out Reference Going out
Functions
The ref modifier
To pass by reference, C# provides the ref parameter modifier
In the following example, p and x refer to the same memory locations:
class Test{
static void Foo (ref int p){
p = p + 1;
Console.WriteLine (p);
}
static void Main(){
int x = 8;
Foo (ref x);
Console.WriteLine (x);
}
}
Functions
The out modifier
An out argument is like a ref argument, except it:
Need not be assigned before going into the function
Must be assigned before it comes out of the function
class Test{
static void Foo (out int p, out int q){
p = 1;
q = 0;
}
static void Main(){
int x ,y;
Foo (out x, out y);
Console.WriteLine (x+” “+y); //x=1 and y=0
}
}
Functions
Exercises
Swap function
A function that returns the sum of all even numbered elements of its integer
array parameter
Solutions for exercises
Swap function
using System;
class Program{
static void Main(string[] args){
int a = 7, b = 2;
Console.WriteLine("Value of a before swap: {0}", a);
Console.WriteLine("Value of b before swap: {0}", b);
Swap(ref a, ref b);
Console.WriteLine("Value of a after swap: {0}", a);
Console.WriteLine("Value of b after swap: {0}", b);
Console.ReadKey();
}
static void Swap(ref int n, ref int m){
int temp = n;
n = m;
m = temp;
}
}
Solutions for exercises
Return the sum of all even numbered elements of an array
using System;
class Program{
static void Main(string[] args){
int[] a = { 2,55,8,9,4,3,5,2};
Console.WriteLine("Sum=" + GetSum(a));
Console.ReadKey();
}
static int GetSum(int[] n){
int sum = 0;
for(int i = 0; i < n.Length; i+=2){
sum += n[i];
}
return sum;
}
}

You might also like