HTML

html content help to improve the coding

Saturday, 31 March 2012

TREE IN DATA STRUCTURE

Tree (data structure)

From Wikipedia, the free encyclopedia
Jump to: navigation, search
A simple unordered tree; in this diagram, the node labeled 7 has two children, labeled 2 and 6, and one parent, labeled 2. The root node, at the top, has no parent.
In computer science, a tree is a widely-used data structure that emulates a hierarchical tree structure with a set of linked nodes.
Mathematically, it is an ordered directed tree, more specifically an arborescence: an acyclic connected graph where each node has zero or more children nodes and at most one parent node. Furthermore, the children of each node have a specific order.

Contents

 [hide

[edit] Terminology

A node is a structure which may contain a value, a condition, or represent a separate data structure (which could be a tree of its own). Each node in a tree has zero or more child nodes, which are below it in the tree (by convention, trees are drawn growing downwards). A node that has a child is called the child's parent node (or ancestor node, or superior). A node has at most one parent.
An internal node (also known as an inner node or branch node[1]) is any node of a tree that has child nodes. Similarly, an external node (also known as an outer node, leaf node, or terminal node) is any node that does not have child nodes.
The topmost node in a tree is called the root node. Being the topmost node, the root node will not have a parent. It is the node at which operations on the tree commonly begin (although some algorithms begin with the leaf nodes and work up ending at the root). All other nodes can be reached from it by following edges or links. (In the formal definition, each such path is also unique). In diagrams, it is typically drawn at the top. In some trees, such as heaps, the root node has special properties. Every node in a tree can be seen as the root node of the subtree rooted at that node. A free tree is a tree that is not rooted.
The height of a node is the length of the longest downward path to a leaf from that node. The height of the root is the height of the tree. The depth of a node is the length of the path to its root (i.e., its root path). This is commonly needed in the manipulation of the various self balancing trees, AVL Trees in particular. Conventionally, the value −1 corresponds to a subtree with no nodes, whereas zero corresponds to a subtree with one node.
A subtree of a tree T is a tree consisting of a node in T and all of its descendants in T. (This is different from the formal definition of subtree used in graph theory.[2]) The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree (in analogy to the term proper subset).

Representations

There are many different ways to represent trees; common representations represent the nodes as dynamically allocated records with pointers to their children, their parents, or both, or as items in an array, with relationships between them determined by their positions in the array (e.g., binary heap).

Trees and graphs

The tree data structure can be generalized to represent directed graphs by removing the constraints that a node may have at most one parent, and that no cycles are allowed. Edges are still abstractly considered as pairs of nodes, however, the terms parent and child are usually replaced by different terminology (for example, source and target). Different implementation strategies exist, for example adjacency lists.
In graph theory, a tree is a connected acyclic graph; unless stated otherwise, trees and graphs are undirected. There is no one-to-one correspondence between such trees and trees as data structure. We can take an arbitrary undirected tree, arbitrarily pick one of its vertices as the root, make all its edges directed by making them point away from the root node - producing an arborescence - and assign an order to all the nodes. The result corresponds to a tree data structure. Picking a different root or different ordering produces a different one.

Traversal methods

Stepping through the items of a tree, by means of the connections between parents and children, is called walking the tree, and the action is a walk of the tree. Often, an operation might be performed when a pointer arrives at a particular node. A walk in which each parent node is traversed before its children is called a pre-order walk; a walk in which the children are traversed before their respective parents are traversed is called a post-order walk; a walk in which a node's left subtree, then the node itself, and then finally its right sub tree are traversed is called an in-order traversal. (This last scenario, referring to exactly two subtrees, a left subtree and a right subtree, assumes specifically a binary tree.) A level-order walk effectively performs a breadth-first search search over the entirety of a tree; nodes are traversed level by level, where the root node is visited first, followed by its direct child nodes and their siblings, followed by its grandchild nodes and their siblings, etc., until all nodes in the tree have been traversed.

Common operations

  • Enumerating all the items
  • Enumerating a section of a tree
  • Searching for an item
  • Adding a new item at a certain position on the tree
  • Deleting an item
  • Pruning: Removing a whole section of a tree
  • Grafting: Adding a whole section to a tree
  • Finding the root for any node

Common uses

See also

Other trees

TREE IN DATA STRUCTURE

4.3.1 Binary Trees

The simplest form of tree is a binary tree. A binary tree consists of
  1. a node (called the root node) and
  2. left and right sub-trees.
    Both the sub-trees are themselves binary trees.
You now have a recursively defined data structure. (It is also possible to define a list recursively: can you see how?)


A binary tree
The nodes at the lowest levels of the tree (the ones with no sub-trees) are called leaves.
In an ordered binary tree,
  1. the keys of all the nodes in the left sub-tree are less than that of the root,
  2. the keys of all the nodes in the right sub-tree are greater than that of the root,
  3. the left and right sub-trees are themselves ordered binary trees.

Data Structure

The data structure for the tree implementation simply adds left and right pointers in place of the next pointer of the linked list implementation. [Load the tree struct.] The AddToCollection method is, naturally, recursive. [ Load the AddToCollection method.]
Similarly, the FindInCollection method is recursive. [ Load the FindInCollection method.]

Analysis

Complete Trees

Before we look at more general cases, let's make the optimistic assumption that we've managed to fill our tree neatly, ie that each leaf is the same 'distance' from the root.

A complete tree
This forms a complete tree, whose height is defined as the number of links from the root to the deepest leaf.
First, we need to work out how many nodes, n, we have in such a tree of height, h.
Now,

n = 1 + 21 + 22 + .... + 2h
From which we have,
n = 2h+1 - 1
and
h = floor( log2n )
Examination of the Find method shows that in the worst case, h+1 or ceiling( log2n ) comparisons are needed to find an item. This is the same as for binary search.
However, Add also requires ceiling( log2n ) comparisons to determine where to add an item. Actually adding the item takes a constant number of operations, so we say that a binary tree requires O(logn) operations for both adding and finding an item - a considerable improvement over binary search for a dynamic structure which often requires addition of new items.
Deletion is also an O(logn) operation.

General binary trees

However, in general addition of items to an ordered tree will not produce a complete tree. The worst case occurs if we add an ordered list of items to a tree. What will happen? Think before you click here!
This problem is readily overcome: we use a structure known as a heap. However, before looking at heaps, we should formalise our ideas about the complexity of algorithms by defining carefully what O(f(n)) means.

Key terms

Root Node
Node at the "top" of a tree - the one from which all operations on the tree commence. The root node may not exist (a NULL tree with no nodes in it) or have 0, 1 or 2 children in a binary tree.
Leaf Node
Node at the "bottom" of a tree - farthest from the root. Leaf nodes have no children.
Complete Tree
Tree in which each leaf is at the same distance from the root. A more precise and formal definition of a complete tree is set out later.
Height
Number of nodes which must be traversed from the root to reach a leaf of a tree.

BYTE ARRAY TO TEXT FILE

The following VB.NET program shows how to write the content of a Byte Array into a Text file.
Byte is an immutable value type that represents unsigned integers with values that range from 0 to 255 . Here we open a FileStream class instance and using the method Write() . Write() method writes a block of bytes to the current stream using data read from buffer.
  oFileStream.Write(byteData, 0, byteData.Length)

Public Class Form1

 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

  Dim str As String = "http://vb.net-informations.com"
  Dim encod As New System.Text.UTF8Encoding
  Dim byteData() As Byte = encod.GetBytes(str)

  Dim oFileStream As System.IO.FileStream
  oFileStream = New System.IO.FileStream("c:\bytes.txt", System.IO.FileMode.Create)
  oFileStream.Write(byteData, 0, byteData.Length)
  oFileStream.Close()

 End Sub
End Class

STRING ARRAY INTO TEXT FILE IN VB.NET

An array is a data structure that contains multiple variables of the same type. Arrays helps us create shorter and simpler code in many situations. Arrays in VB.NET inherit from the Array class in the System namespace.
  Dim months(11) As String
An array allows you to refer to these related values by the same name and to use a number, called an index or subscript, to tell them apart. The default number of array elements is set to zero and the reference element is set to null.
The elements of an array can be of any type, including an array type. The following VB.NET source code shows how to write the array content into a text file.

Public Class Form1

 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

  Dim months(11) As String
  months(0) = "Jan"
  months(1) = "Feb"
  months(2) = "Mar"
  months(3) = "Apr"
  months(4) = "May"
  months(5) = "Jun"
  months(6) = "Jul"
  months(7) = "Aug"
  months(8) = "Sep"
  months(9) = "Oct"
  months(10) = "Nov"
  months(11) = "Dec"
  System.IO.File.WriteAllLines("c:\file.txt", months)

 End Sub
End Class

HOW TO USE NAME VALUE COLLECTION IN VB.NET

NameValueCollection is used to store data like Name, Value format. It is very similar to Vb.Net HashTable, HashTable also stores data in Key , value format . NameValueCollection can hold more than one value for a corresponding Key.
Adding new pairs
Add(ByVal name As String, ByVal value As String)
Add("High","80")
Get the value of corresponding Key
GetValues(ByVal name As String) As String()
String values() = GetValues("High")

Imports System.Collections.Specialized
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Button1.Click

        Dim markStatus As New NameValueCollection
        Dim key As String
        Dim values() As String

        markStatus.Add("Very High", "80")
        markStatus.Add("High", "60")
        markStatus.Add("medium", "50")
        markStatus.Add("Pass", "40")

        For Each key In markStatus.Keys
            values = markStatus.GetValues(key)
            For Each value As String In values
                MsgBox(key & " - " & value)
            Next value
        Next key

    End Sub
End Class

HOW TO USE QUEUE IN VB.NET

The Queue is another adtastructure from VB.NET Collections . Queue works like First In First Out method and the item added first in the Queue is first get out from Queue. We can Enqueue (add) items in Queue and we can Dequeue (remove from Queue ) or we can Peek (that is get the reference of first item added in Queue ) the item from Queue.
The commonly using functions are follows :
Enqueue : Add an Item in Queue
Syntax : Stack.Enqueue(Object)
Object : The item to add in Queue
Dequeue : Remove the oldest item from Queue (we dont get the item later)
Syntax : Stack.Dequeue()
Returns : Remove the oldest item and return.
Peek : Get the reference of the oldest item (it is not removed permenantly)
Syntax : Stack.Peek()
returns : Get the reference of the oldest item in the Queue
The following VB.NET Source code shows some of commonly used functions :

Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object,_
 ByVal e As System.EventArgs) Handles Button1.Click
        Dim queueList As New Queue
        queueList.Enqueue("Sun")
        queueList.Enqueue("Mon")
        queueList.Enqueue("Tue")
        queueList.Enqueue("Wed")
        queueList.Enqueue("Thu")
        queueList.Enqueue("fri")
        queueList.Enqueue("Sat")
        MsgBox(queueList.Dequeue())
        MsgBox(queueList.Peek())
        If queueList.Contains("Sun") Then
            MsgBox("Contains Sun ")
        Else
            MsgBox("Not Contains Sun ")
        End If
    End Sub
End Class

When you execute the program it add seven items in the Queue. Then it Dequeue (remove) the oldest item from queue. Next it Peek() the oldest item from Queue (shows only , not remove ). Next it check the Item "Sun" contains in the Queue.

HOW TO USE STACK IN VB.NET

Stack is one of another easy to use VB.NET Collections . Stack follows the push-pop operations, that is we can Push Items into Stack and Pop it later also it follows the Last In First Out (LIFO) system. That is we can push the items into a stack and get it in reverse order. Stack returns the last item first.
Commonly used methods :
Push : Add (Push) an item in the stack datastructure
Syntax : Stack.Push(Object)
Object : The item to be inserted.
Pop : Pop return the item last Item to insert in stack
Syntax : Stack.Pop()
Return : The last object in the Stack
Contains : Check the object contains in the stack
Syntax : Stack.Contains(Object)
Object : The specified Object to be seach
The following VB.NET Source code shows some of commonly used functions :

Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, 
 ByVal e As System.EventArgs) Handles Button1.Click
        Dim stackTable As New Stack
        stackTable.Push("Sun")
        stackTable.Push("Mon")
        stackTable.Push("Tue")
        stackTable.Push("Wed")
        stackTable.Push("Thu")
        stackTable.Push("Fri")
        stackTable.Push("Sat")
        If stackTable.Contains("Wed") Then
            MsgBox(stackTable.Pop())
        Else
            MsgBox("not exist")
        End If
    End Sub
End Class

When you execute this program add seven items in the stack . Then its checks the item "Wed" exist in the Stack. If the item exist in the Stack , it Pop the last item from Stack , else it shows the msg "Not Exist"

HOW TO USE HASHTABLE IN VB.NET

HashTable stores a Key Value pair type collection of data . We can retrive items from hashTable to provide the key . Both key and value are Objects.
The common functions using in Hashtable are :
Add : To add a pair of value in HashTable
Syntax : HashTable.Add(Key,Value)
Key : The Key value
Value : The value of corrosponding key
ContainsKey : Check if a specified key exist or not
Synatx : HashTable.ContainsKey(key)
Key : The Key value for search in HahTable
ContainsValue : Check the specified Value exist in HashTable
Synatx : HashTable.ContainsValue(Value)
Value : Search the specified Value in HashTable
Remove : Remove the specified Key and corrosponding Value
Syntax : HashTable.Remove(Key)
Key : The argument key of deleting pairs
The following source code shows all important operations in a HashTable

Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, 
 ByVal e As System.EventArgs) Handles Button1.Click
        Dim weeks As New Hashtable
        Dim day As DictionaryEntry
        weeks.Add("1", "Sun")
        weeks.Add("2", "Mon")
        weeks.Add("3", "Tue")
        weeks.Add("4", "Wed")
        weeks.Add("5", "Thu")
        weeks.Add("6", "Fri")
        weeks.Add("7", "Sat")
        'Display a single Item
        MsgBox(weeks.Item("5"))
        'Search an Item
        If weeks.ContainsValue("Tue") Then
            MsgBox("Find")
        Else
            MsgBox("Not find")
        End If
        'remove an Item
        weeks.Remove("3")
        'Display all key value pairs
        For Each day In weeks
            MsgBox(day.Key  "  --  "  day.Value)
        Next
    End Sub
End Class

When you execute this program it add seven weekdays in the hashtable and display the item 5. Then it check the item "Tue" is existing or not . Next it remove the third item from HashTable. Finaly it displays all item exist in the HashTable.

DYNAMIC ARRAY IN VB.NET

Dynamic Arrays can resize the capability of the Array at runtime .when you are in a situation that you do not know exactly the number of elements to store in array while you making the program. In that situations we are using Dynamic Array .
Initial declaration
Dim scores() As Integer
Resizing
ReDim scores(1)
If you want to keep the existing items in the Array , you can use the keyword Preserve .
ReDim Preserve scores(2)
In this case the Array dynamically allocate one more String value and keep the existing values.

Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Button1.Click
        Dim i As Integer
        Dim scores() As Integer

        ReDim scores(1)
        scores(0) = 100
        scores(1) = 200

        For i = 0 To scores.Length - 1
            MsgBox(scores(i))
        Next

        ReDim Preserve scores(2)

        scores(2) = 300

        For i = 0 To scores.Length - 1
            MsgBox(scores(i))
        Next
    End Sub
End Class

When you execute this source code , the first loop shows first two values stored in the Array. Next loop shows the whole value stored in the Array.

IMPORTANT FUNCTION IN ARRAY LIST


Add : Add an Item in an ArrayList
Insert : Insert an Item in a specified position in an ArrayList
Remove : Remove an Item from ArrayList
RemoveAt: remeove an item from a specified position
Sort : Sort Items in an ArrayList
How to add an Item in an ArrayList ?
Syntax : ArrayList.add(Item)
Item : The Item to be add the ArrayList
Dim ItemList As New ArrayList()
ItemList.Add("Item4")
How to Insert an Item in an ArrayList ?
Syntax : ArrayList.insert(index,item)
index : The position of the item in an ArrayList
Item : The Item to be add the ArrayList
ItemList.Insert(3, "item6")
How to remove an item from arrayList ?
Syntax : ArrayList.Remove(item)
Item : The Item to be add the ArrayList
ItemList.Remove("item2")
How to remove an item in a specified position from an ArrayList ?
Syntax : ArrayList.RemoveAt(index)
index : the position of an item to remove from an ArrayList
ItemList.RemoveAt(2)
How to sort ArrayList ?
Syntax : ArrayListSort()
The following VB.NET source code shows some function in ArrayList

Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, 
 ByVal e As System.EventArgs) Handles Button1.Click
        Dim i As Integer
        Dim ItemList As New ArrayList()
        ItemList.Add("Item4")
        ItemList.Add("Item5")
        ItemList.Add("Item2")
        ItemList.Add("Item1")
        ItemList.Add("Item3")
        MsgBox("Shows Added Items")
        For i = 0 To ItemList.Count - 1
            MsgBox(ItemList.Item(i))
        Next
        'insert an item
        ItemList.Insert(3, "Item6")
        'sort itemms in an arraylist
        ItemList.Sort()
        'remove an item
        ItemList.Remove("Item1")
        'remove item from a specified index
        ItemList.RemoveAt(3)
        MsgBox("Shows final Items the ArrayList")
        For i = 0 To ItemList.Count - 1
            MsgBox(ItemList.Item(i))
        Next
    End Sub
End Class

When you execute this program , at first add five items in the arraylist and displays. Then again one more item inserted in the third position , and then sort all items. Next it remove the item1 and also remove the item in the third position . Finally it shows the existing items.

ARRAY IN VB.NET

Arrays are using for store similar data types grouping as a single unit. We can access Array elements by its numeric index.
Dim week(6) As String
The above Vb.Net statements means that , an Array named as week declared as a String type and it can have the capability of seven String type values.
week(0) = "Sunday"
week(1) = "Monday"
In the above statement , we initialize the values to the String Array. week(0) = "Sunday" means , we initialize the first value of Array as "Sunday" ,
Dim weekName as String = week(1)
We can access the Arrays elements by providing its numerical index, the above statement we access the second value from the week Array.
In the following program , we declare an Array "week" capability of seven String values and assigns the seven values as days in a week . Next step is to retrieve the elements of the Array using a For loop. For finding the end of an Array we used the Length function of Array Object.

Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Button1.Click
        Dim i As Integer
        Dim week(6) As String
        week(0) = "Sunday"
        week(1) = "Monday"
        week(2) = "Tuesday"
        week(3) = "Wednesday"
        week(4) = "Thursday"
        week(5) = "Friday"
        week(6) = "Saturday"

        For i = 0 To week.Length - 1
            MsgBox(week(i))
        Next

    End Sub
End Class
ArrayList is one of the most flixible data structure from VB.NET Collections. ArrayList contains a simple list of values and very easily we can add , insert , delete , view etc.. to do with ArrayList. It is very flexible becuse we can add without any size information , that is it grow dynamically and also shrink .

Wednesday, 28 March 2012

MULTIDIMENSIONAL ARRAY IN C++


For each dimension of your array, you will need another for loop. For instance, if I have a 2-D array:

int myMatrix[ROWS][COLS];

Then I would fill it by saying something like:

1
2
3
4
5
for (int i = 0; i < ROWS; i++) {
   for (int j = 0; i < COLS; j++) {
      myMatrix[i][j] = i + j; // or whatever.
   }
}

Well I guess the next dimension would be a 3d array. So:
int 3darray[5][5][5];
This would give you an array that is 5 ints tall, 5ints wide, 5 ints thick.
To add a values to all the parts you would need:
1
2
3
4
5
6
7
8
9
10
for(int i = 0;i < 5; i++)
{
       for(int u = 0; u < 5; u++)
       {
                for (int p = 0;p < 5; p++
                {
                           3darray[i][u][p] = (i + u + p);
                }
       } 
}


Displaying would be more complicated - depending on the way you want to display, I could think of a way but it wouldn't be very good.

I don't know about more then 3d arrays though.


And here's four-d arrays, for good measure.

1
2
3
4
5
6
7
8
9
10
11
12
13

void main(){
   int four_d_array[4][15][23][8];
   for(int i = 0; i < 4; i++){
      for(int j = 0; j < 15; j++){
         for(int k = 0; k < 23; k++){
            for(int l = 0; l < 8; l++){
               four_d_array[i][j][k][l] = whateverValue();
            }
         }
      }
   }
}


for five-d and beyond, You should be able to look at what we've given you and see the pattern emerging. Just add some more square brackets and for loops.

ARRAY IN PHP


Arrays can be used in many ways to store and organize data quickly and efficiently. It is one of the more useful data types available to any programming language.
Arrays can most easily be described as an ordered list of elements. You can access the individual elements by referring to their index position within the array. The position is either specified numerically or by name. An array with a numeric index is commonly called an indexed array while one that has named positions is called an associative array. In PHP, all arrays are associative, but you can still use a numeric index to access them.
An Example of an indexed Array:
<?php
$seven = 7;
$arrayname = array( "this is an element", 5, $seven );

echo $arrayname[0];   //prints: this is an element 
echo $arrayname[1];   //prints: 5 
echo $arrayname[2];   //prints: 7
?>

As you can see, elements in an array can be any type of data (string, integer, double) and can also be other variables. An individual array element can be of any type, including another array.If you want to find out if a variable contains an array you can use the is_array() function. Notice that Indexed arrays start at position zero, not at position one, so your first array element has an index of 0, and the highest position in the array is one less than the number of elements in the array.
Associative Arrays
Associative arrays are arrays that use named keys that you assign to them. Have a look at the following example:
<?php
$first_array = array("key1" => "the first element", "key2" => "the second element");

$second_array = array(
    "key3" => "this is the first element of the second array",
    "key4" => "this is the second element of the second array",
);
echo $first_array['key1'];    //prints "the first element." 
echo $second_array['key3'];   //prints "the first element of the second array" 
echo $first_array['key2'];    //prints "the second element" 
echo $second_array['key4'];   //prints "this is the second element of the second array" 
?>

Right, now you know how to define an associative array, but you probably don't see yet how useful are they. Well think of this, say you have a flower-shop. You have 3 different flowers, and each flower has a different price. Let's make this example in php.
<?php
//We initialize the array using the array() function.
//Note that for readability one can spread the argument over several lines.

$flower_shop = array (
     "rose" => "5.00",
     "daisy" => "4.00",
     "orchid" => "2.00"
);

echo "rose costs $flower_shop['rose'], daisy costs $flower_shop['daisy'], and orchild costs $flower_shop['orchild'].";
?>

Because the indices in this associative array are not numbers, we cannot use a simple counter in a for loop to work with the array. We can use the foreach loop. In the following example we use the foreach loop to iterate through our flowers_shop array, and read them into a table. Note carefully the syntax.
<?php
//We initialize the array using the array() function.
//Note that for readability one can spread the argument over several lines.

$flower_shop = array (
     "rose" => "5.00",
     "daisy" => "4.00",
     "orchid" => "2.00",
);
//let's print out the headers to our table
echo "<table border='1' cellpadding='5'>";
echo"<tr><th>Flower</th><th>Price</th></tr>";
//Now we start the foreach loop using the variable $flower to hold our key
//and $price to hold our cost.

foreach($flower_shop as $Flower=>$Price)
{
  echo "<tr><td>$Flower </td><td>$Price</td></tr> "; //print the values into a table cell for each iteration
}
//finally close the table
echo "</table>";
?> 

Multidimensional Arrays
In preceding example you've learned how to use arrays. But what if you want to give more information on each flower? You now have the cost, but what if you wanted to add the number of flowers you get for that price, and the colour of the flower? One of the ways to do it is using multidimensional arrays.
A multidimensional array is an array that contains at least one other array as the value of one of the indexes. Example below shows how to use multidimensional array:
<?php
//Initialize the array using the array() function.
$flower_shop = array(
"rose" => array( "5.00", "7 items", "red" ),
"daisy" => array( "4.00", "3 items", "blue" ),
"orchid" => array( "2.00", "1 item", "white" ),
);

//print "rose costs 5.00, and you get 7 items."
echo "rose costs ".$flower_shop['rose'][0].", and you get ".$flower_shop['rose'][1].".";
//print "daisy costs 4.00, and you get 3 items." 
echo "daisy costs ".$flower_shop['daisy'][0].", and you get ".$flower_shop['daisy'][1].".";
//print "orchild costs 2.00, and you get 1 item.
echo "orchid costs ".$flower_shop['orchid'][0].", and you get ".$flower_shop['orchild'][1].".";
?>


ARRAY DECLARATION IN PHP


I want to create an array, but its size depends on how many records a file has. So i want to READ a file and after counting how many records it has i want to initialize that array. What's the best way to do this?
Use an array based on a pointer, load the array from the file then allocate the right size of the array to the pointer. That is :

PHP Code:
D MyArray     DS       

        Dim(9999Based(p_My Array)

 


     p_MyArray 
= Alloc(Size(Myarray) * 9999);  
// Load the array from the file
    
     
Do U EOF();
      
Read File ...
       ...                                       
// Count # of entries
     
      
MyArray_Cnt += 1;                            
// Loop

     

     
End do;                                     
// Reallocate the size of the array
    
     
p_MyArray = %Realloc(p_MyArray : %size(MyArray) * MyArray_Cnt);
     ...                                              
// End of Program
  
    
Dealloc p_MyArray;
   
InLR = *On;  

1/ Example WITHOUT qualified

PHP Code:
D Arr             ds                     Based(p_Arr)                D  ArrEntry                     10a      Dim(999)                   D   ArrFld1                      3a      OverlayArrEntry : *Next )D   ArrFld2                      7a      OverlayArrEntry : *Next )
...
D ArrCnt          s             10i 0   inz        
                                                   
 
/free                                             
   p_Arr 
= %Alloc(%Size(ArrEntry) * 9999);
// Load the array from the file               
  
               
   
Do U EOF();                                   
     
Read File ...
     If 
EOF();
        
Leave;
     Else                               
// Count # of entries         
                      
       
ArrCnt = +1;                        
// Load the array
     
       
ArrFld1(ArrCnt) = Fld1;
       
ArrFld2(ArrCnt) = Fld2;                            
       ...                                        
      End If;                        
   
End do;     
                     

  
                      
   
p_Arr = %Realloc(p_Arr : %size(ArrEntry) * ArrCnt);
// Reallocate the size of the array   
   ...                                               
// End of Program                                
 

                                                     Dealloc p_Arr
  *
inlr = *on;  
2/ Example WITH qualified 
PHP Code:
D Arr_Template    ds                    Qualified        
D  Fld1                          
...                         D  Fld2                          ...        
...                                                         
D Arr             ds                    Based(p_Arr)        D                                       Dim(9999)           D                                       Likeds(Arr_Template)
                                                    
D ArrCnt          s             10i 0   inz      
                                                 
 
/free                                           
  p_Arr 
= %Alloc(%Size(Arr) * 9999);             
  
Do U EOF();                                   
    
Read File ...
    If 
EOF();
       
Leave;
    Else                  
// Count # of entries
    

       ArrCnt += 1;               // Load the array   
                  
      
Arr(ArrCnt).Fld1 Fld1;            
      
Arr(ArrCnt).Fld2 Fld2
      ... 
    End If;    
  
End Do;   
                                  
 

   
p_Arr = %Realloc(p_Arr : %size(Arr) * ArrCnt);
// Reallocate the size of the array  
   ...                                         
// End of Program  
                                                   
  
                             
  
Dealloc p_Arr;
  *
inlr = *on;