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 (20)

PPTX
C++ lecture 04
HNDE Labuduwa Galle
 
PDF
Homework Assignment – Array Technical DocumentWrite a technical .pdf
aroraopticals15
 
PPTX
Programming in C sesion 2
Prerna Sharma
 
PPTX
Lecture 9
Mohammed Khan
 
DOCX
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
pranauvsps
 
PPTX
Arrays in programming
TaseerRao
 
PPT
07 Arrays
maznabili
 
PPTX
C++ Programming Homework Help
C++ Homework Help
 
PPT
Arrays in c programing. practicals and .ppt
Carlos701746
 
PPT
ch06.ppt
ansariparveen06
 
PPT
ch06.ppt
chandrasekar529044
 
PPT
ch06.ppt
AqeelAbbas94
 
PPT
array Details
shivas379526
 
PPTX
2D Array
Ehatsham Riaz
 
PDF
DOC-20250225-WA0016..pptx_20250225_232439_0000.pdf
HivaShah
 
PPTX
Array BPK 2
Riki Afriansyah
 
PPTX
Module 7 : Arrays
Prem Kumar Badri
 
DOCX
Array assignment
Ahmad Kamal
 
PDF
Arrays, continued
Michael Gordon
 
PPTX
Arrays in Java with example and types of array.pptx
ashwinibhosale27
 
C++ lecture 04
HNDE Labuduwa Galle
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
aroraopticals15
 
Programming in C sesion 2
Prerna Sharma
 
Lecture 9
Mohammed Khan
 
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
pranauvsps
 
Arrays in programming
TaseerRao
 
07 Arrays
maznabili
 
C++ Programming Homework Help
C++ Homework Help
 
Arrays in c programing. practicals and .ppt
Carlos701746
 
ch06.ppt
ansariparveen06
 
ch06.ppt
AqeelAbbas94
 
array Details
shivas379526
 
2D Array
Ehatsham Riaz
 
DOC-20250225-WA0016..pptx_20250225_232439_0000.pdf
HivaShah
 
Array BPK 2
Riki Afriansyah
 
Module 7 : Arrays
Prem Kumar Badri
 
Array assignment
Ahmad Kamal
 
Arrays, continued
Michael Gordon
 
Arrays in Java with example and types of array.pptx
ashwinibhosale27
 

Recently uploaded (20)

PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PDF
Geographical Diversity of India 100 Mcq.pdf/ 7th class new ncert /Social/Samy...
Sandeep Swamy
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PPTX
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPTX
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PPTX
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
PPTX
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PPTX
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PPTX
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
Geographical Diversity of India 100 Mcq.pdf/ 7th class new ncert /Social/Samy...
Sandeep Swamy
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 

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; } }