Data Structures and Algorithms: Tanya M Smael Department of Computer Science Soran University
Data Structures and Algorithms: Tanya M Smael Department of Computer Science Soran University
Data Structures and Algorithms: Tanya M Smael Department of Computer Science Soran University
Lecture 2
Tanya M Smael
Department of Computer Science
Soran University
This session
• Arrays
• Recursion
Arrays
• It is a data structure designed to store a fixed-size sequential collection of
elements of the same type, i.e., it is a collection of variables of the same
type.
• An array stores a fixed-size sequential collection of elements of the same
type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
Array Types
1 2 5 7 8
Elements of an
array
Array of 5
elements
Array variable and creating Arrays
• datatype[] arrayname;
Example: Square brackets
double[] myList;
For example,
myList.length returns 10
Declaring, creating, initializing Using
the Shorthand Notation
double[] myList = {1.9, 2.9, 3.4, 3.5};
This shorthand notation is equivalent to the following statements:
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;
Use of Arrays
• Below shown examples have only been able to hold one value at
a time
• Example:
int age = 20;
string name = “Orange”;
int id = 3;
• An Array allows you to use just one identifying name that refers
to lots of values
Assigning values
arrayName[position] = arrayValue;
Total
int[] age = new int[4]; number of
age[0] = 58; // first array array = size
age[1] = 24;
Index starts from zero
age[2] = 33;
age[3] = 41; // last (4th) array
• Structure of 2D array
Column 0 Column 1 Column 2
0 Int[ ]
Int[ ]
1
Int[ ]
2
• You can also initialize the array upon declaration like this:
• Fibonacci series
• Binary search
• Linear search
• Quick sort
• Merge sort
• Tree traversal
• Towers of Hanoi and many more…