Sunday 28 June 2015

OPERATORS IN JAVA

OPERATORS IN JAVA

JAVA supports 44 number of operators and like C and C++, it's divided into 3 categories ,
1. Unary operator.
2. Binary operator
3. Conditional operator.

UNARY: + , - , ++ , -- , !

BINARY:
Arithmatic: + , - , * , / , ÷
Logical: && , ||
Bitwise: & , | , ^
Relational: > , < , >= , <= , != , ==
Assignment: = , += , -= , *= , ÷= , /=
Shift: << , >> , >>> ( unsigned right shift)

Ternary: ?!
Special: ( ), [ ] , , , . , type , instanceof

Modulus operator never works for float and double value in C or C++, but works in JAVA. I.e System.out.println(10.0℅3.0); o/p = 1.0

TYPE OPERATOR OR TYPE CASTING OPERATOR
Typecasting in JAVA is divided into 3 types-
1. Implicit casting
2. Explicit casting
3. Boolean casting.

Instanceof operator: it's am object comparison operator.
This operator always checks the object existence and returns Boolean value.
Object if the child class can be the object of the parent class.

DOT OPERATOR: It access the variable or the constant, accesses the method , accesses the object, accesses the class and accesses the package.

Saturday 27 June 2015

FLOAT AND DOUBLE

Float and Double : these two datatypes always stores the real Constant.
Real Constant is always by default double in nature.( example, 4.2 is double in nature and thus, it is a real Constant.)
Thus, float x = 4.2; is an error.
Rather you have to typecast it as : float x = (float)4.2; or float x = 4.2f.

CHARACTER DATATYPE:
Character in JAVA supports Unicode. 65536 number of characters are supported by the JAVA language, since the maximum value of 16bits is 216 which is 65536.
Boolean in JAVA only supports true or false values.

Friday 26 June 2015

DATATYPE AND WRAPPER CLASS

JAVA supports 8 primitive datatypes, then the language is not purely object oriented.
For each datatype. JAVA provides a predefined class ( known as wrapper class in JAVA).
Wrapper class is used to make JAVA pure object oriented.

All the wrapper class present in java.lang package and the default package in JAVA.

PRIMITIVE DATATYPE

Datatype.    Size.    default value.    Wrapper class
Byte.             8 Bits.           0.                    Byte
Short.            16 Bits.        0.                    Short      
Int.                 32 Bits.         0                    Integer
Long.             64 Bits.          0L.                Long
Float.             32 Bits.          0.0f.             Float
Double.          64 Bits.         0.0.                Double
Boolean.         1 Bit.             False.           Boolean
Char.               16 Bits.        /u0000.         Character

Wrapper class makes JAVA pure object oriented but still it's not purely object oriented ad it supports primitive datatypes.

Signed and unsigned are the two keywords that are not available in JAVA. So by default the datatype is signed in nature. Character datatype in JAVA is signed in nature, I.e it only holds positive value. (As ASCII value us always positive)

Negative number is always stored in the form of 2's complement. Example: 11111111 -> 00000001(2's complement) = -1.

MAX_VALUE & MIN_VALUE are the two predefined static constants which always display the maximum and the minimum value related to the datatype and present in each wrapper class.

toString ( ) is a predefined static method present in the wrapper class which converts any datatype to the string format.
parseByte( ) is a static method present in the Byte upper class which converts a string to byte datatype.

FLIR One : The thermal camera for Android and iOS now available

Just plug it into your micro USB port(for Android) or to the lightning port( for iPhone) and pheww, work's done! Some cool stuff to handle thereafter.

The FLIR thermal camera allows mobile users to see heat from the comfort of their smartphone or tablet.

Spy stuff huh? Well, to be honest, I have seen better( in James Bond and Mission Impossible of course ).

Google takes next-gen autonomous cars to the streets.

Vroom! Tech has always been something orgasmic to me.
And this is, well... NextGen tech!

Google posted pictures of the car driving ...well, itself, in the streets!

Apple removes Civil War games from App Store for showing the Confederate flag

Poor game developers, all their hard work was also shot upon.

In the wake of last week's horrific shooting at a church in Charleston, Apple assassinated all its civil war games, as a gesture of goodwill, I suppose.

Think different! That's always been Apple. Right?

Class 2

Class 2

Void: The main method never returns any value to the JVM. If the main method doesn't return any value, then the return type should be void in JAVA.
public static = static public
COMMAND LINE ARGUMENT
The arguments accepted by the main function is called command line arguments. The main function in JAVA only accepts array of strings as an argument.
String is a predefined class present in JAVA language.
String args [ ] -> name of the array of strings.

NAMING CONVENTION FOR PREDEFINED MEMBERS.
1. Class -
Example: BufferedReader , String
Each word's first letter should be capital, and there shouldn't be any space.
2. Predefined "to" Method -
Example: toString( ), toCharArray( ) ; I.e except the first word, each word's first letter should be capital.
3. Predefined Constant: SIZE , MAX_VALUE; All the letters should be inupper case.
4. Package: java.lang, javax.swing, java.applet ; here each letter should be in lower case and the packages are separated by a "." symbol.

DEFAULT LENGTH OF THE COMMAND LINE ARGUMENT IS 0.

EXAMPLE OF A COMMAND LINE ARGUMENT:
public class Test{
static public void main ( String args[  ] )
{
    System.out.println (args.length); // 2
    for(int i=0; I<args.length; I++)
    {
        System.out.println (args [ i ]); //10, 20
    }
    System.out.println( args[ 0 ] + args [ 1 ] ); // 1020
    System.out.println(10+20); // 30
    System.out.println (5+6+'A'+'B'+5+6+(4+5)); //76B569
    System.out.println("10" + (5 - 10)); // 10-5
}
}

Convert string to integer by parseInt( ). It is a static member and it is called by a class.
Similarly, string to float can be converted by the use of parseFloat.

SYSTEM.OUT.PRINTLN:
A static member is always called by a Class name and a Non Static member is always called by an object name.
The difference between System.out and System.err is that the output produced by System.err can't redirect a file but System.out can
The difference between print and println is that println just adds a new line after printing your desired line.

Thursday 25 June 2015

Masala of the Maggi

The milk that your milkman leaves at your doorstep every morning is milched from a cow drugged with Oxytocin.

The mangoes you enjoyed this summer had calcium carbide coated onto their skins.

The cauliflower you munched into last winter, was doped with Arsenic.

Yet we panic only when we realise Maggi had lead.

How did Apple manage to reduce the storage size of  iOS 9 to 1GB from 5 GB in iOS 8?

This is due to a new technology called 'App Thinning'

Now this consisted of 3 parts, let's just have an bird's eye view:

App Slicing: iOS apps are developed to run on a variety of devices, so they come with code to support all them, whether or not your particular device requires it. App Slicing will allow your device to download only those files required by our device. Example: you don't need the 3x iPhone 6 Plus assets if you're running a 4-inch model.

On-Demand Resources (ODRs): It works on the idea that an app probably doesn't need its entire library of resources at any given time, so parts of it can be downloaded or deleted as needed. Developers will be able to specify what code is needed at what times by tagging sections of code as ODRs. These portions will be automatically downloaded from the App Store when they are required and deleted when they won't be needed again.

Bitcode: It refers to an "intermediate representation" of an app that developers will upload to the App Store rather than a pre-compiled binary. This works hand-in-hand with App Slicing, allowing the bitcode to be compiled on demand as 32-bit or 64-bit, depending on the downloading device. This will also allow any compiler improvements made by Apple to be implemented automatically, rather than having developers resubmit their apps.

INTRODUCTION TO JAVA PROGRAMS

Block----> public class class_name
{
public static void main(string args[ ])
{
System.out.println (...);
}
}

Access specifier in JAVA language:
The major job of access specifier is to specify the scoop of the variable (data member), constructor out any class.
Access specifier---> variable, function, class, constructor.

JAVA folder-> package

Boundaries/scope:
within the same class
• within the same package
• outside the package

Types of access specifier in JAVA: public, protected, default(no access specifier), private

Public: within the same class, within the same package, outside the package
Protected: within the same class, within the same package and outside the package (only in inheritance)
Default: within the same class, within the same package
Private : within the same class.

In JAVA, you can't declare a variable or function or any member as global.

Java doesn't support an global member like C or C++, bit if a member is declared as public , it behaves as a global member in JAVA.

Execute that class that only contains the main.
You can't execute more than one class simultaneously.

If the class is declared as public then the class name and file name should be the same.

Almost one public class can be declared and that would be the entry point.

Private and public keywords are not allowed for top level class but nested class can be declared as private or protected.

Class
Class is a collection of similar kind of objects, that is from one class we can create "n" number of objects, all with similar type.
Class is a blue print of the object, I.e skeleton.

Class is a logical container which never allocated any memory.
In JAVA , class is able to contain 4 types of members.
1. Data mamber
2. Method member
3. Block member
4. Constructor member

public class Test
{
  int x; // data member
  Test() // constructor member
  {
  }
  static // block member
  {
  }
  public static void main( string args[]) //method member
  {
  System.out.println("Hello");
}

Javac: to compile the JAVA program.
Javap: JAVA dessemble. It will display all the members present in all user defined or pre defined class.

Class name is the identifier which maybe same as the file name, but should satisfy the rules of the identifier ( data member, object/ reference name, method name, constructor name, class name, Package name )
Space is not allowed in identifier.
Identifier rules:
1. Space is not allowed in identifier.
2. Digits are allowed but the name can't start with digits.
3. Should not be a reserved word. (Keyword)
4. No special symbols are allowed except "_" or "$"

PUBLIC STATIC VOID MAIN
In JAVA, "main" is user defined function, but the signature is predefined.
Compiler never checks the "main" method existence.
But the execution is always started from the main method.

KERNEL calls the main method in C and C++
But JVM( JAVA Virtual Machine ) calls the main function in JAVA.
• JAVA Virtual Machine.
• System software
• Development in C language.
• Platform dependant ( but JAVA is platform independant)

JVM is a system software inbuilt to OS (I.e itbis present by default)
The main job of JVM is to execute the class file, and the execution always starts from the main method.l, as the main method is always called by JVM from the OS, which is outside the package. So main method should be declared as public, else it can't be called from outside.

WHY MAIN METHOD IS STATIC IN JAVA?
Main method is called by the JVM with the name of the class.
If a method is called by the class name, it should be declared as static in JAVA.

A curved iPhone is reportedly planned

Hold your breath!
Apple is planning to give an "Edge" to Samsung yet again.
Plus,
Sources claim that Apple is very interested in OLED display technology, and that is good news given how well these displays have evolved in color saturation and brightness.

T-Mobile's iPhones are getting the 'blue screen of death'

If you have the same problem, you are not alone!

From now, you don't need a Facebook account to log into the Facebook messenger

Facebook Messenger no longer requires a Facebook account. Starting today, new Messenger users in the US, Canada, Venezuela and Peru can sign up using a full name and phone number.

Seems like the messenger didn't get much of a success!

Color-changing condoms tell you what sort of VD you just got

A group of teenage inventors have struck upon a clever way to alert folks to the presence of various venereal diseases before the burning starts: fluorescing condoms that light up when they encounter dangerous bacteria or virii.

Data Structure Chapter 1 & 2



Introduction to
Algorithm
What is an Algorithm? (1/2) 
Definition
A computable set of steps to achieve a desired result
What is an Algorithm? (2/2) 
Properties
      –  Finiteness -> an algorithm terminates after a finite numbers of steps
      –  Definiteness -> each step in algorithm is unambiguous. This means that the action specified by the step cannot be interpreted (explain the meaning of) in multiple ways & can be performed without any confusion
      –  Input -> an algorithm accepts zero or more inputs
      –  Output -> it produces at least one output
      –  Effectiveness -> it consists of basic instructions that are realizable. This means that the instructions can be performed by using the given inputs in a finite amount of time

Classes of Algorithm (1/4)
There is no universally accepted breakdown for the various types of algorithms, but there are common classes that algorithms are frequently agreed to belong to e.g.
Dynamic Programming Algorithms: This class remembers older results and attempts to use this to speed the process of finding new results.

Classes of Algorithm (2/4)
Greedy Algorithms: Greedy algorithms attempt not only to find a solution, but to find the ideal solution to any given problem.
Brute Force Algorithms: The brute force approach starts at some random point and iterates through every possibility until it finds the solution.
Randomized Algorithms: This class includes
any algorithm that uses a random number at
any point during its process.

Classes of Algorithm (3/4)
Branch and Bound Algorithms: Branch and bound algorithms form a tree of subproblems to the primary problem, following each branch until it is either solved or lumped in with another branch.
Simple Recursive Algorithms: This type of algorithm goes for a direct solution immediately, then backtracks to find a simpler solution.

Classes of Algorithm (4/4)
Backtracking Algorithms: Backtracking algorithms test for a solution, if one is found the algorithm has solved, if not it recurs once and tests again, continuing until a solution is found.
Divide and Conquer Algorithms: A divide and conquer algorithm is similar to a branch and bound algorithm, except it uses the backtracking method of recurring in tandem with dividing a problem into subproblems.
Algorithm Analysis (1/15) Why should we analyze algorithms?
A problem may have numerous algorithmic solutions.
In order to choose the best algorithm for a particular task, you need to be able to judge how long a particular solution will take to run.
Or, more accurately, you need to be able to judge how long two solutions will take to run, and choose the better of the two.
You don't need to know how many minutes and seconds they will take, but you do need some way to compare algorithms against one another.

Algorithm Analysis (2/15)
Most algorithms transform input objects into output objects.
The running time of an algorithm typically grows with the input size.
Average case time is often difficult to determine.
We focus on the worst case running time.
Easier to analyze
Crucial to applications such as games, finance and robotics
Algorithm Analysis (3/15)

How to Calculate Running Time
Write a program implementing the algorithm
Run the program with inputs of varying size and composition
Use a method like System.currentTimeMillis() to get an accurate measure of the actual running time
Plot the results

Algorithm Analysis (4/15) 
Limitations
It is necessary to implement the algorithm, which may be difficult.
Results may not be indicative of the running time on other inputs not included in the experiment.
In order to compare two algorithms, the same hardware and software environments must be used.

Algorithm Analysis (5/15) 
Theoretical Analysis
Uses a high-level description of the algorithm instead of an implementation
Characterizes running time as a function of the input size, n.
Takes into account all possible inputs
Allows us to evaluate the speed of an algorithm independent of the hardware/software environment

Algorithm Analysis (6/15)
Primitive Operations
Basic computations performed by an algorithm
Identifiable in pseudocode
Largely independent from the programming language
Exact definition not important (we will see why later)
Assumed to take a constant amount of time in the RAM model

Algorithm Analysis (7/15)
Primitive Operations Examples: Evaluating an expression
Assigning a value to a variable
Indexing into an array
Calling a method
Returning from a method

Algorithm Analysis (8/15) 
Counting Primitive Operations
By inspecting the pseudocode, we can
determine the maximum number of primitive
operations executed by an algorithm, as a
function of the input size
Algorithm arrayMax(A, n) currentMax ¬ A[0]
for i ¬ 1 to n - 1 do
if A[i] > currentMax then currentMax ¬ A[i]
{ increment counter i } return currentMax
# operations 1
n
(n - 1) (n - 1) (n - 1) 1
4n - 1
Total

Algorithm Analysis (9/15) 
Estimating Running Time
Algorithm arrayMax executes 4n - 1 primitive operations in the worst case.
Define:

a = Time taken by the fastest primitive operation 
b = Time taken by the slowest primitive operation
Let T(n) be worst-case time of arrayMax. Then a(4n-1)<=T(n)<=b(4n-1)
Hence, the running time T(n) is bounded by two linear functions

Algorithm Analysis (10/15) 
Growth Rate Vs Running Time
Changing the hardware/ software environment 
Affects T(n) by a constant factor, but
Does not alter the growth rate of T(n)
The linear growth rate of the running time T(n) is an intrinsic property of algorithm arrayMax
Algorithm Analysis (11/15)
  Worst-case Complexity
            –  Maximum steps the algorithm takes for any possible input.
            –  Most tractable measure.
  Average-case Complexity
            –  Average of the running times of all possible inputs.
            –  Demands a definition of probability of each input, which is usually difficult to provide and to analyze.
  Best-case Complexity 
– Minimum number of steps for any possible input. Not a useful measure.

Algorithm Analysis: (12/15) 
Example
Alg.: MIN (a[1], ..., a[n]) m a[1];
for i 2 to n if a[i] < m
then m a[i]; Running time:
the number of primitive operations (steps)
executed before termination
T(n) =1 [first step] + (n) [for loop] + (n-1) [if condition] + (n-1) [the assignment in then] = 3n - 1
Order (rate) of growth:
The leading term of the formula
Expressestheasymptoticbehaviorofthealgorithm


Algorithm Analysis: (13/15) Typical Running Time Functions
1 (constant running time):
Instructions are executed once or a few times
logN (logarithmic)
A big problem is solved by cutting the original problem in smaller
sizes, by a constant fraction at each step N (linear)
A small amount of processing is done on each input element N logN
A problem is solved by dividing it into smaller problems, solving them independently and combining the solution
Algorithm Analysis: (14/15) Typical Running Time Functions
N2 (quadratic)
Typical for algorithms that process all pairs of data items (double
nested loops) N3 (cubic)
Processing of triples of data (triple nested loops)
NK (polynomial)
2N (exponential)
Few exponential algorithms are appropriate for practical use

Algorithm Analysis: (15/15)
Asymptotic Notations
A way to describe behavior of functions in the limit Abstracts away low-order terms and constant factors
How we indicate running times of algorithms
Describe the running time of an algorithm as n grows to ¥
• • •
O notation: (Big Oh)
asymptotic “less than”:
W notation: (Big Omega) asymptotic “greater than”:
Q notation: (Big Theta) asymptotic “equality”:
f(n) “≤” g(n) f(n) “≥” g(n) f(n) “=” g(n)

O(Big Oh) -Notation
O(Big Oh) - Example
  2n2 = O(n3):
  1000n2+1000n = O(n2):
2n2 ≤cn3Þ2≤cnÞc=1andn0=2 n2 = O(n2): n2 ≤ cn2 Þ c ≥ 1 Þ c = 1 and n0= 1
1000n2+1000n ≤ 1000n2+ 1000n2 = 2000n2Þ c=2000 and n0 = 1
  n = O(n2): n ≤ cn2 Þ cn ≥ 1 Þ c = 1 and n0= 1
  2n + 10 = O(n) :
  n2¹O(n)
  7n -2 = O(n)
  3n3 + 20n2 + 5 = O(n3)
  3 logn + log log n = O(log n)

W (Big Omega) - Notation
• Intuitively: W(g(n)) = the set of functions with a larger or same order of growth as g(n)
W (Big Omega) - Example 5n2 = W(n)
$ c, n0 such that: 0 £ cn £ 5n2 Þ cn £ 5n2 100n + 5 ≠ W(n2)
$c,n0 suchthat:0£cn2 £100n+5 100n + 5 £ 100n + 5n (" n ³ 1) = 105n
cn2 £ 105n
Since n is positive Þ cn – 105 £ 0
Þ c = 1 and n0 = 1
Þ n(cn – 105) £ 0
Þ contradiction: n cannot be smaller than a constant
n = W(2n), n3 = W(n2), n = W(logn)

Þ n £ 105/c
Q (Big Theta) - Notation


• Intuitively Q(g(n)) = the set of functions with the same order of growth as g(n)
Q (Big Theta) - Example n2/2 –n/2 = Q(n2)
  1⁄2 n2 - 1⁄2 n ≤ 1⁄2 n2 "n ≥ 0 Þ c2= 1⁄2
  1⁄2 n2 - 1⁄2 n ≥ 1⁄2 n2 - 1⁄2 n * 1⁄2 n ( "n ≥ 2 ) = 1⁄4 n2 Þ c1= 1⁄4 
– n≠Q(n2):c1 n2 ≤n≤c2 n2 Þ only holds for: n ≤ 1/c1 6n3 Q(n2):c1 n2 ≤6n3 ≤c2 n2 Þ only holds for: n ≤ c2 /6 n≠Q(logn):c1 logn≤n≤c2 logn
Þ c2 ≥ n/logn, " n≥ n0 impossible 

Asymptotic Notations - Exercise
For each of the following pairs of functions, either f(n) is O(g(n)), f(n) is Ω(g(n)), or f(n) is Θ(g(n)). Determine which relationship is correct.
      –  f(n) = log n2; g(n) = log n + 5
      –  f(n) = n; g(n) = log n2
      –  f(n) = log log n; g(n) = log n
      –  f(n) = n; g(n) = log2 n
      –  f(n) = n log n + n; g(n) = log n
      –  f(n) = 10; g(n) = log 10
      –  f(n) = 2n; g(n) = 10n2
      –  f(n) = 2n; g(n) = 3n
f(n) = Q (g(n)) f(n) = W(g(n)) f(n) = O(g(n)) f(n) = W(g(n)) f(n) = W(g(n)) f(n) = Q(g(n)) f(n) = W(g(n)) f(n) = O(g(n))
More on Asymptotic Notations
  There is no unique set of values for n0 and c in proving the asymptotic bounds
  Prove that 100n + 5 = O(n2)
100n+5≤100n+n=101n≤101n2 for all n ≥ 5
n0 =5andc=101isasolution 
– 100n+5≤100n+5n=105n≤105n2 for all n ≥ 1
n0 = 1 and c = 105 is also a solution
Must find SOME constants c and n0 that satisfy the asymptotic notation relation
Comparisons of Functions
  Theorem:
f(n) = Q(g(n)) Û f = O(g(n)) and f = W(g(n))
  Transitivity:
f(n) = Q(g(n)) and g(n) = Q(h(n)) Þ f(n) = Q(h(n)) 
– SameforOandW
  Reflexivity: 
– f(n) = Q(f(n)) 
– SameforOandW
  Symmetry: 
– f(n) = Q(g(n)) if and only if g(n) = Q(f(n))
  Transpose symmetry: 
– f(n) = O(g(n)) if and only if g(n) = W(f(n))


Asymptotic Notations in Equations
On the right-hand side
Q(n2) stands for some anonymous function in Q(n2) 2n2 + 3n + 1 = 2n2 + Q(n) means:
There exists a function f(n) Î Q(n) such that
2n2 + 3n + 1 = 2n2 + f(n)
On the left-hand side
2n2 + Q(n) = Q(n2)
No matter how the anonymous function is chosen on the left-hand side, there is a way to choose the anonymous function on the right-hand side to make the equation valid.

Sorting Algorithms
Name
Best
Average
Worst
Method
Quick
n log n
n log n
n2
Partitioning
Merge
n log n
n log n
n log n
Merging
Heap
n log n
n log n
n log n
Selection
Insertion
n
n2
n2
Insertion
Selection
n2
n2
n2
Selection
Bubble
n2
n2
n2
Exchanging
Other Sorting Algorithms
Introsort
Timsort
Shell sort
Binary Tree sort Cycle sort
Library sort
Patience sort Smoothsort
Strand sort Tournament
sort
Cocktail sort Comb sort
Gnome sort Bogosort
Comparison Sort
Other Sorting Algorithms
Pigeonhole sort Bucket sort
Counting sort
LSD Radix sort
MSD Radix sort Spreadsort
Non Comparison Sort


______________________________________________________________________________________


Introduction to Data Structures 
• Problem solving =


– Understanding the problem – Designing a solution

– Implementing the solution 

What exactly is a solution? – A solution = a program 
An Algorithm 
An algorithm is a sequence of steps that take us from the input to the output.
Properties of Algorithm 
–  Input: may or may not some input data
–  Output: at least one output
–  Definiteness: every step must be clear and unambiguous
–  Finiteness: It must terminate after a finite number of steps
–  Effectiveness: the steps must be basic steps so that dry-run will be possible

Data Organization 
• Any algorithm we come up with will have to manipulate data in some way 
– The way we choose to organize our data directly affects the efficiency of our algorithm 
• Solution = algorithm + data organization
– Both components are strongly interconnected. 

Data structures 
Data structure: An arrangement of data in a computer’s memory (or sometimes on a disk).
conceptual and concrete ways to organize data for efficient storage and efficient manipulation 
– Arrays, linked lists, stacks, trees, hash tables. 

Algorithms manipulate the data in these 
structures in order to accomplish some task. – Inserting an item, search for an item, sorting. 

How are Data structures used • As an actual way to store real-world data 
– e.g., lists, trees
• As a tool to be used only within a program 

(not visible to the user)
– E.g., stacks, queues, priority queues 

• As a model of real-world situations – e.g., graphs 
Why different data structures 
• Each data structure has different advantages and disadvantages, and will be useful for different types of applications. 
– Example: arrays
• Fast access: if we know the index of the item we are looking for • Insertion and Deletion is slow
• size is fixed 

– Maintain a Job Queue • Queuecanbeused 
– Hierarchy of employees of an organization • Tree can be used  
Stack 
Types of data structures 
Data Structure 
Linear Non Linear 
Queue Tree Graph 
ADT 
A primitive data type holds a single piece of data – e.g. in Java: int, long, char, boolean etc.
– Legal operations on integers: + - * / ... 

Adatastructurestructuresdata! 
–  Usually more than one piece of data


–  Should provide legal operations on the data
–  The data might be joined together (e.g. in an array): a 
collection 

An Abstract Data Type (ADT) is a data type together with the operations, whose properties are specified independently of any particular implementation.
Principles of ADT 
• Encapsulation:Providingdataandoperationsonthe data 
• Abstraction:hidingthedetails. 
– e.g. A class exhibits what it does through its methods; however, the details of how the methods work is hidden from the user 
• Modularity: Splitting a program into pieces.
– An object-oriented program is a set of classes (data structures) which work together.
– There is usually more than one way to split up a program .

__________________________________________________________________________________________________________________________________________________________________



A
R
R
A
Y
\0






327
328
329
330
331
332

• An array is an indexed sequence of components
– The array occupies sequential storage locations
– The length of the array is determined when the array is created, and cannot be changed
– Each component of the array has a fixed, unique index • Indices range from a lower bound to an upper bound
– Any component of the array can be inspected or updated by using its index
• This is an efficient operation: O(1) = constant time
Array Dimensions
• The simplest form of array is a ‘one- dimensional’ array
• The dimension of an array can be 1 or more than 1
• 1-D array – int A[10];
• 2-D array
– int A[3][5];
General Info
   The two basic operations that access an array are 
– Extraction x = A[i]; – Storing A[i] = x; 

   The smallest index of the array is called ‘lower bound’ (0 always in ‘C’) and highest index is ‘upper bound’ 
• The number of elements in an array is – upper - lower + 1 

General Info
   Neither the upper nor the lower bound of an array can be changed during program execution (Static) 

   One very useful technique is to declare a bound as a constant identifier (MACRO) 

1-D Array • Declaration
– int A[100];
   The address of first element (A[0]) is called the 
‘base address’ let it be denoted by base(A) 

   Suppose the size of each individual element of 
the array is esize
Then the reference to the A[i] is to the 
element at location base(A) + i * esize
• int a[5]; • int *p;
• p = a;

‘a’ is a constant pointer pointing to the first

1-D Array & Pointer 
Array of pointers int *a[10]; 
Array a can store 10 addresses Ex. a[0] = &p, a[1] = &q like that 
Pointer to an array

int (*a)[10];

a is a pointer pointing to an array of 10 integers 


Declaration 
int A[3][5];
This defines a new array containing 3 
elements 
Each of these elements is itself an array containing 5 integers 

2-D Array A 2-D array actually stored as a linear array 
int numbers[3][4];

2-D Array & Pointer 


  • int A [3][4]; 
  • int (*p)[4]; 


Array Operations 
Traversal 
Searching 
Sorting 
Insertion
At begin, end, specific position, after element, before 
element 
Deletion 
From begin, end, specific position, after element, before element, element 
Merging 
Reversing 

Inserting an Element 
1. If array is full then print “overflow”
2. Else shift the elements to right from the position where you want to insert
3. Insert the new element at that position