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

Visual Programming (CSC-209) : Teacher: Arjumand Yar Khan 7/8/10 September 2015 Lecture 7

The document provides an overview of arrays and arraylists in visual programming. It discusses different types of arrays including single and multi-dimensional arrays as well as ragged arrays. It covers declaration and initialization of these arrays and provides examples. It also discusses advantages of ragged arrays over multi-dimensional arrays. Finally, it introduces arraylists as dynamic arrays and covers creation and adding elements to arraylists.

Uploaded by

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

Visual Programming (CSC-209) : Teacher: Arjumand Yar Khan 7/8/10 September 2015 Lecture 7

The document provides an overview of arrays and arraylists in visual programming. It discusses different types of arrays including single and multi-dimensional arrays as well as ragged arrays. It covers declaration and initialization of these arrays and provides examples. It also discusses advantages of ragged arrays over multi-dimensional arrays. Finally, it introduces arraylists as dynamic arrays and covers creation and adding elements to arraylists.

Uploaded by

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

Visual Programming

(CSC-209)
Teacher: Arjumand Yar Khan
7/8/10 September 2015 Lecture 7

Topics to be covered

Understanding Arrays & Objects


Declaration and initialization
Types of Array
Single vs multi-dimensional arrays
Ragged Arrays
Advantages of Ragged Arrays
Arraylists

Understanding Arrays

Suppose, you need to store years of 100 cars. Will you define 100
variables?
int y1, y2,, y100;

The data structures LIKE arrays, array lists, and Ragged arrays are useful to
solve many (such)types of programming problems.
WHAT IS AN ARRAY?
An array is a sequence of objects of same data types for instance strings.
The object of an array is known as element of an array.

13

Understanding Arrays &


Memory
They (elements) occupy continuous
area of memory.
Name

memory

24
C[0]
59
C[1]
35
C[2]
C[3]
...
C[4]
...
C[5]
...
C[6]
...
C[7]
...
Arrays are declaredC[8]
much like variables,
... with a set of [] brackets after the
data type, like this: C[9]
...

Single dimensional array

C# arrays are zero indexed; that is, the array indexes start at zero.
Arrays in C# work similarly to how arrays work in most other popular
languages.
There are, however, a few differences in which an important one is:

When declaring an array, the square brackets ([]) must come after the type,
not the identifier. Placing the brackets after the identifier is not legal
syntax in C#.

Declaration (Single dimensional array)


Type Specifier [] arrayName
E.g:

string[] names;

You need to instantiate the array to use it, which is done like this:
new type Specifier [numberOf Elements];
E.g: string[] names = new string[2];
where:
typeSpecifier is the data type you want to use.
arrayName is the name you want to use for the array.
numberOfElements is the number of array elements (size) you want.

Initializing Single dimensional


array

int[] numbers = new int[5] { 4, 3, 8, 0, 5 };

With one line, we have created an array with a size of 5,


and filled it with 5 integers. By filling the array like this,
you get an extra advantage, since the compiler will check
and make sure that you don't put too many items into the
array. Try adding a number more - you will see the
compiler complain about it.
Actually, it can be done even shorter, like this:
int[] numbers = { 4, 3, 8, 0, 5 };
This is short, and you don't have to specify a size.

Some Array Details


N 1 Rule
Each element of an array is referenced by its position in the
array.
The position of an element in an array is represented by an
index value or subscript. In an array with n elements the
index value are 0,1,n-1, where 0 represent the index
value of the first element and n-1 represent the index value
of last elements.
An element of an array is accessed by its subscript value The
subscript or index value is written inside a pair of square
bracket [] with the name of the array

Array Details
In C#, arrays are actually objects. System.Array is the abstract base type
of all array types. You can use the properties, and other class members,
that System.Array has.
The System.Array class provides many other useful methods/properties,
such as methods for sorting, searching, and copying arrays.
An example of this would be using the Length property to get the length
of an array. The following code assigns the length of the numbers array,
which is 5, to a variable called LengthOfNumbers:
int[] numbers = {1, 2, 3, 4, 5};
int LengthOfNumbers = numbers.Length;

Important Note

Complete application as an Example on


Single Dimensional Array is attached as a
separate file

Declaration MULTIDIMENSIONAL ARRAYS


A multi-dimensional array is an array of more than one
array.
It consists of columns and rows. Each element of the multidimensional array is referenced by its index values or
subscript For example:
The index value of two dimensional array consists of two
subsists. One subscript represent row number while the
second represent column number.
Syntax:
int [,] number;

Initializing multi- dimensional array

TwodimensionalArray
int[,]number=newint[2,3]{{1,2,3},{4,5,6}};
ThreeDimensionalArray
Int[,,]number=newint[1,2,3].
FourDimensionalArray
Int[1,2,3,4]number=newint[1,2,3,4]{{{{1,2},{1,2},
{1,2}},{{1,2},{1.2},{1,2}}}};

Jagged Arrays
A Jagged array is an array of arrays.
A jagged array is an array whose elements are arrays. The
elements of a jagged array can be of different dimensions
and
sizes.
Compared to a 2D array where each row has equal number
of columns a Jagged array has different number of columns.

Jagged Arrays vs Multi-dimentional array

Multi dimensional array


string[][]array=newstring[5][7];//inC++
string[,]array=newstring[5,7];//inC#
Jagged Array
string[][]array=newstring[5][];

Important Note

Complete application as an Example on


Multi-Dimensional Array is attached as a
separate file

Jagged Arrays
A jagged array is the same in any language, but it's
where you have a 2+ dimensional array with
different array lengths in the second and beyond
array.

DECLARATION
Declaring a Jagged array
You can declare a jagged array scores of int
values as:
int [][] scores
Declaring an array, does not create the array in
memory. To create the above array:
int[][] scores = new int[3][];

INITIALIZATION
jaggedArray[0] = newint[5];
jaggedArray[1] = newint[4];
jaggedArray[2] = newint[2];
Each of the elements is a single-dimensional
array of integers. The first element is an array
of 5 integers, the second is an array of 4
integers, and the third is an array of 2 integers.

Ragged Arrays (Cont..)


It is also possible to use initializers to fill
the array elements with values, in which
case you do not need the array size. For
example:

jaggedArray[0] = newint[] { 1, 3, 5, 7,
9 }; jaggedArray[1] = newint[] { 0, 2, 4, 6
}; jaggedArray[2] = newint[] { 11, 22 };

Simplifying the declaration and initialization of Ragged array

Initialization of Ragged array at the time of its Declaration:


int[][] scores = new int[2][]{new int[]{92,93,94},new int[]{85,66,87,88}};

Where, scores is an array of two arrays of integers - scores[0]


is
an array of 3 integers and scores[1] is an array of 4 integers.

Accessing individual array


elements

// Assign 77 to the second element ([1]) of the first array ([0]):

jaggedArray3[0][1] = 77;
// Assign 88 to the second element ([1]) of the third array ([2]):
jaggedArray3[2][1] = 88;

Example 1: Ragged Arrays


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ragged_Arrays
{
class Program
{
static void Main(string[] args)
{
string[] []names = new string[2][];

names[0] = "City University";


names[1] = "Peshawar";
foreach (string s in names)
Console.WriteLine(s);
Console.ReadLine();
}
}
}

Example 2: Ragged Arrays


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ragged_Arrays
{
class Program
{
static void Main(string[] args)
{
int[][] names = new int[2][];

names[0] = new int[] { 10, 45, 734 };


names[1] = new int[] { 986,
233,233};
foreach (int s in names[0])
Console.WriteLine(s);
Console.ReadLine();
}
}
}

Advantages of Ragged Array


Ragged arrays are generally considered better since they can
do everything a multi-dimensional array can do and more. In
a Ragged array you can have each sub-array be a different
size, whereas you cannot do that in a multi-dimensional
array.
Indexing jagged arrays is fast.
Jagged arrays are almost always better when you need an
array of arrays. That is, when the second dimension is
variable.

Important Note

Complete applications as an Example on


Ragged/Jagged Array is attached as a
separate file

ARRAYLIST OBJECTS
The arrays discussed thus far are called static arrays. This is because
when you set their element sizes, they cannot be changed. Indeed, you
cannot use a static array until its dimension or dimensions have been
determined.
However, life isnt always that simple. Quite often you have a situation
in which you know you need to store the data in an array but dont have a
clue how many elements you might need.

For example, you might write a program that records the names and
addresses of friends in an object called Friends. When you run the
program, you might need 50 array elements, but another person might
need only only 20 elements. The issue is, How do you decide how many
elements to allocate for the array?

ARRAYLIST
With static arrays, the usual solution is to settle for a worst-case design. A worstcase design is one in which you try to guess the largest reasonable value you will
ever need for the size of the array and then set the dimension for the array to that
size.
This can be inefficient because you will likely overestimate the required size for the
array most of the time.
The ArrayList object overcomes this limitation of static arrays. ArrayList objects
have the effect to create dynamic arrays for which you dont have to specify a size.
Now see how this works.
ArrayList objects offer some features that are not available with simple array. This
is especially true for those arrays where you dont know the size of the array at
compile time.

Key Points

The ArrayList is a class of System.Collection namespace


which is just like arrays.
Unlike array you can add and remove items from a list at a
specified position using an index and the array resizes itself
automatically.

It also allow dynamic memory allocation, adding, searching


and sorting items in the list.

Creation of ArrayList
To create the ArrayList the following code
is used:
ArrayListarr =newArrayList();

Add the elements in ArrayList

To add values, the Add() method is used.


The following code describes how we add the elements to the ArratList.
namespace ArrayList1
{
class Program
{
static void Main(string[] args)
{
ArrayList arr = new ArrayList();
arr.Add("Sunday");
arr.Add("Monday");
arr.Add("Tuesday");
arr.Add("Wednesday");
arr.Add("Thusday");
arr.Add("Friday");
arr.Add("Saturday");
Console.WriteLine("The elements of the ArrayList are:");
foreach (object obj in arr)
{
Console.WriteLine(obj);
}
}
}
}

Add the elements in a List


private void button1_Click(object sender, EventArgs e)
{
/* List<string> Names = new List<string>();
Names.Add("arjumand");
Names.Add("yar");
Names.Add("khan");
MessageBox.Show(Names[1]);*/

List<int> Numbers = new List<int>();


Numbers.Add(5);
Numbers.Add(2);
Numbers.Add(1);
MessageBox.Show(Numbers[1].ToString());
}

Methods of ARRAYLIST

Note:
Complete applications as an Example on Methods of Array List are
attached as separate files

Capacity Method of Array List


Capacity
Gets or sets the number of elements that the ArrayList can
contain.
The default capacity of an ArrayList is 4. If we add 5 elements
then its capacity becomes doubled (that is 8) relative to the
previous one (that is, 4).

Count Method of Array List


Count Method
Gets the number of elements actually contained
in theArrayList.

Clear()Method of Array List


Clear Method
Removes all elements from theArrayList.

Insert Range() Method of Array


List
Insert Range()
Inserts the elements of a collection into
theArrayListat the specified index.

IndexOf(object) Method of Array


List
IndexOf(object)
Searches for the specified object and returns the
zero-based index of the first occurrence within the
entireArrayList.

SortMethod of Array List


Sort
Sorts the elements in the entireArrayList.

Assignment
* Bucket Analogy
* Array List class (Constructor, other important
Methods)

Due Date: 7/4/2015

Array vs Array List


Arrays are strongly typed
Array-Lists are not strongly typed.
Elements in Arrays have to be of same data type (int, string, double, char,
bool).
Elements in Array-List can have a combination of combined data types or
single data type. Note: If Array-List has combined data types then type
cast is must.
Arrays are fixed specified length size therefore they cannot be resize
dynamically during runtime.
Array-List can resize dynamically during runtime

Note:
Complete application as an Example on Array List with type casting is
attached as a separate file.

Summarize the disussion


The End

You might also like