Fibonacci Number Series:

 

Sunflowers have fibonacci pattern in them

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ……

F( n ) = F( n-1 )  +  F( n-2 )

Fibonacci numbers are a very useful and interesting phenomena occurring in nature and has been largely studied by mathematicians. It is an important concept in maths and computer science as well. Everyone would have come across them during their coursework or interviews. Assuming that you know the basics, I will straightaway give two different approaches of writing C++ code for fibaonacci series and you will be surprised how simple yet different they are.

By definition, the first two numbers of a Fibonacci series are 0 and 1 and each subsequent number is the sum of the previous two. The seed values are F( 0 ) = 0 and F( 1 ) = 1.

int fibonacci(int n)

{

switch(n)

{

case 0:

return 0;

case 1:

return 1;

default:

return (fibonacci(n-1) + fibonacci(n-2)); };

}

 

void main()

{

int n;

cout<<”Enter the number “;

cin>>n;

cout<<”\n result = “<< fibonacci(n);

}

Time complexity : Exponential ( 2n )

The runtime can be calculated recursively

t(1)=1
t(2)=1
t(n)=t(n-1)+t(n-2)+1 , where +1 is irrelevant for large n;

 

To improve recursion we can cache already calculated results, thus bringing the time complexity to linear( n) , like the iterative approach, like dod table lookups.

 

Better approach?  Use iteration instead of recursion.

int fibonacci(int n)

{

int x=0, y=1, res=0;

for(int i=2; i<n ;i++)

{

res = x+y;

x=y;

y=res;

}

return res;

}

 

void main()

{

int n;

cout<<”Enter the number “;

int res =   cout<<”\n final result = “<< fibonacci(n);

}

Time complexity : linear ( n )

Wikipedia gives a very interesting description of fibonacci numbers.

http://en.wikipedia.org/wiki/Fibonacci_number

Below are a couple of good discussion threads on them

http://www.daniweb.com/software-development/cpp/threads/28093

http://www.cplusplus.com/forum/beginner/3212/

Why Hex numbers are used in computers?

There are so many number systems around but when dealing with computers (especially writing programs and debugging) we especially come across Hexadecimal Numbers. The memory locations are represented as hex and we read those and make sense of out them. But why hexadecimals and why not OCT or Decimal ?? I came across this article which I am sharing with you. It will be worth knowing about what you do everyday.

There are two important aspects to the beauty of using Hexadecimal with computers: First, it can represent 16-bit words in only four Hex digits, or 8-bit bytes in just two; thus, by using a numeration with more symbols, it is both easier to work with and makes it possible to understand some of the vast streams of data inside a computer merely by looking at the Hex output. This is why programs such as DEBUG, use only Hexadecimal to display the actual Binary bytes of a Memory Dump rather than a whole bunch of ones and zeros!

The second aspect is closely related: Whenever it is necessary to convert the Hex representation back into the actual Binary bits, the process is simple enough to be done mentally. For example, FAD7 hex is 1111101011010111 (F=1111, A=1010, D=1101, 7=0111) in Binary. The reason one might wish to do this is in order to work with logical (the instructions AND, OR or XOR) and “bit-oriented” operations (Bit tests, etc.) which may be easier (at times) for a programmer to comprehend.

A very good discussion on the topic can be found here:
http://in.answers.yahoo.com/question/index?qid=20080313054357AAa2uL5
http://www.theproblemsite.com/codes/hex.asp

There are interpreters and compilers to translate a high level language into machine code.

Basic Interpreter
Interpreters directly translate the source into activities (like groups of m/c instructions) and execute them. Basic, for example executes a line and then forgets it executed it, making it slow. Python interpreter translates the entire source code into an intermediate language that is then executed by a much faster interpreter.

Interpreters have an advantage that transition from writing to interpretation is almost immediate. And the source code is always available, so the interpreter can be much more specific when locating errors. Ease of interaction and rapid development are advantages.

However, interpreters are severely limited when building large applications, with python as an exception.

  • The interpreter must always be in memory to execute the code
  • The source code should always be available all at once.

This causes several limitations.

Other examples of interpreted languages are Perl, Javascript, PHP etc

Basic Compiler
Compilers convert the source into assembly language or machine instructions. Eventually, it generates files containing m/c code. There are several steps involved. In most compilers different parts of the code can be compiled separately and linked together by a linker. Thus one can build separate libraries independently and use them later. Compilers also provide good debugging features, with some source level powerful debuggers to show exactly what is happening in the program by tracing its progress through execution.  The steps involved in C/C++ compilation are

-Preprocessor: Preprocessor is a simple program that finds patterns in a source code and replaces it with other text that the programmer has defined. It helps in reducing code size and increasing understandability of the source.  The pre-processed code is written to an intermediate file.

-Compilation 1st pass: The compilation usually happens in two phases. In the first phase, the compiler breaks the source into smaller units and organizes them in structures/trees. For ex, the expression  A+B is broken into A, +, B and each is stored as leaves of the tree.

-Compilation Optional Global optimizer: It is run sometimes between first and second to produce faster smaller code.

-Compilation 2nd pass: In the second pass the compiler walks through the pass tree to generate code for the nodes of the tree. If the code is assembly then the assembler has to be run. In both cases the output is an object (goal) file. A peephole optimizer is sometimes run to eliminate redundant assembly code.

Basic Linker
Linker combines the object modules into an executable that can then be loaded into memory and run by the Operating System. The linker looks for all the references that were made from one object module to another and resolves them. It makes sure that all the external functions that we claimed during compilation, actually exist. Else we get a Linker error. The linker also adds a special module to enable startup activities.  The linker can search through special files called libraries to resolve references. A library contains a collection of object modules in a single file. These libraries are created and maintained by a program called Librarian.

The compiler does static type checking to make sure that the types are not violated. Dynamic type checking is also possible in C++, but static type checking is important for higher execution speed. Separate compilation of subprograms or functions is possible by placing them in separate files.

The compiler allocates storage for identifiers at the point of definition. For a variable, the compiler determines how big the variable is and allocates memory to hold the data for that variable. For a function, the compiler generates code which ends up occupying memory space. We can declare functions and variables in any different places, but there should be only one definition. This is called ODR(One definition Rule).

A detailed discussion of these can be found here:
http://www.antlr.org/wiki/display/ANTLR3/The+difference+between+compilers+and+interpreters
The link below discusses their characteristics very briefly
http://web.cs.wpi.edu/~gpollice/cs544-f05/CourseNotes/maps/Class1/Compilervs.Interpreter.html

Association, Aggregation, Composition

 

Association, aggregation and Composition are the very basic and important design choices when we go on designing any program structure (class structure). We use them often even sometimes without thinking of the terms. In interview questions like ‘design a parking garage using Object Oriented Model’, these three tools come in very handy. I found this below in a blog long back (do not remember which) after a long search for a good explanation and think it is worth sharing.

 

When we have only one relationship between objects, that is called Association. Aggregation and Composition both are specialized form of Association. Composition is again specialize form of Aggregation.

 

Association is a relationship where all object have their own lifecycle and there is no owner. Let’s take an example of Teacher and Student. Multiple students can associate with single teacher and single student can associate with multiple teachers but there is no ownership between the objects and both have their own lifecycle. Both can create and delete independently.

 

Aggregation is a specialize form of Association where all object have their own lifecycle but there is ownership and child object can not belongs to another parent object. Let’s take an example of Department and teacher. A single teacher can not belongs to multiple departments, but if we delete the department teacher object will not destroy. We can think about “has-a” relationship.

 

Composition is again specialize form of Aggregation and we can call this as a “death” relationship. It is a strong type of Aggregation. Child object dose not have their lifecycle and if parent object deletes all child object will also be deleted. Let’s take again an example of relationship between House and rooms. House can contain multiple rooms there is no independent life of room and any room can not belongs to two different house if we delete the house room will automatically delete. Let’s take another example relationship between Questions and options. Single questions can have multiple options and option can not belong to multiple questions. If we delete questions options will automatically delete.

The images have been picked up from a blog. So it would be nasty of me not to give a link of it.
http://yanny0808.blogspot.com/2010/08/uml-association-aggregation-composition.html

It is very difficult to find a good discussion of the topic anywhere. However I’m posting a few links which you may find useful
http://www.visualcase.com/kbase/associations.htm
http://www.go4expert.com/forums/showthread.php?t=17264
 

Association, Aggregation, Composition

When we have only one relationship between objects, that is called Association. Aggregation and Composition both are specialized form of Association. Composition is again specialize form of Aggregation.

Association is a relationship where all object have their own lifecycle and there is no owner. Let’s take an example of Teacher and Student. Multiple students can associate with single teacher and single student can associate with multiple teachers but there is no ownership between the objects and both have their own lifecycle. Both can create and delete independently.

Aggregation is a specialize form of Association where all object have their own lifecycle but there is ownership and child object can not belongs to another parent object. Let’s take an example of Department and teacher. A single teacher can not belongs to multiple departments, but if we delete the department teacher object will not destroy. We can think about “has-a” relationship.

Composition is again specialize form of Aggregation and we can call this as a “death” relationship. It is a strong type of Aggregation. Child object dose not have their lifecycle and if parent object deletes all child object will also be deleted. Let’s take again an example of relationship between House and rooms. House can contain multiple rooms there is no independent life of room and any room can not belongs to two different house if we delete the house room will automatically delete. Let’s take another example relationship between Questions and options. Single questions can have multiple options and option can not belong to multiple questions. If we delete questions options will automatically delete.

Malloc, Calloc, ReAlloc, Free, Memcpy, Memcmp, Memmov, Memset


Standard C provides basically these 4 functions for heap memory allocation at runtime.  All of these are described in standard C library stdlib.h and should be used to handle plain old data, never for class objects in C++.

malloc() -

takes the size of the memory to be allocated and returns a void* pointing to the chunk of allocated memory. If the memory allocation fails, it returns a NULL. We need to typecast the return value into an appropriate pointer and also initialize it as it is not initialized by malloc. So the returned chunk may contain garbage.

Prototype: void *malloc(size_t size);

 

Syntax: cchar * String = (char *) malloc(1000)

So above, 1000 bytes are reserved and the pointer string points to the first byte. The memory is uninitialized.

 

calloc()  -

too allocates memory in a very similar fashion as malloc() with two major differences.

  1. It allocates memory for an array. So it has two parameters, the first gives the number of elements in the array and the second gives the size of each element.
  2. It initializes the memory to zero, so no initialization overhead on the caller.

 

Prototype: void *calloc(size_t elements, size_t sz);

 

Syntax: int * p = (int*) calloc (100, sizeof(int));

 

 

realloc() -

does a little bit more than calloc and malloc. As the name suggests, it can reallocate memory to a pointer. This is an important requirement. So realloc has certain important features

  1. Logically it takes two parameters, one is the pointer whose memory has to be reallocated. And second is the size of the memory to be allocated.
  2. After reallocation it returns the new void pointer which may be the same address before or a new address and which has to be cast to desired type.
  3. The contents of the old memory block are preserved if the size of the new block is larger. Then the contents of the outer bytes are indeterminate. If the size is smaller then, the outer bytes are wiped out.
  4. If the first parameter is zero/NULL, then it behaves exactly like malloc. It returns a pointer to the new allocated memory.
  5. If the second parameter is 0, it behaves like free and deallocates the memory. It is versatile in that sense.

Below is a program demonstrating the use of realloc(). The program takes a number from the user in a loop and allocates memory for it every time. In the end all the numbers in the memory are displayed.

/* realloc example: rememb-o-matic */

#include < stdio.h >

#include < stdlib.h >


int main ()

{

int input,n;

int count=0;

int * numbers = NULL;

 

do {

printf ("Enter an integer value (0 to end): ");

scanf ("%d", &input);

count++;

numbers = (int*) realloc (numbers, count * sizeof(int));

 

if (numbers==NULL)

{

puts ("Error (re)allocating memory"); exit (1);

}

 

numbers[count-1]=input;

} while (input!=0);

 

printf ("Numbers entered: ");

 

for ( n=0; n < count; n++)

printf ("%d ",numbers[n]);

 

free (numbers);

return 0;

}

 


free() -

is used to free the memory allocated by any of the above methods.

/* free example */

#include

#include


int main ()

{

int * buffer1, * buffer2, * buffer3;

buffer1 = (int*) malloc (100*sizeof(int));

buffer2 = (int*) calloc (100,sizeof(int));

buffer3 = (int*) realloc (buffer2,500*sizeof(int));

free (buffer1);

free (buffer3);

return 0;

}

There are some other functions which are almost used every time in C and C++ memory related operations.

 

memset(): -

is used to set the memory to a certain value. We have three parameters to control the behavior of this function.

  1. Pointer to the memory to get the starting address of the memory location
  2. Value to be set for each byte of the memory starting from the pointer
  3. Number of bytes from the start to be set

So the prototype looks something like this:

void* memset(void* ptr, int val, size_t num)

/*

ptr - pointer to the block of memory to fill

val - value to be set. The val is passed as an int but the function fills the

block of memory as an unsigned char version of this value

num - Number of bytes to be set to this value

*/

Ptr is returned as a void pointer, and it is not necessary to catch it.

/* memset example */

#include <stdio.h>

#include <string.h>


int main ()

{

char str[] = "almost every programmer should know memset!";

memset (str,'-',6);

puts (str);

return 0;

}


memchr(): -

searches through the given number of bytes starting from the given pointer for a particular value. If successful, returns the pointer to the first location where the value occurred else returns NULL.

The syntax is very similar to memset. The operation is however different.

const void* memchr(const void* ptr, int val, size_t num)

void* memchr(  void* ptr, int val, size_t num)

/*

ptr - pointer to the block of memory to search

val - value to be searched. The val is passed as an int but the function

searches byte per byte of the block of memory as an unsigned char

version of this value

num - Number of bytes to be searched/analyzed for this value

*/

If the value is found, a pointer to the first occurrence of the value in the block is returned. If the value to be matched is not found, a NULL is returned.

int main ()

{

char * pch;

char str[] = "Example string";

pch = (char*) memchr (str, 'p', strlen(str));

if (pch!=NULL)

printf ("'p' found at position %d.\n", pch-str+1);

else

printf ("'p' not found.\n");

return 0;

}

/*

Output: P is found at position 5

*/

 

memcmp(): -

compares two blocks of memory and returns an integer value of 0, >0 or <0 depending on whether the match. It takes the const pointer of the two memory blocks and the number of bytes to compare.

The syntax is as below:

int memcmp(const void* ptr1, const void* ptr2, size_t num)

/*

ptr1 - const pointer to first the block of memory to compare

ptr2 - const pointer to second the block of memory to compare

num - Number of bytes to be compared

*/

 

The return value is an integer 0 if the two blocks match exactly for the num bytes. The return value is an integer greater than zero if the first byte that does not match has a greater value in ptr1. Following logically a return value of less than zero indicates the opposite.

/* memcmp example */

#include <stdio.h>

#include <string.h>


int main ()

{

char str1[256];

char str2[256];

int n;

printf ("Enter a sentence: "); gets(str1);

printf ("Enter another sentence: "); gets(str2);

n=memcmp ( str1, str2, 256 );

if (n>0) printf ("'%s' is greater than '%s'.\n",str1,str2);

else if (n<0) printf ("'%s' is less than '%s'.\n",str1,str2);

else printf ("'%s' is the same as '%s'.\n",str1,str2);

return 0;

}

memcpy (): -

copies a chunk of memory from source to destination. The function does a bit by bit copying and does not check for any null terminating characters. So the programmer has to be careful while using this. Also the source and destination blocks should not be overlapping. If so then there is a danger of overflowing(Null Terminators might get moved too). In these cases, a safer option to go for is memmove().

Void* memcpy(void* destination, const void* source, size_t num)

/*

destination - pointer to the destination memory block

source - pointer to the source memory block

num - number of bytes to be copied.

*/

The pointer to the destination is returned.

/* memcpy example */

#include <stdio.h>

#include <string.h>


int main ()

{

char str1[]="Sample string";

char str2[40];

char str3[40];

memcpy (str2,str1,strlen(str1)+1);

memcpy (str3,"copy successful",16);

printf ("str1: %s\nstr2: %s\nstr3: %s\n",str1,str2,str3);

return 0;

}

memmove(): -

copies a chunk of memory from the source memory location to the destination memory. It does a bit by bit copy from the source to the destination. However, the difference of memmove with memcpy is that, in memmove copying takes place as if a buffer was used, thus the source and the destination can overlap. The function prototype is exactly the same as memcpy.

Void* memcpy(void* destination, const void* source, size_t num)

/*

destination - pointer to the destination memory block

source - pointer to the source memory block

num - number of bytes to be copied.

*/

The pointer to the destination is returned.

/* memmove example */

#include <stdio.h>

#include <string.h>


int main ()

{

char str[] = "memmove can be very useful......";

memmove (str+20,str+15,11);

puts (str);

return 0;

}

Before I start let me show you this video. This video gives a funnily insightful thought on the topic.

This is a haunting question for beginners in programming and sometimes even seasoned programmers who look fr a switch. I have been asked this several times myself but thankfully never dealt with it myself as C++ was thrown on me literally all the time and never had to make a choice. However the question is important and I will try to throw some light on it for you to reach an answer. A very critical comparison between the two can be found here.

First of all C++ and Java are not the only languages. You can start with Python or Perl or a host of other languages as well which are very powerful. But C++ and Java are the De Facto programming standards and it is good for one to know at least one of these and it is a good idea to start with one of these. They also give you a good foundation in programming and once you know either of them then you can confidently take on the programming world confidently.

The choice is however not an easy one. First I believe you will have done a bit of both in school and have at least a faint idea of what these have to offer. These are humungous languages with ever growing APIs but your first contact with them should give you a feel of whats going to come. And finally there is not one answer as to which one is better. Both are good and have their set of strengths (and weaknesses). There are millions out there working on both and churning out beautiful programs. So the choice is yours and make it carefully. Reading the below might help you arrive at one.

 

  1. C++ has pointers and Java does not. This is a very important consideration if you have found yourself struggling with pointers in school. Pointers are a powerful as well as ugly feature and can make your life hard. I have seen large programs failing and being refactored completely to deal with pointer errors.
  2. Java is (believe me) easier tot write and manage. I did only one project in Java and found it rather easy to learn and grasp. C++ can get ugly and unmanageable with a lot of pointers and references.
  3. C++ I believe gives a lot of power at the hands of the programmer (more than Java). Again pointers essentially let you manage every memory location in the way you want and if you are good at it then you can do anything you want. But with power comes responsibility. For this reason I believe that core tech companies like Google, MS, Yahoo Amazon etc use more C++ than Java.
  4. Java had a large set of useful API, practically a class for everything you want while C++ was lacking in this regard. Now that has changed. With Standard Template Library and Boost Library you have an exhaustive set of API which will make your life easier. Again Java libraries are still easier to use.
  5. If you have never programmed before and have no idea about the above points that I am talking about, then go for C++. I believe that the difficult route is better and can help you later. Once you know C++ well, learning Java will be a piece of cake.

 

Below are a couple of good books for C++ and Java which I suggest to friends.

Object oriented Programing in C++ by Robert Lafore – A very good one for beginning C++.

Thinking in C++ volume 1 and 2 by Bruce Eckel – Excellent pick after you have done Lafore. The two together if done nicely will take you to a level of black belt Ninjas  if done nicely.

Core javaby Cay S. Horstmann and Gary Cornell – An excellent book to learn and grasp Java. Read this slow and steady and you will learn what is java, how it works, design patterns and a lot more. I loved it. Bruce Eckel has a book for Java too and it is naturally called “Thinking in Java” :)

All three books above are award winners and best in business. They are the best way to start.

From a technical perspective, the article below catches quite a few differences.
http://www.computing.dcu.ie/~renaat/projects/cvjava.html

From a career perspective below is a brilliant blog.
http://ask.metafilter.com/56467/Programming-Careers-Java-vs-C
Happy thinking for now. Hope this post helped.