C# Arrays
Week 4, Lecture 1
Instructor: Jawad Shaukat
1
Outline
Foreach Loop
Arrays
Multidimensional Arrays
Jagged Arrays
The Array Class
Foreach Loop
A foreach loop is similar to a for loop, but you do not have to worry about
the index variable
The foreach loop automatically iterates though all elements of the array.
Syntax:
Foreach (data-type someVariable in arrayName)
statements;
Data Type of variable should match the array type
Examples
int[] x=new int[5] {9,15,65,78,16}; string [ ] color = {"red", "green",
foreach (int i in x) "blue"};
{ foreach (string val in color)
Console.WriteLine(i); Console.WriteLine (val);
}
Output Output
9 Red
15 Green
65 Blue
78
16
Two-Dimensional Arrays
Two-dimensional and other multidimensional arrays follow same
guidelines as one-dimensional
Two kinds of two-dimensional arrays
Rectangular
Visualized as a table divided into rows and columns
Jagged or ragged
Referenced much like you reference a matrix
Data stored in row major format (C# – row major language)
5
Two-Dimensional Representation
6
Two-Dimensional Arrays (continued)
Declaration format
type [ , ] identifier = new type [integral value, integral value];
Two integral values are required for a two-dimensional array
Number of rows listed first
Data values placed in array must be of the same base type
Example (create a 7x3 matrix)
int [ , ] calories = new int[7, 3];
7
Two-Dimensional Arrays (continued)
calories
references
address of
calories[0,0]
8
Two-Dimensional Arrays (continued)
Length property gets total number of elements in all dimensions
Console.WriteLine(calories.Length); // Returns 21
GetLength( ) – returns the number of rows or columns
GetLength(0) returns number of rows
GetLength(1) returns number of columns
Console.WriteLine(calories.GetLength(1)); //Display 3
(columns)
Console.WriteLine(calories.GetLength(0)); //Display 7 (rows)
Console.WriteLine(calories.Rank); // returns 2
(dimensions)
9
Jagged Arrays
Rectangular arrays always have a rectangular shape, like a table; jagged arrays do not
Also called ‘arrays of arrays’
int[][] aray2d = new int[3][];
aray2d[0] = new int[5];
aray2d[1] = new int[2];
aray2d[2] = new int[4];
for (int i = 0; i < 3; i++)
{ for (int j = 0; j < aray2d[i].Length; j++)
{ aray2d[i][j] = Int32.Parse(Console.ReadLine());
} }
for (int i = 0; i < 3; i++)
{ for (int j = 0; j < aray2d[i].Length; j++)
10
{ Console.WriteLine(aray2d[i][j]); } }
Using Foreach loop
Foreach loop using 2d Array Foreach loop using Jagged Array
int[,] aray2d = new int[2, 2] { { 1,2}, {3,4 } }; int[][] Jagged_Array = new int[3][];
Jagged_Array[0] = new int[]{ 0, 1,
foreach (int a in aray2d) 2 };
{ Jagged_Array[1] = new int[] { 3, 4 };
Console.WriteLine(a); Jagged_Array[2] = new int[] { 5 };
} foreach (int[] array in Jagged_Array)
{
foreach (int value in array)
{
Console.WriteLine(value.ToString());
}
}
11
Multidimensional Arrays
Limited only by your imagination as far as the number of dimensions
Format for creating three-dimensional array
type [ , , ] identifier =
new type [integral value, integral value, integral
value];
Example (rectangular)
int [ , , ] calories = new int [4 ,7 ,3];
(4 week; 7 days; 3 meals)
Allocates
storage for
84 elements
12
= 4*7*3
Multidimensional
Arrays (continued)
Upper bounds
on the indexes
are 3, 1, 2
13
Two vs Three Dimensional Array
14
Arrays as Method Parameters
Can send arrays as arguments to methods
Heading for method that includes array as a parameter
modifiers returnType identifier (type [ ]
arrayIdentifier...)
Open and closed square brackets are required
Length or size of the array is not included
Example
void DisplayArrayContents (double [ ] anArray)
15
Pass by Reference
Arrays are reference variables
No copy is made of the contents
Array identifier memory location does not contain a value, but rather
an address for the first element
Actual call to the method sends the address
Call does not include the array size
Call does not include the square brackets
Example
DisplayArrayContents (waterDepth);
16
Example: Using Arrays as Method
Arguments
/* StaticMethods.cs
using System;
using System.Windows.Forms;
namespace StaticMethods
{
class StaticMethods
{
public const string caption = "Array Methods Illustrated";
static void Main( )
{
double [ ] waterDepth = {45, 19, 2, 16.8, 190, 0.8, 510, 6, 18 };
17
Example: Using Arrays as Method
Arguments (continued)
// StaticMethods.cs continued
double [ ] w = new Double [20];
DisplayOutput(waterDepth, "waterDepth Array\n\n" );
// Copies values from waterDepth to w
Array.Copy(waterDepth, 2, w, 0, 5);
//Sorts Array w in ascending order
Array.Sort (w);
DisplayOutput(w, "Array w Sorted\n\n" );
// Reverses the elements in Array w
Array.Reverse(w);
DisplayOutput(w, "Array w Reversed\n\n");
}
18
Example: Using Arrays as Method
Arguments (continued)
// StaticMethods.cs continued
// Displays an array in a MessageBox
public static void DisplayOutput(double [ ] anArray,
string msg)
{
foreach(double wVal in anArray)
if (wVal > 0)
msg += wVal + "\n";
MessageBox.Show(msg, caption);
}
}
}
19
Example: Using Arrays as
Method Arguments
(continued)
Output from Examples
20
Using Arrays as return type
public static int[] calculate()
{
int[] x = new int[5]{90,1,2,3,4};
return x;
}
static void Main(string[] args)
{
int[] y;
y = calculate();
Console.WriteLine(y[0]);
Console.ReadLine();
}
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.
C# Methods and Classes
Week 4, Lecture 2
Instructor: Jawad Shaukat
24
Outline
Methods
Creation and Calling
Methods Parameters
Methods Overloading
Classes and Objects
Access Modifiers.
Properties
Constructors
Methods
A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also known
as functions.
Why use methods? To reuse code: define the code once, and use it many
times.
Creating a Method
Create a method inside the Program class:
class Program
{
static void MyMethod()
{
// code to be executed
}}
My method is the name of the method.
Void means it has no return type.
Static means that the method belongs to the Program class and not an object
of the Program class.
Calling a method
static void MyMethod()
{
Console.WriteLine("I just got executed!");
}
static void Main(string[] args)
{
MyMethod();
}
Parameter Passing in Methods
Value Passing In method. Default Parameter Value
static void MyMethod(string fname)
{ static void MyMethod(string country =
Console.WriteLine(fname + " "Norway")
Refsnes"); {
} Console.WriteLine(country);
}
static void Main(string[] args)
{ static void Main(string[] args)
MyMethod("Liam"); {
MyMethod("Jenny"); MyMethod("Sweden");
MyMethod("Anja"); MyMethod("India");
} MyMethod();
MyMethod("USA");
}
Named Arguments
It is also possible to send arguments with the key: value syntax. That way, the
order of the arguments does not matter:
static void MyMethod(string child1, string child2, string child3)
{
Console.WriteLine("The youngest child is: " + child3);
}
static void Main(string[] args)
{
MyMethod(child3: "John", child1: "Liam", child2: "Liam");
}
Methods Overloading
With method overloading, multiple methods can have the same name with
different parameters. Instead of defining two methods that should do the
same thing, it is better to overload one.
static int PlusMethod(int x, int y)
{ return x + y;}
static double PlusMethod(double x, double y)
{ return x + y;}
static void Main(string[] args)
{ int myNum1 = PlusMethod(8, 5);
double myNum2 = PlusMethod(4.3, 6.26);
Console.WriteLine("Int: " + myNum1);
Console.WriteLine("Double: " + myNum2);}
Value Type vs Reference
Types in C# are divided into two categories
—
value types and reference types
C#’s simple types are all value types e.g.
int a = 7; / / variable a contains values
7
Where as reference type variable
contains address of the memory
location. e.g.
Reference Type Example
static void calculate_square(ref int x)
{ x = x * x;
Console.WriteLine("Value of X in other method:"+x); }
static void Main(string[] args)
{ int x = 10;
Console.WriteLine("Value of X in main method before passing:" + x);
calculate_square(ref x);
Console.WriteLine("Value of X in main method after passing:" + x);
Console.ReadLine();}
Classes and Objects
C# is an object-oriented programming language.
Everything in C# is associated with classes and objects, along with its
attributes and methods. For example: in real life, a car is an object. The
car has attributes, such as weight and color, and methods, such as
drive and brake.
A Class is like an object constructor, or a "blueprint" for creating
objects.
As we cant drive a Engineering Design of car, similarly we cant benefit from
class definition in our application until we build objects from it.
Objects interact with each other by passing messages. (function calls,
method invoke). Classes have properties or attributes similar in our car
example car have property of Color, Model, Make, Speeds
Class
/ / Class declaration with one GradeBook
------------
method.
using System;
------------
public class GradeBook + DisplayMessage()
{/ / display a welcome message to the GradeBook
user
public void DisplayMessage()
{
Console.WriteLine( "Welcome to the Grade
Book!" );
} / / end method DisplayMessage
} / / end class GradeBook
Declaring an object of class and
calling function
/ / Create a GradeBook object and call its DisplayMessage
method.
public class GradeBookTest
{
/ / Main method begins program execution
public static void Main( string[] args )
{
/ / create a GradeBook object and assign it to
myGradeBook GradeBook myGradeBook = new
GradeBook(); myGradeBook.DisplayMessage();
/ / call myGradeBook's DisplayMessage method
} / / end Main
} / / end class GradeBookTest
Welcome to the Grade Book!
Class with functions
GradeBook
/ / Class declaration with one method. ------------
using System;
public class GradeBook
------------
{ + DisplayMessage(string str)
/ / display a welcome message to the GradeBook user
public void DisplayMessage(string strCourseName)
{
Console.WriteLine( "Welcome to the {0}!“,
strCourseName );
} / / end method DisplayMessage
} / / end class GradeBook
Access modifires private and public
• private
– Only visible inside a class, not accessible
directly. Information hiding
• public
– Visible to the world, directly accessible.
Now how to access private member?
private string courseName;
We use public functions to modify private members
values. (Security)
e.g. GetCourseName, SetCourseName
Class with variables
/ / Class declaration with one method. GradeBook
using System; ------------
- nMarks: int
public class GradeBook ------------
+ SetMarks( Marks: int)
{ + int GetMarks()
+ DisplayMessage(msg:string)
private int nMarks; //member variable
/ / reading and writhing methods for private
variable public void SetMarks(int val){ nMarks =
val; }
public int GetMarks(){ return nMarks; }
public void DisplayMessage(string strCourseName)
{
Console.WriteLine( "Welcome to the {0}!“,
strCourseName );
} / / end method DisplayMessage
} / / end class GradeBook
Variables & Properties
using System;
GradeBook
public class GradeBook
------------
{ - courseName: string
- <<property>>CourseName: string
private string courseName; / / course name for this ------------
GradeBook + SetMarks( Marks: int)
+ int GetMarks()
/ / property to get and set the course name + DisplayMessage(msg:string)
public string CourseName
{
get
{
return courseName;
} / / end get
set
{
courseName = value;
} / / end set
} / / end property CourseName
} / / end class GradeBook
Auto implemented properties
C# provides auto implementation of
properties,
public string CourseName { get; set; }
C# compiler creates a private instance
variable, and the get and set accessors for
returning and modifying the private instance
variable.
But we cannot take the advantage of
Constructors
Constructor is a function which is automatically called when
an object is created
• Class provides a constructor that can be used to
initialize an object of a class when the object is created.
Name is similar as
using System; class
public class GradeBook
{
public GradeBook()
{} No return type
Why?
} / / end class
GradeBook
GradeBook gradeBook =new
GradeBook();
Default Constructors
using System;
public class GradeBook
{
public string CourseName { get; set; }
public GradeBook()
{
C
o
u
rs
e
N
a
m
e
Constructors with arguments
using System;
public class GradeBook
{
public string CourseName { get; set; }
public GradeBook(string courseName)
{
CourseName = coursename;
}
} / / end class GradeBook
GradeBook gradeBook =new GradeBook(“Visual
Programming”);
“Also Known as constructor overloading”
Overloaded Constructors …
public class GradeBook
{
public string CourseName { get; set; }
public GradeBook(string courseName)
{
CourseName =
coursename; GradeBook();
}
public GradeBook()
{ Console.WriteLine(“I am a
default constructor”);}
} / / end class GradeBook
GradeBook gradeBook =new
Why we need constructors?
Some times we must initialize class variables to
avoid undesirable results.
public class Counter
{
public string CurrentCount{ get; set; }
public Counter()
{
CurrentCount = 0;
}
public void Increment() { CorrentCount++;}
} / / end class Counter
Counter counter1=new Counter();