Showing posts with label Computer Science. Show all posts
Showing posts with label Computer Science. Show all posts

Tuesday, April 24, 2012

Programming Pointers Definition C/C++ (Learn what are pointers? How defined and used using sample example pointer code in C++)

Pointers Definition: A pointer is a data type recognized by C++ and C, but not by Java. A variable of data type pointer contains an address of some other data element stored in data memory (RAM), e.g., the address of the value stored in some other variable. The pointer variable itself is also stored at some address in data memory.


Diagram to learn programming pointers: 

Pointers in different computer programming languages: 


Pointers in C++/C: A pointer variable contains the address of other data elements. The values stored at the address can be changed, copied, etc., using only the address. Advantage of pointers in C/C++ is that programmers can directly access memory locations of the variables assigned while programming application programs either for embedded systems or operating system programs. Pointers should be used very carefully while programming your application in C/C++ since mirror error in pointer can terminate your whole application.

Pointers in Java: Java programmer does not have access to pointers. Pointers are used implicitly by the Java compiler/interpreter. Actually used more frequently by the Java compiler/interpreter than by the either the C++ or C compiler. Explicit manipulation of addresses/pointers by the Java programmer is forbidden. 

Now lets simply understand how pointers are defined and used in C++ using simple example for better understanding pointers for practical purposes:
STEP 1: float A;
1. First of all, the data type of variable A is float.
2. The variable name A is for human/programmer use only. The compiler converts the variable name into an address/pointer that is used by the compiled code to access the value stored at that address.
3. The variable name is converted by the compiler into an address in data memory.
4. The address that is synonymous with to the variable name A contains the value that has been assigned to that variable.
5. Normally the code that manipulates the address that corresponds to the variable A is hidden from the programmer. 6. If desired by the programmer that address can be accessed, again it is only possible in C and C++ but not in JAVA. Variable address can be accessed using:
a. A reference to the variable A, as in &A.
b. A pointer to A (explained below).

STEP 2: float* PtrToA;
1. The notation float* defines the data type of pointer-to-float.
2. The variable name which follows is, then, the name of a variable which holds a value which is the address of some floating point value.
3. Alternate notation: float *PtrToA;

STEP 3: A = 3.1415;
1. Standard assignment statement.
2. The constant value 3.1415 is stored at the address in RAM that corresponds to the variable A.


STEP 4: PtrToA = &A;
1. A slightly different assignment statement.
2. The notation &A designates the address of the variable A.
3. Therefore: PtrToA = &A; causes the address of the variable A to be loaded into the address in RAM that corresponds to the pointer variable PtrToA.

In the end, lets program in C++ what we have explained above about pointers usage to see the actual results in programming how pointers are defined inside computer memory and how pointers are used inside the computer programming.

Samle example Code:
#include <iostream>
using namespace std; 
void main() 
{
float A; // declaration of a floating point variable 
// allocates four bytes of RAM and attaches // the memory to the program. 
          float* PtrToA; // declaration of a variable that will hold the
// address of a floating point number. 
          A = 3.1415; // Assign a value to the floating point variable, i.e., store a value at the address
// in RAM that is synonymous with the  variable name. 
          PtrToA = &A; // The value assigned to the pointer variable is the address of the floating point variable
          cout << endl << "The value of A is " << A << " while the address of A is " << PtrToA << endl << "                and the value stored at the address " << PtrToA << " is " << *PtrToA << endl;
         *PtrToA = 89.526;
          cout << endl << "The value of A is " << A << " while the address of A is " << PtrToA << endl << " and the value stored at the address " << PtrToA << " is " << *PtrToA << endl;
} 


The output of the above sample code to understand pointers would be:


The value of A is 3.1415 while the address of A is 0012FF7C and the value stored at the address 0012FF7C is 3.1415 
The value of A is 89.526 while the address of A is 0012FF7C and the value stored at the address 0012FF7C is 89.526

Friday, March 23, 2012

Binary Search Integer Array C Code Algorithm (Simplified code to learn)

What are search algorithms?
Given a database, the first thing you would want to do is probably search through its entries to see if a particular entry exists. This is why search algorithms are one of the most basic and widely used algorithms, and one of the first algorithms taught in any class.

Binary Search drastically reduces the worst-case time required to search through a database. However, it can be used only when the database is sorted i.e. when the entries are arranged either in ascending or descending order.

Following binary search algorithm(in C language) takes user inputs to load the specified data structure array in this case and then sorts it using insertion sort approach, you could also use other sorting methods. Then it print the sorted array of integers. It asks for user to input what entry you want to search, it then prints if particular entry if found or not.
Yes, we can add even more functionality to this code, but I made it simple enough so that other people can understand it and go further to add more towards it.
(Please leave your feedback) Code is:

#include<stdio.h>
//this function sorts the array using insertion sort
int sort(int array[],int n)
{
   int i,j,temp;
   for(i=1;i<n;i++)
   {
          temp=array[i];
          j=i-1;
          while(temp<array[j] && j>=0)
          {
                  array[j+1]=array[j];
                  j=j-1;
          }
          array[j+1]=temp;
   }
}

//this function gets data from user to load into data array
int get_data(int array[],int n)
{
   int i;
   printf("Enter data for array :\n");
   for(i=0;i<n;i++)
   {
          scanf("%d",&array[i]);
   }
}

//this function prints the sorted array
int out_data(int array[],int n)
{
   int i;
   printf("Array after sorting......\n\n");
   for(i=0;i<n;i++)
   {
          printf("%d ",array[i]);
   }
}

//this function searches for particular number entry in the data array
int binary_search(int a[], int low, int high, int target)
{
    if (high < low)
        return -1;
    int middle = (low + high)/2;
    if (target < a[middle])
        return bi_search(a, low, middle-1, target);
    else if (target > a[middle])
        return bi_search(a, middle+1, high, target);
    else if (target == a[middle])
        return middle;
}

//its main code which loads user inputs to functions and perform binary search after sorting the data array
main()
{
//make sure array size is hard coded in this program (30) therefore enter number of array elements less than 30
   int n,array[30],k,b;
   printf("\n\nEnter number of elements you want to enter to data(less than 30 since array size is 30):");
   scanf("%d",&n);
   get_data(array,n);
   sort(array,n);
   out_data(array,n);
   printf("\n\nEnter value to search :");
   scanf("%d",&b);
   k=binary_search(array,0,n-1,b);
   if(k==-1)
   printf("-->%d is not found......!\n",b);
   else
   printf("-->%d is found......!\n\n",b);
}
}




Monday, February 27, 2012

What are the three types of abstract system model that are recommended by the MDA method?

What are the three types of abstract system model that are recommended by the MDA method?
Answer: 1. A computation independent model (CIM) that models the important domain abstractions used in the system. CIMs are sometimes called domain models. You may develop several different CIMs, reflecting different views of the system.
2. A platform independent model (PIM) that models the operation of the system without reference to its implementation. The PIM is usually described using UML models that show the static system structure and how it responds to external and internal events.
3. Platform specific models (PSM) which are transformations of the platform independent model with a separate PSM for each application platform.

What are the claimed benefits of model-driven engineering?

What are the claimed benefits of model-driven engineering?
Answer: Model-based engineering allows engineers to think about systems at a high level of abstraction, without concern for the details of their implementation. This reduces the likelihood of errors, speeds up the design and implementation process, and allows for the creation of reusable, platform-independent application models. By using powerful tools, system implementations can be generated for different platforms from the same model. Therefore, to adapt the system to some new platform technology, it is only necessary to write a translator for that platform. When this is available, all platform-independent models can be rapidly rehosted on the new platform.

What is the basic assumption that underlies event-driven modeling?

What is the basic assumption that underlies event-driven modeling?
Answer: Event-driven modeling is based on the assumption that a system has a finite number of states and that events (stimuli) may cause a transition from one state to another. For example, a system controlling a valve may move from a state ‘Valve open’ to a state ‘Valve closed’ when an operator command (the stimulus) is received. Event-driven modeling shows how a system responds to external and internal events.

How is generalization used to simplify the models of a system with many similar objects?

How is generalization used to simplify the models of a system with many similar objects?
Answer: Generalization is an everyday technique that we use to manage complexity. It is often useful to examine the classes in a system to see if there is scope for generalization. This means that common information will be maintained in one place only. This is good design practice as it means that, if changes are proposed, then you do not have to look at all classes in the system to see if they are affected by the change. In object-oriented languages, such as Java, generalization is implemented using the class inheritance mechanisms built into the language. In a generalization, the attributes and operations associated with higher-level classes are also associated with the lower-level classes.

What is illustrated in a UML sequence diagram?

What is illustrated in a UML sequence diagram?
Answer: Sequence diagrams in the UML are primarily used to model the interactions between the actors and the objects in a system and the interactions between the objects themselves. A sequence diagram shows the sequence of interactions that take place during a particular use case or use case instance. The UML has a rich syntax for sequence diagrams, which allows many different kinds of interaction to be modeled. The objects and actors involved are listed along the top of the diagram, with a dotted line drawn vertically from these. Interactions between objects are indicated by annotated arrows.

What are the principal components of a textual use-case description?

What are the principal components of a textual use-case description?
Answer: Name: The name of the use case.
Brief Description: A brief description of the role and purpose of the use case.
Flow of events: A textual description of what the system does in regard to the use case (not how specific problems are solved by the system). The description is understandable by the customer.
Special requirements: A textual description that collects all requirements, such as non-functional requirements, on the use case, that are not considered in the use-case model, but that need to be taken care of during design or implementation.
Preconditions: A textual description that defines a constraint on the system when the use case may start.
Post conditions: A textual description that defines a constraint on the system when the use cases have terminated.
Extension points: A list of locations within the flow of events of the use case at which additional behavior can be inserted using the extend-relationship.

How are activity diagrams used in describing the context of use of a system?

How are activity diagrams used in describing the context of use of a system?
Answer: Activity diagrams are intended to show the activities that make up a system process and the flow of control from one activity to another. The start of a process is indicated by a filled circle and the end by a filled circle inside another circle. In a UML activity diagram, arrows represent the flow of work from one activity to another. A solid bar is used to indicate activity coordination.

What is described in a context model?

What is described in a context model?
Answer: Context models show what lays outside the system boundaries by illustrating the operational context of a system. This involves working with system stakeholders to decide what functionality should be included in the system and what is provided by the system’s environment. Social and organisational concerns may affect the decision on where to position system boundaries. Context models normally show that the environment includes several other automated systems. However, they do not show the types of relationships between the systems in the environment and the system that is being specified. Architectural models show the system and its relationship with other systems.

What UML diagram types may be used to represent the essential features of a system?

What UML diagram types may be used to represent the essential features of a system?
Answer: (a) Activity diagrams, which show the activities involved in a process or in data processing.
(b) Use case diagrams, which show the interactions between a system and its environment.
(c) Sequence diagrams, which show interactions between actors and the system and between system components.
(d) Class diagrams, which show the object classes in the system and the associations between these classes.
(e) State diagrams, which show how the system reacts to internal and external events.

What perspectives may be used for system modeling?

What perspectives may be used for system modeling?
Ans: (a) An external perspective, where you model the context or environment of the system.
(b) An interaction perspective where you model the interactions between a system and its environment or between the components of a system.
(c) A structural perspective, where you model the organization of a system or the structure of the data that is processed by the system.
(d) A behavioral perspective, where you model the dynamic behavior of the system and how it responds to events.

Tuesday, November 9, 2010

Ackermann Function A(n,x,y) Examples

Ackermann  Function is an extreme example of Recurrence Relations and
Recursive Functions.
The Ackermann function was discovered and studied by Wilhelm Ackermann (1896–1962) in 1928. Ackermann worked as a high-school teacher from 1927 to 1961 but was also a student of the great mathematician David Hilbert in Göttingen and, from 1953, served as an honorary professor in the university there. Together with Hilbert he published the first modern textbook on mathematical logic.


The Ackermann function can be defined as follows:
     A(0, n) = n + 1 for n = 0 
     A(m, 0) = A(m - 1, 1) for m = 1 
     A(m, n) = A(m - 1, A(m, n - 1)) for m, n = 1


Two positive integers, m and n, are the input and A(m, n) is the output in the form of another positive integer. The function can be programmed easily in just a few lines of code. The problem isn't the complexity of the function but the awesome rate at which it grows. For example, the innocuous-looking A(4,2) already has 19,729 digits!


Definition of Ackermann's Function A(n,x,y):

  • A(0,x,y) = x + 1
  • A(n,x,0) = x     if     n = 1
  • A(n,x,0) = 0     if     n = 2
  • A(n,x,0) = 1     if     n = 3
  • A(n,x,0) = 2     if     n >=4
  • A(n,x,y) = A(n-1,A(n,x,y-1),x)     if     n > 1 and y > 0


Recursive C++ function that calculates values for Ackermann's Function:
int Ackermann(int N, int X, int Y)
{
int K, L;
if (N == 0) return X + 1;
else if ((N > 0) && (Y == 0))
{
if (N == 1) return X;
else if (N == 2) return 0;
else if (N == 3) return 1;
else if (N >= 4) return 2;
else { cout << "Error 1: " << N << ", " << X
<< ", " << Y;
exit(1);
}
}
else if ((N > 0) && (Y > 0))
{ K = Ackermann(N, X, Y - 1);
return Ackermann(N - 1, K, X);
}
else {
cout << "Error 2: " << N << ", " << X << ", " << Y;
exit(1);
}
}

Recursion function and Fibonacci series

Recursive Function: A recursive function is a function that calls itself, either directly, or indirectly. Recursion is an important topic in upper-level computer science courses.
  • A recursive function invokes itself.
  • A recurrence relation is a relation that is specified using itself.
  • Anything that can be done recursively can be done iteratively and vice versa.
  • If there were a data processing Inquisition programmers would probably be burned at the stake based on a belief or disbelief in recursion.
Advantages:
  1. Code to implement an algorithm can be very succinct.
  2. If an algorithm is specified recursively, in the form of a recurrence
    relation, it is the easiest way to code it.

Disadvantages:
  1. Expensive in CPU time and memory.
Recurrence Relation Example:
n! = n * (n-1) * (n-2).....1 = n * (n-1)!
4! = 4 * 3 * 2 * 1 = 24

Recursive Function Example:
A translation of the recurrence relation into C++.
int RcrsFact(int Num)
{
if (Num == 0) return 1;
else return (Num * RcrsFact(Num - 1));
}

Example using recursion: Fibonacci Numbers

Fibonacci
a. Real Name: Leonardo of Pisa
b. Fibona cci sh ort for: Filius Bon Acci, or good son of Acci.
c. Well traveled merchant with extensive acquaintance with Mideast
d. Familiar with Arabian mathematics.
e. Introduced European world to Arabic notations for numerals (as
opposed to Roman numerals) in his book Liber Abaci.


Fibonacci Sequence: Fibon(n) = Fibon(n-1) + Fibon(n-2)
a. Number of leaves on certain plants (assuming that no leaves fall
off) is a Fibonacci number.
b. Fibonacci numbers appear in odd places in series or solutions to
equations.
c. Doubly recursive.

Recursive Logic:
int RcrsFibon(int Num)
{
if (Num == 0) return 0;
else if (Num == 1) return 1;
else if (Num == 2) return 1;
else return (RcrsFibon(Num - 1) + RcrsFibon(Num - 2));
}