SlideShare a Scribd company logo
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 before
we have access to them
Arrays can be initialized in two
ways
We can either specify the
contents of the array in a literal
form, or we can specify the size
of the array and use the new
keyword to initialize the array
E.g.
int[] array={3,5,8,3};
Or
int[] array=new int[4];
array[0]=3;
array[1]=5;
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;
}
}

More Related Content

Similar to Intro to C# - part 2.pptx emerging technology

C++ lecture 04
C++ lecture 04C++ lecture 04
C++ lecture 04
HNDE Labuduwa Galle
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
aroraopticals15
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
Prerna Sharma
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
Mohammed Khan
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
TaseerRao
 
07 Arrays
07 Arrays07 Arrays
07 Arrays
maznabili
 
C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework Help
C++ Homework Help
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
valerie5142000
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
ansariparveen06
 
array Details
array Detailsarray Details
array Details
shivas379526
 
2D Array
2D Array 2D Array
2D Array
Ehatsham Riaz
 
Array BPK 2
Array BPK 2Array BPK 2
Array BPK 2
Riki Afriansyah
 
Module 7 : Arrays
Module 7 : ArraysModule 7 : Arrays
Module 7 : Arrays
Prem Kumar Badri
 
Array assignment
Array assignmentArray assignment
Array assignment
Ahmad Kamal
 
Chap1 array
Chap1 arrayChap1 array
Chap1 array
raksharao
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson Arrays
Maulen Bale
 
arrays in c# including Classes handling arrays
arrays in c#  including Classes handling arraysarrays in c#  including Classes handling arrays
arrays in c# including Classes handling arrays
JayanthiM19
 

Similar to Intro to C# - part 2.pptx emerging technology (20)

C++ lecture 04
C++ lecture 04C++ lecture 04
C++ lecture 04
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
 
07 Arrays
07 Arrays07 Arrays
07 Arrays
 
C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework Help
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
 
array Details
array Detailsarray Details
array Details
 
2D Array
2D Array 2D Array
2D Array
 
Array BPK 2
Array BPK 2Array BPK 2
Array BPK 2
 
Module 7 : Arrays
Module 7 : ArraysModule 7 : Arrays
Module 7 : Arrays
 
Array assignment
Array assignmentArray assignment
Array assignment
 
Arrays, continued
Arrays, continuedArrays, continued
Arrays, continued
 
Chap1 array
Chap1 arrayChap1 array
Chap1 array
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson Arrays
 
arrays in c# including Classes handling arrays
arrays in c#  including Classes handling arraysarrays in c#  including Classes handling arrays
arrays in c# including Classes handling arrays
 

Recently uploaded

A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 

Recently uploaded (20)

A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 

Intro to C# - part 2.pptx emerging technology

  • 1. Introduction to C# - part 2 Kitaw A.
  • 2. 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
  • 3. Arrays Declaring Arrays Arrays are declared in the following way: <baseType>[] <name>; Here, <baseType> may be any variable type E.g. int[] array;
  • 4. Arrays Arrays must be initialized before we have access to them Arrays can be initialized in two ways We can either specify the contents of the array in a literal form, or we can specify the size of the array and use the new keyword to initialize the array E.g. int[] array={3,5,8,3}; Or int[] array=new int[4]; array[0]=3; array[1]=5; array[2]=8; array[3]=3;
  • 5. 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); }
  • 6. 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.
  • 7. 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;
  • 8. 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} }
  • 9. 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][];
  • 10. 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; }
  • 11. 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
  • 13. 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.
  • 14. 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);
  • 15. 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();
  • 16. 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
  • 18. 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
  • 19. 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; }
  • 20. Functions Defining a function <access specifier> <return type> method_name(parameter_list) { // method body }
  • 21. 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
  • 22. 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
  • 23. 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; }
  • 24. 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
  • 25. 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.
  • 26. 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();
  • 27. 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:
  • 28. 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
  • 29. 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); } }
  • 30. 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 } }
  • 31. Functions Exercises Swap function A function that returns the sum of all even numbered elements of its integer array parameter
  • 32. 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; } }
  • 33. 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; } }