You are on page 1of 39

ITP261

Enterprise Application Development


LECTURE 02
C# PROGRAMMING (PART 2)

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 1


Learning outcome
Array Declaration & Initialisation
ArrayList and List collection
Accessing data in arrays
Use loops to traverse the elements of an array
Implement Object Orientated Programming in C#

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 2


Array
An array is a collection of elements of the same data type.
The syntax for an array declaration:
◦ data type [ ] arrayName;

To create elements in an array, we will assume the following syntax to


declare and initialize an array:

Example:
int [ ] age={18,17,18,19,17};

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 3


Array Declaration
General Form
Datatype[ ] ArrayName = new DataType[NumberofElements];
Datatype[ ] ArrayName = new DataType[] {InitialValueList};
Datatype[ ] ArrayName = {InitialValueList};

string[ ] name = new string[25];


decimal[ ] balance = new decimal[10];
string[ ] product = new string[99];
int[ ] age = new int[] {1,5,12,18,20};
string[ ] name = {“Sean”, “Sam”, “Sally”, “Sara”};

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 4


The Array Index or Subscript
Subscripts may be constants, variables, or numeric expressions
Subscripts must be integers
Specify the number of elements in the array in the array’s declaration
statement
Array subscripts start from zero
A subscript must reference a valid element of the array
Exception will be thrown if a subscript is out of range

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 5


The Array Index or Subscript
int [ ] marks = { 20, 33, 15, 29 };
marks 20 33 15 29
0 1 2 3 Array Index or Subscript:
•Always start with zero
•Last value is Array Size - 1

Store data to Array


Use the Index or Subscript to STORE data to individual element .

marks[ 2 ] = 99; will store 99 into the 3rd element or box.

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 6


Getting data from Arrays
Specify the element of the array

OUTPUT
public void PrintArray( )
{ 1st number:1

int [] numbers= {1,2,3}; 2nd number:2

Response.Write("1st number:"); 3rd number:3


Response.Write (numbers[0]+"<br/>");
Response.Write("2nd number:");
Response.Write(numbers[1]+"<br/>"); What will happen if we try to print numbers[3] ?

Response.Write("3rd number:");
Response.Write (numbers[2]+"<br/>");
System generates an “Index out of range exception”

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 7


ArrayList
ArrayList represents an ordered collection of an object that can be indexed
individually.
Array lists are not strongly type collection. It will store values of different
datatypes or same datatype.
Array list size will increase or decrease dynamically it can take any size of values
from any data type.
Array lists will be accessible with “System.Collections” namespace
Property Description
Count Gets the number of elements actually contained in the ArrayList
Item Gets or sets the element at the specified index.

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 8


Common method of ArrayList
Name Description

Add() Adds an object to the end of the ArrayList.

Insert(Int32, Object)) Inserts an element into the ArrayList at the specified index.

Remove(Object) Removes the element at the specified index of the ArrayList.

Sort() Sorts the elements in the entire ArrayList.

Clear() Removes all elements from the ArrayList.

More method and property from


https://msdn.microsoft.com/en-us/library/system.collections.arraylist(v=vs.110).aspx

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 9


Code sample of using ArrayList
ArrayList al = new ArrayList();
// Adding some numbers in ArrayList al
al.Add(45); 45
al.Add(78); 78
al.Add(33); 33
al.Add(56); 56
// Sort the ArrayList
al.Sort(); al after sort
33
45
56
78

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 10


ArrayList is not strongly type
ArrayList al = new ArrayList();
// Adding items of various data type in ArrayList
al.Add(45); al
al.Add(“Susan”);
45
al.Add(33.7);
Susan
33.7

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 11


List collection class
List is a generic collection class present in “System.Collections.Generic” namespace.
A List class can be used to create a collection of any type, such a list of integer, string or object
List can grow in size automatically. You do not worry of exception of index out of range

Example
List<int> marks = new List<int>();
In the collection “marks” you can only add
marks.Add(60);
integers and no other type.
marks.Add(80);

List<string> names = new List<string>(); In the collection “name” you can only add string .
name.Add("Susan");
In the collection “student” you can only add
List<Student> students = new List<Student>(); Student object .

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 12


Common method of List
Name Description

Add() Adds an object to the end of the List.

Insert(Int32, T)) Inserts an element into the List<T> at the specified index.

Remove(T) Removes the first occurrence of a specific object from theList<T>.

Sort() Sorts the elements in the entire List.

Clear() Removes all elements from the List.

More method and property from https://msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 13


Looping and Iteration
Looping is the process of repeating a series of instructions

The group of repeated instructions is the loop

An iteration is a single execution of the statement(s) in the loop

A while or do/while loop terminates based on a condition

Use while or do/while loops when you don’t know how many iterations are
needed

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 14


The while and do/while Loops
Pretest Loop
while (Condition)
{
//Statements in loop
}

Posttest Loop
do
{
//Statements in loop
} while (Condition);

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 15


The while Loops
Pretest loop test for completion of looping
If terminating condition is true, statements in loop may never execute

Example:
intTotal = 0;
while (intTotal != 0)
{
//Statements in loop
}

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 16


The while and do/while Loops
Posttest loop test for completion at bottom of loop
Statements inside the loop will always execute at least once

Example:
intTotal = 0;
do
{
//Statements in loop
} while (intTotal != 0);

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 17


for Loops
Use a for loop to repeat statements in a loop a specific number of times

for loop has four parts


◦ Initialization – start value of loop counter.
◦ The condition - condition to test whether to loop.
◦ Increment - value to increase loop counter.
◦ The action to occur when condition is met

Use a semicolon to separate the parts of the for statement

Use a loop index to count iterations

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 18


for Loops
Examples
for (int Index = 2; Index <= 100; Index += 2)
{
sumEven = sumEven + Index
}

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 19


for Loops
You can decrement the counter and test for the lower bound in the condition

Statements in body of loop will not execute if the final value is reached before
entry into the loop

Some code can get into an endless loop that is impossible to exit on its own
◦ Click on form’s close box
◦ Use Visual Studio IDE menu or toolbar to stop program
◦ Use the C# break statement

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 20


for Loops
The for Loop structure can
◦ READ data from the array, and
◦ STORE data into an array.

(whereas the foreach loop can only read data from the array)

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 21


foreach Statement
foreach is a looping construct to read data from the array. It cannot change the
value in the array
General Form
foreach (DataType ElementName in ArrayName)
{
//Statement(s) in loop
}
C# automatically references each array element, assigns its value to
ElementName, and makes one pass through the loop

The foreach loop will execute if the array has at least one element

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 22


foreach Examples
foreach (string day in dayOfWeek)
{
//Write one element of the array
Response.Write (day + “<br/”);
}

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 23


Comparing for and foreach
Limitations
◦ The foreach loop can only be used to READ data from the array.
◦ It cannot be used to STORE data into the array.
Advantage of foreach:
◦ Do not need to manipulate array subscripts
◦ Do not need to know no. of elements in array

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 24


Comparing for and while loops
Consider the similarities between the 2 sets of codes below:

for Loop: while Loop:


int count; int count = 0;
for(count=0; count < 5; count++) while( count < 5 )
{ {
<loop body>…………………. <loop body>……………
} count = count + 1; //count++
}

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 25


Multidimensional Arrays
Two-dimensional arrays have rows and columns
Array declaration specifies number of rows and columns in the array
Row is horizontal and column is vertical
Must always use two subscripts to refer to individual elements of
table
◦ Row is first subscript
◦ Column is second subscript row

column

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 26


Multidimensional Arrays
General Form

DataType[,] ArrayName = new Datatype[NumberOfElements,NumberOfElements];

DataType[,] ArrayName = new DataType[ , ] = {ListOfValues} ;

Must use a comma to specify two dimensions to the array

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 27


Multidimensional Arrays
Column 0 Column 1 Column 2 Column 3
Examples:
Row 0 James Mary Sammie Sean
string[,] nameString = new string[3,4]; Row 1 Tom Lee Leong Larry
string[,] nameString = new string[ , ] = Row 2 Maria Margaret Jill John
{
{“James”, “Mary”, “Sammie”, “Sean”},
What are the value ?
{“Tom” , “Lee”, “Leon”, “Larry”}, nameString [1, 1]
nameString [2, 2]
{“Maria” , “Margaret”, “Jill”, “John”}
};

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 28


Initialize Two-Dimensional Arrays
Numeric array elements are initialized to 0 and strings are initialized to empty
strings
Use nested for loops to initialize array elements
int _row, _col;
string [ , ] _name = new string[ 3, 4 ];
for (_row = 0; _row < 3; _row ++)
{
for (_col = 0; _col < 4; _col ++)
{
_name[_row, _col] = “” ;
}
}

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 29


Object Oriented Programming
In Objected-Oriented Programming (OOP), developers split a program into
building blocks known as objects.

An object in OOP is a thing that stored in the computer’s memory.


The object has properties. Properties are the characteristic of the object.
What kind of properties does a customer object have?
Customer Id
Name
Date of birth
Gender
Address

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 30


Object Oriented Programming
Each object has a set of behaviours that enable it to do something.
In OOP, the method s are the operations that an object can perform.
What kind of operations does a customer object perform?
Create new customer
Update customer particular
Delete a customer

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 31


Class
Class is a template for an Object. Define the class before you create the object.
Define a class:
Accessibility level Keyword Class Name

Create object: a new instance of the object is created with new keyword
followed by the class name

Object Name
32

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT


Accessibility of
public - class can be accessed from everywhere, including code outside the current
project
private – class can only be accessed within the declared class itself.
protected - can be accessed only by code in the same class, or its sub class.
internal - can be accessed by any code in the same project, but not from another
project.
protected internal – not in the scope of this module

https://www.youtube.com/watch?v=G238zPCJBu4

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 33


OOP and VS Web Application
Right click VS Solution Explore to add new item, and select class.
The class is created. Noted that the class
name is same as file name
using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;
namespace Lec3
{
public class Score
{

}
}

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 34


Step 1 – Declare class properties
In C# 3.0 and later, auto-implemented properties make getter, setter declaration more concise.
However using this, validation of property cannot be done at property set.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;
namespace Lec3
{
public class Score
{
public string Admino { get; set; }
public int StudScore { get; set; }
}
}

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 35


Step 2 – Declare constructor
namespace Lec3
{
public class Score
{
public string Admino { get; set; }
public int StudScore { get; set; }
Constructor is a special method in a class.
public Score() It is used to create instance of a object.
{ The name must be the same as class
} name.

public Score(string MyAdmNo )


{
Admino = MyAdmNo; Optionally you may create overloaded
StudScore = 0; constructor
}

}
}
ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 36
Step 3 – Declare the method in class

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 37


Instantiating the class & invoke the method
protected void BtnAddScore_Click(object sender, EventArgs e)
{
// instantiate object s1 using new keyword follow by class name

Score s1 = new Score(TextBoxAdm.Text);

s1.StudScore = Convert.ToInt32(TextBoxScore.Text);
// call the AddScore method of new object s1

s1.AddScore();

lblScoreList.Text = "student score added";

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 38


Summary
Array Declaration & Initialisation
ArrayList and List collection
Accessing data in arrays
Use loops to traverse the elements of an array
Implement Object Orientated Programming in C#

ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 39

You might also like