<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/">
<channel>
	<title>Bilal Hatipoglu's Blog</title>
	<link>http://www.bhatipoglu.com/</link>
	<description>The important thing is never to stop questioning</description>
	<lastBuildDate>12.02.2008 22:53:36</lastBuildDate>
	<generator>http://www.bhatipoglu.com/</generator>
	<language>en</language>
	
        <item>
		    <title>Matematik Asla Yalan Söylemez!</title>
		    <link>http://www.bhatipoglu.com/entry/53/matematik-asla-yalan-soylemez</link>
		    <pubDate>12.02.2008 22:53:36</pubDate>
		    <dc:creator>Bilal Hatipoglu</dc:creator>
		    <category><![CDATA[ OFF-Topic ]]></category>
		    <guid isPermaLink="false">http://www.bhatipoglu.com/entry/53/matematik-asla-yalan-soylemez</guid>
		    <description><![CDATA[
		        Matematik Asla Yalan Söylemez...  :))
		        ]]>
		    </description>
			<content:encoded><![CDATA[
			    <div class="tac">
 <img src="/files/matematik/matematik.jpg" /></div>
                <br /><br />
                <a href="http://www.bhatipoglu.com/entry/53/matematik-asla-yalan-soylemez" target="_blank">Feed users, click here to go to this topic's page. You can find related topics and reference links and you can read the comments for this topic</a>
                <br /><br />
                <a href="/comment.asp?id=53" target="_blank">Feed users, click here to post a comment for this topic</a>
                <br /><br />
                <b>Note: There might be problems about HTML code and parsing and displaying HTML code of your viewer application. Also, there are problems caused by Google Reader on displaying of code samples on the entry. Also, the entry might be updated. So, it is recommended to visit the page of the entry.</b>
                <br /><br />
                ]]>
            </content:encoded>
            <wfw:comment>http://www.bhatipoglu.com/entry/53/matematik-asla-yalan-soylemez/#comments</wfw:comment>
		</item>
		
        <item>
		    <title>Finding and Removing Loop on a Singly-Linked List</title>
		    <link>http://www.bhatipoglu.com/entry/52/finding-and-removing-loop-on-a-singly-linked-list</link>
		    <pubDate>06.02.2008 12:02:52</pubDate>
		    <dc:creator>Bilal Hatipoglu</dc:creator>
		    <category><![CDATA[ C / C++ ]]></category>
		    <guid isPermaLink="false">http://www.bhatipoglu.com/entry/52/finding-and-removing-loop-on-a-singly-linked-list</guid>
		    <description><![CDATA[
		        One of the most common interview questions for software professionals is "How do you find a loop in a singly linked list?". Most of the people tend to think in the recursive way to solve this problem. The truth is that the most optimal solution for this problem lies out of the scope of the linked list...
		        ]]>
		    </description>
			<content:encoded><![CDATA[
			    One of the most common interview questions for software professionals is "How do you find a loop in a singly linked list?". Most of the people tend to think in the recursive way to solve this problem. The truth is that the most optimal solution for this problem lies out of the scope of the linked list.
<br /><br />
A singly linked list is a common data structure familiar to all computer scientists. A singly linked list is made of nodes where each node has a pointer to the next node (or null to end the list). On a linked list, adding a new fist element, removing the existing first element, and examining the first element are very fast O(1) operations.
<br /><br />
When working with singly linked list, you are typically given a link to the first node. Common operations on a singly linked list are iterating through all the nodes, adding to the list, or deleting from the list. Algorithms for these operations generally require a well formed linked list. That is a linked list without loops or cycles in it.
<br /><br />
If a linked list has a cycle:
<br /><br />
• The malformed linked list has no end (no node ever has a null next_node pointer) <br />
• The malformed linked list contains two links to some node <br />
• Iterating through the malformed linked list will yield all nodes in the loop multiple times 
<br /><br />
A malformed linked list with a loop causes iteration over the list to fail because the iteration will never reach the end of the list. Therefore, it is desirable to be able to detect that a linked list is malformed before trying an iteration. This article is a discussion of various algorithms to detect a loop in a singly linked list.
<br /><br /><br />

<span class="sp2">Incorrect "Solutions"</span>
<br /><br />
<b>Mark Each Node</b>
<br /><br />
Traverse the list and mark each node as having been seen. If you come to a node that has already been marked, then you know that the list has a loop.


<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>// Incorrect 'solution'
function boolean hasLoop(Node startNode){
  Node currentNode = startNode;
  do {
    if (currentNode.seen) return true;
    currentNode.seen = true;
  } while (currentNode = currentNode.next());
  return false;
}</pre>
</div>
<br />


The problem with this solution is ensuring that "seen" is marked as false for all the nodes before you start. If the linked list has a loop, it isn't possible to iterate over each node to set "seen" to "false" as an initial value for each node.
<br /><br />
Even if you are able to solve the initial value problem, each node in a linked list may not have a field to use for this purpose. Requiring such a field in each node would mean that this is not a generic solution. As we will see later, this field in not needed for a perfectly correct and efficient solution anyway.
<br /><br />
<b>Detect Only Full Loops</b>
<br /><br />
When asked to come up with a solution, a common pitfall is not detecting all loops, but just a loop where the last node links to the first. A loop could still occur (and not be detected) if the last element linked to (for example) the second element. 


<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>// Incorrect 'solution'
function boolean hasLoop(Node startNode){
  Node currentNode = startNode;
  while (currentNode = currentNode.next()){
    if (currentNode == startNode) return true;
  }
  return false;
}</pre>
</div>
<br />


<br />
<span class="sp2">Most Common Inefficient Solution</span>
<br /><br />
<b>Keep a hash set of all nodes seen so far (O(n) time complexity, O(n) space complexity)</b>
<br /><br />
Keeping a set of all the nodes have seen so far and testing to see if the next node is in that set would be a perfectly correct solution. It would run fast as well. However it would use enough extra space to make a copy of the linked list. Allocating that much memory is prohibitively expensive for large lists.


<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>// Inefficient solution
function boolean hasLoop(Node startNode){
  HashSet nodesSeen = new HashSet();
  Node currentNode = startNode;
  do {
    if (nodesSeen.contains(currentNode)) return true;
    nodesSeen.add(currentNode);
  } while (currentNode = currentNode.next());
  return false;
}</pre>
</div>
<br />

<br />
<span class="sp2">Best Solutions</span>
<br /><br />
<b>Catch Larger and Larger Loops (O(n) time complexity)</b>
<br /><br />
Always store some node to check. Occasionally reset this node to avoid the "Detect Only Full Loops" problem. When resetting it, double the amount of time before resetting it again.


<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>// Good solution
function boolean hasLoop(Node startNode){
  Node currentNode = startNode;
  Node checkNode = null;
  int since = 0;
  int sinceScale = 2;
  do {
    if (checkNode == currentNode) return true;
    if (since >= sinceScale){
        checkNode = currentNode;
        since = 0;
        sinceScale = 2*sinceScale;
    }
    since++;
  } while (currentNode = currentNode.next());
  return false;
}</pre>
</div>
<br />


This solution is O(n) because sinceScale grows linearly with the number of calls to next(). Once sinceScale is greater than the size of the loop, another n calls to next() may be required to detect the loop. This solution requires up to 3 traversals of the list.
<br /><br />
This solution was devised by Stephen Ostermiller and proven O(n) by Daniel Martin.
<br /><br />

<b>Catch Loops in Two Passes (O(n) time complexity)</b>
<br /><br />
Simultaneously go through the list by ones (slow iterator) and by twos (fast iterator). If there is a loop the fast iterator will go around that loop twice as fast as the slow iterator. The fast iterator will lap the slow iterator within a single pass through the cycle. Detecting a loop is then just detecting that the slow iterator has been lapped by the fast iterator.


<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>// Best solution
function boolean hasLoop(Node startNode){
  Node slowNode = Node fastNode1 = Node fastNode2 = startNode;
  while (slowNode && fastNode1 = fastNode2.next() && fastNode2 = fastNode1.next()){
    if (slowNode == fastNode1 || slowNode == fastNode2) return true;
    slowNode = slowNode.next();
  }
  return false;
}</pre>
</div>
<br />


This solution is "Floyd's Cycle-Finding Algorithm" as published in "Non-deterministic Algorithms" by Robert W. Floyd in 1967. It is also called "The Tortoise and the Hare Algorithm".
<br /><br />
Robert W. Floyd discoverd the Floyd's cycle-finding algorithm in 1967 based on the properties of the pseudo-random sequences. By applying this algorithm, we simultaneously go through the list by ones (slow iterator) and by twos (fast iterator). If there is a loop the fast iterator will go around that loop twice as fast as the slow iterator. The fast iterator will lap the slow iterator within a single pass through the cycle. Detecting a loop is then just detecting that the slow iterator has been lapped by the fast iterator.
<br /><br /><br />

<span class="sp2">How to remove the loop?</span>
<br /><br />
It's obvious now to detect a loop. But how to remove the loop in the linked list? Goal is to locate the place where the loop is occurring and set that node's next to null.
<br /><br />
It's actually continuation of the detection process. Once the first two pointers have met, ie., a loop has been detected, freeze the first pointer, and set other pointer pointing to the head, advance these two by 1 step each till the next node to each is the same. The position of the second pointer points to the node that is expected to be the tail, and hence its next should be set to NULL.
<br /><br />
But actually it will not work for circlic linked lists, so we need a modification on the algorithm.
<br /><br />
Here is the code that I have written for both, does detection and removal. Test code is included, so you can compile and run for testing. I have tested for there cases: No loop case, one loop in the middle case and circlic case, it's OK.


<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>
#include <stdio.h>

typedef enum { FALSE, TRUE } bool;

/* Declaration of Node type */
typedef struct node_s {
	int data;
	struct node_s *next;
} node_t;

/*
** Detection: Have two pointers into the list (ptr and depar). Advance depar twice as
** fast as ptr; if they ever point to the same place then the list
** has a loop in it.
**
** Removal: Leave one pointer(depar) in place where the two pointers in the previous
** step met, and another pointer(ptr) pointing to the head, advance these two by 1 step
** each till the next node to each is the same. The node pointer with depar will be the
** last node, so set it's next to NULL.
*/
bool findAndRemoveLoop (node_t *head)
{
	node_t *ptr = head;
	node_t *depar = head;
	bool ret = FALSE;		// the return value
	
	// this loop detects the loop
	while (depar) {
		ptr = ptr->next;
		if ((depar = depar->next) && (depar = depar->next) && depar == ptr) {
			ret = TRUE;
			break;
		}
	}
	
	// this part removes the loop
	if (ret == TRUE) {
		ptr = head;
		while(ptr->next != depar->next) {
			ptr = ptr->next;
			depar = depar->next;
		}
		if(ptr == depar) {	    // note that this means it's a circlic list
			// iterate through the last (prev) node
			while(depar->next != ptr) {
				depar = depar->next;
			}
		}
		depar->next = NULL;	// this points to the last node
	}
	
	return ret;
}


////////////////////// TEST CODE ///////////////////////


node_t nodearr[10];

void initNodes()
{
	int i;
	
	// initialize the nodes
	for(i = 0; i < 10; i++) {
		nodearr[i].data = i;
		nodearr[i].next = NULL;
	}
}

void printList(node_t *head)
{
	int limit = 20;
	while(head && (--limit)) {
		printf("%d->",head->data);
		head = head->next;
	}
	printf("\n");
}

int main()
{
	int i;
	node_t * head;
	
	initNodes();
	
	// establish the linked list
	for(i = 0; i < 9; i++) {
		nodearr[i].next = &nodearr[i+1];
	}
	head = &nodearr[0];
	
	// Scenario 1: No loop
	printf("Scenario 1: No loop\n");
	printList(head);
	printf("Scenario 1: After removal\n");
	findAndRemoveLoop(head);
	printList(head);
	
	// Scenario 2: Loop from node 5	
	// let's have the list loop from node 5
	nodearr[9].next = &nodearr[4];
	printf("Scenario 2: Loop from node 5\n");
	printList(head);
	findAndRemoveLoop(head);
	printf("Scenario 2: After removal\n");
	printList(head);
	
	// Scenario 3: Circlic list
	nodearr[9].next = &nodearr[0];
	printf("Scenario 3: Circlic list\n");
	printList(head);
	findAndRemoveLoop(head);
	printf("Scenario 3: After Removal\n");
	printList(head);	
	
	return 0;
}

<a class="a2" target="_blank" href="/files/linkedlist/codes/loop.c">Download Code</a></pre>
</div>
<br />

I hope it helps you. :))
                <br /><br />
                <a href="http://www.bhatipoglu.com/entry/52/finding-and-removing-loop-on-a-singly-linked-list" target="_blank">Feed users, click here to go to this topic's page. You can find related topics and reference links and you can read the comments for this topic</a>
                <br /><br />
                <a href="/comment.asp?id=52" target="_blank">Feed users, click here to post a comment for this topic</a>
                <br /><br />
                <b>Note: There might be problems about HTML code and parsing and displaying HTML code of your viewer application. Also, there are problems caused by Google Reader on displaying of code samples on the entry. Also, the entry might be updated. So, it is recommended to visit the page of the entry.</b>
                <br /><br />
                ]]>
            </content:encoded>
            <wfw:comment>http://www.bhatipoglu.com/entry/52/finding-and-removing-loop-on-a-singly-linked-list/#comments</wfw:comment>
		</item>
		
        <item>
		    <title>Obfuscated C</title>
		    <link>http://www.bhatipoglu.com/entry/51/obfuscated-c</link>
		    <pubDate>03.02.2008 15:27:17</pubDate>
		    <dc:creator>Bilal Hatipoglu</dc:creator>
		    <category><![CDATA[ C / C++ ]]></category>
		    <guid isPermaLink="false">http://www.bhatipoglu.com/entry/51/obfuscated-c</guid>
		    <description><![CDATA[
		        Obfuscated code is source code that is (usually intentionally) very hard or ambiguous to read and understand with extraneous information. Some languages are more prone to obfuscation than others. C, C++ and Perl are most often cited as easily obfuscatable languages. Macro preprocessors are often used to create hard-to-read code by masking the standard language syntax and grammar from the main body of code.
<br /><br />
Code is sometimes obfuscated deliberately for recreational purposes. There are programming contests which reward the most creatively obfuscated code. The contest for C code obfuscation is "The
                                                        International Obfuscated C Code Contest".
		        ]]>
		    </description>
			<content:encoded><![CDATA[
			    Obfuscated code is source code that is (usually intentionally) very hard or ambiguous to read and understand with extraneous information. Some languages are more prone to obfuscation than others. C, C++ and Perl are most often cited as easily obfuscatable languages. Macro preprocessors are often used to create hard-to-read code by masking the standard language syntax and grammar from the main body of code.
<br /><br />
Code is sometimes obfuscated deliberately for recreational purposes. There are programming contests which reward the most creatively obfuscated code. The contest for C code obfuscation is "<a class="a1" href="http://www0.us.ioccc.org/main.html" target="_blank">The
                                                        International Obfuscated C Code Contest</a>".
<br /><br />
The International Obfuscated C Code Contest (abbr. IOCCC) is a programming contest for the most creatively obfuscated C code held annually since 1984. There are many winning entries each year, and each entry gets a category such as "Worst Abuse of the C preprocessor" or "Most Erratic Behavior".
<br /><br />
The IOCCC was started by Landon Curt Noll and Larry Bassel. They were talking together about the horrible code it was their jobs to maintain. They decided to hold a contest for the worst possible C code. Within the code size limit of only a few kilobytes, the contestants manage to do complicated things — a 2004 winner turned out an operating system.
<br /><br />
Some ways in which contributions are notable include:
<br /><br />
• The appearance of the source code, which may resemble images, text, etc. <br />
• Preprocessor redefinitions to make code harder to read <br />
• <a class="a1" href="http://en.wikipedia.org/wiki/Self-modifying_code" target="_blank">Self-modifying code</a>
                                                    <br />
• Worst abuse of the rules. In several years, an entry was submitted that was so patently absurd that it required a new definition of some of the rules for the next year. This, of course, is a high honor. An example is the world's shortest self-reproducing program. The entry was a program zero bytes in length that if run printed zero bytes to the screen (this requires some creative use of the makefile to get it right). The nature of this contest has naturally resulted in programs which skirt around the edges of C standards, or result in constructs which trigger rarely used code path combinations in compilers. As a result, several of the past entries may not compile directly in a modern compiler, and some may even cause crashes.
<br /><br />
An example of obfuscated C code may be this code, which won an award on Obfuscated C Code Contest:
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>#include &lt;stdio.h>
main(t,_,a)
char *a;
{return!0&lt;t?t<3?main(-79,-13,a+main(-87,1-_,
main(-86, 0, a+1 )+a)):1,t<_?main(t+1, _, a ):3,main ( -94, -27+t, a
)&&t == 2 ?_<13 ?main ( 2, _+1, "%s %d %d\n" ):9:16:t<0?t<-72?main(_,
t,"@n'+,#'/*{}w+/w#cdnr/+,{}r/*de}+,/*{*+,/w{%+,/w#q#n+,/#{l,+,/n{n+\
,/+#n+,/#;#q#n+,/+k#;*+,/'r :'d*'3,}{w+K w'K:'+}e#';dq#'l q#'+d'K#!/\
+k#;q#'r}eKK#}w'r}eKK{nl]'/#;#q#n'){)#}w'){){nl]'/+#n';d}rw' i;# ){n\
l]!/n{n#'; r{#w'r nc{nl]'/#{l,+'K {rw' iK{;[{nl]'/w#q#\
n'wk nw' iwk{KK{nl]!/w{%'l##w#' i; :{nl]'/*{q#'ld;r'}{nlwb!/*de}'c \
;;{nl'-{}rw]'/+,}##'*}#nc,',#nw]'/+kd'+e}+;\
#'rdq#w! nr'/ ') }+}{rl#'{n' ')# }'+}##(!!/")
:t<-50?_==*a ?putchar(a[31]):main(-65,_,a+1):main((*a == '/')+t,_,a\
+1 ):0&lt;t?main ( 2, 2 , "%s"):*a=='/'||main(0,main(-61,*a, "!ek;dc \
i@bK'(q)-[w]*%n+r3#l,{}:\nuwloca-O;m .vpbks,fxntdCeghiry"),a+1);}

<a class="a2" target="_blank" href="/files/obfuscated/codes/siir.c">Download Code</a></pre>
</div>
<br />

The code above successfully compiles and suprisingly runs and prints an English poem called "The 12 days of christmas":


<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>blaplopl:/mnt/hgfs/bilalshared/deneme # ./siir
On the first day of Christmas my true love gave to me
a partridge in a pear tree.

On the second day of Christmas my true love gave to me
two turtle doves
and a partridge in a pear tree.

On the third day of Christmas my true love gave to me
three french hens, two turtle doves
and a partridge in a pear tree.

On the fourth day of Christmas my true love gave to me
four calling birds, three french hens, two turtle doves
and a partridge in a pear tree.

On the fifth day of Christmas my true love gave to me
five gold rings;
four calling birds, three french hens, two turtle doves
and a partridge in a pear tree.

On the sixth day of Christmas my true love gave to me
six geese a-laying, five gold rings;
four calling birds, three french hens, two turtle doves
and a partridge in a pear tree.

On the seventh day of Christmas my true love gave to me
seven swans a-swimming,
six geese a-laying, five gold rings;
four calling birds, three french hens, two turtle doves
and a partridge in a pear tree.

On the eighth day of Christmas my true love gave to me
eight maids a-milking, seven swans a-swimming,
six geese a-laying, five gold rings;
four calling birds, three french hens, two turtle doves
and a partridge in a pear tree.

On the ninth day of Christmas my true love gave to me
nine ladies dancing, eight maids a-milking, seven swans a-swimming,
six geese a-laying, five gold rings;
four calling birds, three french hens, two turtle doves
and a partridge in a pear tree.

On the tenth day of Christmas my true love gave to me
ten lords a-leaping,
nine ladies dancing, eight maids a-milking, seven swans a-swimming,
six geese a-laying, five gold rings;
four calling birds, three french hens, two turtle doves
and a partridge in a pear tree.

On the eleventh day of Christmas my true love gave to me
eleven pipers piping, ten lords a-leaping,
nine ladies dancing, eight maids a-milking, seven swans a-swimming,
six geese a-laying, five gold rings;
four calling birds, three french hens, two turtle doves
and a partridge in a pear tree.

On the twelfth day of Christmas my true love gave to me
twelve drummers drumming, eleven pipers piping, ten lords a-leaping,
nine ladies dancing, eight maids a-milking, seven swans a-swimming,
six geese a-laying, five gold rings;
four calling birds, three french hens, two turtle doves
and a partridge in a pear tree.</pre>
</div>
<br />
 

Another interesting award-winning example is the following code:


<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>#include &lt;stdio.h>
#include &lt;stdlib.h>
#include &lt;math.h>

#define _			;double
#define void			x,x
#define case(break,default)	break[O]:default[O]:
#define switch(bool) 		;for(;x<bool;
#define do(if,else)		inIine(else)>int##if?
#define true			(--void++)
#define false			(++void--)

char*O=" <60>!?\\\n"_ doubIe[010]_ int0,int1 _ Iong=0 _ inIine(int eIse){int
O1O=!O _ l=!O;for(;O1O<010;++O1O)l+=(O1O[doubIe]*pow(eIse,O1O));return l;}int
main(int booI,char*eIse[]){int I=1,x=-*O;if(eIse){for(;I<010+1;I++)I[doubIe-1]
=booI>I?atof(I[eIse]):!O switch(*O)x++)abs(inIine(x))>Iong&&(Iong=abs(inIine(x
)));int1=Iong;main(-*O>>1,0);}else{if(booI<*O>>1){int0=int1;int1=int0-2*Iong/0
[O]switch(5[O]))putchar(x-*O?(int0>=inIine(x)&&do(1,x)do(0,true)do(0,false)
case(2,1)do(1,true)do(0,false)6[O]case(-3,6)do(0,false)6[O]-3[O]:do(1,false)
case(5,4)x?booI?0:6[O]:7[O])+*O:8[O]),x++;main(++booI,0);}}}

<a class="a2" target="_blank" href="/files/obfuscated/codes/hoyle.c">Download Code</a></pre>
</div>
<br />

This small and paranormal code draws the graph of given polynomial on the command line output. Two example runs and outputs are:


<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>blaplopl:/mnt/hgfs/bilalshared/deneme/2004 # ./hoyle 0 0 1
\_                              |                              A
  \                             |                             /
   \                            |                            /
    \                           |                           /
     \                          |                          /
      \                         |                         /
       \                        |                        /
        \_                      |                      A/
          \                     |                     /
           \_                   |                   A/
             \_                 |                 A/
               \                |                /
                \__             |             A_/
                   \_           |           A/
                     \__        |        A_/
                        \_______|A______/
________________________________V_______________________________
                                |
                                |
                                |
                                |
                                |
                                |
                                |
                                |
                                |
                                |
                                |
                                |
                                |
                                |
                                |
blaplopl:/mnt/hgfs/bilalshared/deneme/2004 # ./hoyle 0 0 1 2
                                |                              /
                                |
                                |                             /
                                |                            /
                                |                           /
                                |
                                |                          /
                                |                         /
                                |                        /
                                |                      A/
                                |                     /
                                |                   A/
                                |                  /
                                |               A_/
                                |            A_/
                                |A__________/
____________________A___________/_______________________________
                A__/            |
              A/                |
            A/                  |
           /                    |
         A/                     |
        /                       |
       /                        |
      /                         |
     /                          |
    /                           |
   /                            |
                                |
  /                             |
 /                              |
                                |</pre>
</div>
<br />
 
 
It's working, isn't it?
<br /><br />
Another famous C example is:

<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>_(__,___,____){___/__<=1?_(__,___+1,____):!(___%__)?_(__,___+1,0):___%__==___/
__&&!____?(printf("%d\t",___/__),_(__,___+1,0)):___%__>1&&___%__<___/__?_(__,1+
___,____+!(___/__%(___%__))):___<__*__?_(__,___+1,____):0;}main(){_(100,0,0);}</pre>
</div>
<br />

This program prints out the prime numbers less than 100. While this program is extremely difficult to follow, it is the result of several simple transformations from the following elementary program:

<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>void primes(int cap) {
  int i, j, composite;
  for(i = 2; i < cap; i++) {
    composite = 0;
    for(j = 2; j < i; j++) 
      composite += !(i % j);
    if(!composite)
      printf("%d\t", i);
  }
}
 
int main() { 
  primes(100);
}</pre>
</div>
<br />


The first set of transformations aim to reduce the primes function into a single statement: (1) the meat of the function is rewritten as a single while loop with a sequence of cascading if-else structures inside of it; (2) the while loop is then rewritten as recursion; (3) the cascading if-else statements is rewritten as a single conditional statement. These transformations serve to obfuscate the code considerably. The remaining transformations purposefully hide the details of the function by: (4) removing all intermediate variables; (5) renaming the few variables left to _, ___, etc.; and, finally, (6) removing all whitespace and unnecessary parentheses.
<br /><br />
The first transformation takes advantage of the well-known property that any simple function can be transformed into a single while loop followed by a series of cascading if-else statements. The program above is first transformed by rewriting the primes function in this form:

<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>void primes(int cap) { 
  int i, j, composite, t = 0;
  while(t < cap * cap) {
    i = t / cap;
    j = t++ % cap;
    if(i <= 1);
    else if(j == 0)
      composite = 0;
    else if(j == i && !composite)
      printf("%d\t",i);
    else if(j > 1 && j < i)
      composite += !(i % j);  
  }
}
 
int main() {
  primes(100);
}</pre>
</div>
<br />


Another well-known property is that any while loop can be replaced by a series of recursive calls. The program is further transformed by replacing the while loop with recursion. Note that this requires adding two parameters to the primes function's header. Also note the consolidation of two statements into a list in the third if block. Finally note that one additional if-else block must be added to capture the situation in the non-recursive version where program flow fails all of the if-conditions and the while loop would simply continue with t incremented by one:

<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>void primes(int cap, int t, int composite) {
  int i,j;
  i = t / cap;
  j = t % cap;
  if(i <= 1)
    primes(cap,t+1,composite);
  else if(j == 0)
    primes(cap,t+1,0);
  else if(j == i && !composite)
    (printf("%d\t",i), primes(cap,t+1,0));
  else if(j > 1 && j < i)
    primes(cap,t+1, composite + !(i % j));
  else if(t < cap * cap)
    primes(cap,t+1,composite);
}
 
int main() {
  primes(100,0,0);
}</pre>
</div>
<br />


The program is next transformed by changing the variable names to single letters and replacing the if-else structure with conditional statements (e.g. if(A) B else if(C) D else E becomes A ? B : C ? D : E):

<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>void primes(int m, int t, int c) {
  int i,j;
  i = t / m;
  j = t % m;
  (i <= 1) ? primes(m,t+1,c) : (j == 0) ? primes(m,t+1,0) : (j == i && !c) ? 
  (printf("%d\t",i), primes(m,t+1,0)) : (j > 1 && j < i) ? 
  primes(m,t+1,c + !(i % j)) : (t < m * m) ? primes(m,t+1,c) : 0;
}
 
int main() {
  primes(100,0,0);
}</pre>
</div>
<br />



Next, the program is transformed by removing the intermediate variables i and j and replacing them with (t / m) and (t % m), respectively:

<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>void primes(int m, int t, int c) {
  ((t / m) <= 1) ? primes(m,t+1,c) : !(t % m) ? primes(m,t+1,0) : 
  ((t % m)==(t / m) && !c) ? (printf("%d\t",(t / m)), primes(m,t+1,0)) : 
  ((t % m)> 1 && (t % m) < (t / m)) ? primes(m,t+1,c + !((t / m) % (t % m))) : 
  (t < m * m) ? primes(m,t+1,c) : 0;
}
 
int main() {
  primes(100,0,0); 
}</pre>
</div>
<br />



Next, the program is transformed by renaming the function primes and the variables m, t, and c to _, __, ___, and ____, respectively:

<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>void _(int __, int ___, int ____) {
  ((___ / __) <= 1) ? _(__,___+1,____) : !(___ % __) ? _(__,___+1,0) : 
  ((___ % __)==(___ / __) && !____) ? (printf("%d\t",(___ / __)), 
  _(__,___+1,0)) : ((___ % __) > 1 && (___ % __) < (___ / __)) ? 
  _(__,___+1,____ + !((___ / __) % (___ % __))) : (___ < __ * __) ? 
  _(__,___+1,____) : 0;
} 
 
int main() {
  _(100,0,0); 
}</pre>
</div>
<br />



Finally, the program is transformed by removing white space, type declarations, and unambiguous parentheses to come up with the fully obfuscated version:

<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>_(__,___,____){___/__<=1?_(__,___+1,____):!(___%__)?_(__,___+1,0):___%__==___/
__&&!____?(printf("%d\t",___/__),_(__,___+1,0)):___%__>1&&___%__<___/__?_(__,1+
___,____+!(___/__%(___%__))):___<__*__?_(__,___+1,____):0;}main(){_(100,0,0);}</pre>
</div>
<br />



This program runs on most systems. The limiting factor generally will be stack overflow because setting the equivalent of the cap parameter to 100 generally results in 100^2 recursive calls. This sort of obfuscation by program transformation is relatively easy to apply and can be performed on many simple programs.
<br /><br />
There are many varieties of interesting obfuscations ranging from simple keyword substitution, use/non-use of whitespace to create artistic effects, clever self-generating or heavily compressed programs, or programs that are valid and operate similarly in multiple programming languages.
<br /><br />
You can find really very compilated and interesting, award winning codes an programs on "<a class="a1" href="http://www.au.ioccc.org/years.html" target="_blank">The International Obfuscated C Code Contest Winners by Years</a>". There are really interesting ones for example a 32-bit multitasking operating system, a flight simulation program, a maze game, a poker game etc.
<br /><br />
Note: You can download and try the codes below. I have tested each on Linux environment and compiled with GCC. The codes may get unexpected warnings, may not be compiled or run depending on your environment and compiler.

                <br /><br />
                <a href="http://www.bhatipoglu.com/entry/51/obfuscated-c" target="_blank">Feed users, click here to go to this topic's page. You can find related topics and reference links and you can read the comments for this topic</a>
                <br /><br />
                <a href="/comment.asp?id=51" target="_blank">Feed users, click here to post a comment for this topic</a>
                <br /><br />
                <b>Note: There might be problems about HTML code and parsing and displaying HTML code of your viewer application. Also, there are problems caused by Google Reader on displaying of code samples on the entry. Also, the entry might be updated. So, it is recommended to visit the page of the entry.</b>
                <br /><br />
                ]]>
            </content:encoded>
            <wfw:comment>http://www.bhatipoglu.com/entry/51/obfuscated-c/#comments</wfw:comment>
		</item>
		
        <item>
		    <title>Is C a Vitamin? Yes, of course...</title>
		    <link>http://www.bhatipoglu.com/entry/50/is-c-a-vitamin-yes-of-course</link>
		    <pubDate>01.02.2008 08:05:54</pubDate>
		    <dc:creator>Bilal Hatipoglu</dc:creator>
		    <category><![CDATA[ C / C++ ]]></category>
		    <guid isPermaLink="false">http://www.bhatipoglu.com/entry/50/is-c-a-vitamin-yes-of-course</guid>
		    <description><![CDATA[
		        This article is actually a followup for the entry of Ozgur Macit, <a class="a4" href="http://www.ozgurmacit.com/2007/is-c-a-vitamin/"
                                                        target="_blank">on his blog called 'Is C a vitamin?</a> He criticies the missing features of C, importance of C and the teaching of C for Engineering students.
<br /><br />
Please go and read <a class="a4" href="http://www.ozgurmacit.com/2007/is-c-a-vitamin/"
                                                        target="_blank">the referred article</a> before this entry...
		        ]]>
		    </description>
			<content:encoded><![CDATA[
			    This article is actually a followup for the entry of Ozgur Macit, <a class="a4" href="http://www.ozgurmacit.com/2007/is-c-a-vitamin/"
                                                        target="_blank">on his blog called 'Is C a vitamin?</a> He criticies the missing features of C, importance of C and the teaching of C for Engineering students.
<br /><br />
Please go and read <a class="a4" href="http://www.ozgurmacit.com/2007/is-c-a-vitamin/"
                                                        target="_blank">the referred article</a> before this entry.
<br /><br /><br />

At first, let me congratulate Ozgur Macit for this professional entry. it's good to have references, even for a single blog entry, this gives a professionality and article like dignity. But this negative critisism bites me :) , I think there are many worng decisions and iniquity for C, so I've considered to follow up.
<br /><br />
<b>1) Readability (<em>yes, it is Read'A'bility, not Readibility</em>)</b>
<br /><br />
The deep mistake on the entry is, you are comparing C, the low-end of high level languages(this original definition is written by me :) ) with a very-high language, Python. They are so irrelevant that, they are for different purposes. This is from one of your references, "<a class="a1" href="http://en.wikipedia.org/wiki/Comparison_of_programming_languages"
                                                        target="_blank">Comparison of programming languages</a>", on wikipedia:
<br /><br />
                                                    <em>"Language: C<br />
Intended Use: System<br />
Design Goal: Low level access, Minimal constraint<br /><br />

Language: Python<br />
Intended Use: Application, Educational, Scripting<br />
Design Goal: Simplicity, Readability, Expressiveness, Modularity"<br />
                                                    </em>
                                                    <br />

Although this article an wikipedia has many missing things, are there any similarity? No, right. Let's exploit wikipedia, for the purpose and deign goal of C:
<br /><br />
<i>"C is a general-purpose, block structured, procedural, imperative computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system. It has since spread to many other platforms. Although C was designed as a system implementation language, it is also widely used for applications. C has also greatly influenced many other popular languages, especially C++, which was originally designed as an extension to C.
<br /><br />
C is an imperative (procedural) systems implementation language. Its design goals were for it to be compiled using a relatively straightforward compiler, provide low-level access to memory, provide language constructs that map efficiently to machine instructions, and require minimal run-time support. C was therefore useful for many applications that had formerly been coded in assembly language.
<br /><br />
Despite its low-level capabilities, the language was designed to encourage machine-independent programming. A standards-compliant and portably written C program can be compiled for a very wide variety of computer platforms and operating systems with minimal change to its source code. The language has become available on a very wide range of platforms, from embedded microcontrollers to supercomputers..."</i>
<br /><br />
Let me summarize the main goal of the C, the main purpose of use of C: Writing memory and CPU efficient programs, relatively easy to compile(fast compilation), easy to code near the level of assembly languages. It's so low-level that, you can imagine the assembly equivalent of the C code while you are writing the C code :)
<br /><br />
I'm not so familiar with Python, but I know it's for a different purpose, with different pros and cons, with different(higher) level of programming.
<br /><br />
If you want to compare C with another language, this must be Pascal, or Basic or whatever, but with the similar level, with the similar efficiency and similar purpose. You will see it's mostly Pascal, if you want to compare C with a language.
<br /><br />
Now, go and see the comparison on wikipedia: Comparison of Pascal and C (http://en.wikipedia.org/wiki/Pascal_and_C)
<br /><br />
Then, you may not say anything about C's readability. Readability is the primary benefit for whom uses C. You may not know Pascal, but you will see it's very similar to PL/SQL in the syntax. You have the begin-end blocks, if-then-end if, etc. It's very hard to read such a code, compared to the C equivalent, isn't it?
<br /><br />
Also, from a simple Google search, you can find the links:
<br /><br />
                                                    <em>• </em><a class="a1" href="http://www.pascal-central.com/top10.html" target="_blank">
Top 10 Reasons Pascal beats C</a><br />
                                                    <em>• </em><a class="a1" href="http://users.iafrica.com/r/ra/rainier/cpas.htm" target="_blank">
                                                        C vs. Pascal</a>
                                                    <br />
                                                    <em>• </em><a class="a1" href="http://www.lysator.liu.se/c/bwk-on-pascal.html" target="_blank">
Why Pascal is Not My Favorite Programming Language</a>
                                                    <br />
                                                    <br />
If you read them, you can see it's also very ridiculous to compare Pascal and C, because no way to have a better comment than:
<br /><br />
<i>"The question asked is: Which is better or more suited to a particular task ?
<br /><br />
The answer ? There is no answer !"</i>
<br /><br />
And also I love the moral of the story:
<br /><br />
<i>"Bottom line is: 
<br /><br />
Choose the tool you are at ease with and it will serve you well. The C vs Pascal debate is a waste of time. "</i>
<br /><br />
(Both quoted from <a class="a1" href="http://users.iafrica.com/r/ra/rainier/cpas.htm"
                                                        target="_blank">C vs. Pascal</a>)
<br /><br />
And maybe you will have a chance to understand how funny to compare C and Python, or Java or something like.
<br /><br />

<b>2) Orthogonality</b>
<br /><br />
The example ypu have given is not so strange, you can do the same thing with MALLOC kind of stuff, you know. You have addressed the problem of C doesn't have a native String type. That's what the higher-level languages like Java or Python do for storing a String: Dynamic allocation! Since the language does it automatically, it comes so simple for the programmer. You have the simplicity, but you lost the conrol, you lost the efficiency.
<br /><br />
It's not he Orthogonality issue as you said:
<br /><br />
<i>"Programmer occasionally does not have chance to write a similar code for two similar instances of same problem in C. For this reason, C is said to be not orthogonal."</i>
<br /><br />
And let me write the similar code for the same problem that you addressed. You can
                                                    compile and run, it's working:

<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>#include <stdio.h>
#include <stdlib.h>
#include <string.h>


char * double_str(char * s) {
	int len = strlen(s) * 2 + 1;
	char *t = malloc(sizeof(char)*len);
	
	strcpy(t, s);
	strcat(t, s);
	
	t[len-1] = '\0';
	
	return t;
}

int main() {
	char s[] = "hello bilal!";
	
	char *ret = double_str(s);
	
	printf("%s\n",ret);
	
	return 1;
}</pre>
</div>
<br />



<b>3) Safety</b>
<br /><br />
<i>• "Though type checking is done by compiler, programmer is free to make type casting."</i>
<br /><br />
Yes, that what we "the C coders" love. What's wrong with it? In C, the programmer have the power but he also have the responsibility.
<br /><br />
<i>• "C never and never makes index range checking. It is claimed that C encourages buffer overflows with this property in [2]. Same source gives a list of functions that may cause buffer overflow accidentally."</i>
<br /><br />
As I said, "In C, the programmer have the power but he also have the responsibility". Index range checking is not the problem of C, it's actually the problem of the compiler. I know some C compilers does index range checking, but actually it's disabled feature traded to have efficiency.
<br /><br />
Consider a huge loop:

<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>char *c;

...


for(i = 0; i < 999; i++) {
	c[i] = i;
}</pre>
</div>
<br />


And the "sweety"(!) compiler adds the index range checking code:



<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>char *c;

...


for(i = 0; i < 999; i++) {
	if(i > index_range_of_c) {	// whatever, the compiler knows
		printf("Index range out of bounds: c[%d]\n",i);
		return;	// or exit();
	}
	c[i] = i;
}</pre>
</div>
<br />


and compare the execution time (and also compilation effort, not for this case but for general case) of each. Than come and say "Why don't C have index range checking? C is an evil."
<br /><br />
<i>• "Programmer has the memory! No safety check is done about memory allocation." </i>
<br /><br />
Yes. "In C, the programmer have the power but he also have the ..." :)
<br /><br />
C let's programmer to write some code, not writes the code, generates the algorithm and does the job of programmer etc. like Java or Python.
<br /><br />
<i>• "You must not free same pointer twice - again accidentally, if you do you are in trouble. There is no internal mechanisms to avoid this. Programmer must always check the pointer while allocating and freeing memory."</i>
<br /><br />
If programmer needs to check it, he checks it. If the programmer knows what he is doing, no problem. For compiler, why bother and trade the performance for collecting the "garbage" of the programmer every time, so pump and exaggerate the code which will steal my machine cycles and memory?
<br /><br />

<b>4) Redundancy</b>
<br /><br />
<i>"But like a lot of similar things it cannot be fully thrown out of language, because backward compatibility is needed."</i>
<br /><br />
Go and look the documentation of Java. You will see a lot of stuff that is deprecated, although, Java is a brand-new language (developed in mid 90's). C is an old language, yes, some functions have security problems or bugs, but it's normal and not so much.
<br /><br />
<i>“In many ways, the C language evolved into a collection of overlapping features...”</i>
<br /><br />
Overlapping features?? Yes C has overlapping features, but which "old" language doesn't have? The brand-new Java although have much more overlapping features and non-reliabilities. Go and look about it.
<br /><br />
<i>“... providing too many ways to say the same thing, while in many cases not providing needed features.”</i>
<br /><br />
C not providing needed features?? Oh no, why don't you find a psychiatrist, who can carefully listen and confirm you and what you are saying about C?
<br /><br />
Yes a "White Paper" of Java can say that. I had always encouraged them to go and look about inside Java. :))
<br /><br />

<b>5) String type, Error Handling</b>
<br /><br />
Yes, these are considered as missing features also in C community. But one can do what he want with writing some more code and with some workaround, right?
<br /><br />

<b>6) Reaching Elements</b>
<br /><br />
<i>"Another complaint about C is why do we have both . and -> to use for the same purpose. Firstly, they are not for the same purpose. '.' is structure offset and -> is used for dereferencing. Sure we should expect from compiler to take care of this difference or we can simply do not want to help the compiler to ease its job."</i>
<br /><br />
Why not? Is the compiler your enemy, or opponent? It seems to be a simple feature for compiler, but it's actually not easy to keep track of. Notice one of the main purposes of C: Easy, fast compilation. C is designed as it can be compiled also on limited environments.
<br /><br />

<i>"But in my opinion understandability of code increases with this small difference. Looking at the code we can easily see what is a pointer and we are dereferencing its indigrents and what is a name of a real structure. Let me say I never liked Java way of avoiding pointers."</i>
<br /><br />
I can't understand on which side are you but with two different identifiers '.' and '->' one can easily understand if it is a pointer or structure itself. It's more readable. Pascal has also just the '.', but it's just lack of readability I think.
<br /><br />

<b>7) goto statement</b>
<br /><br />
<i>"James A. C. Joyce claims that using a goto statement is the only way of breaking out of nested for or while loops in [2]."</i>
<br /><br />
Yes, he now compared with PHP!! What about Pascal or Basic? And he says:
<br /><br />
<i>"A couple of examples should illustrate what I mean quite nicely. If you've ever programmed in PHP for a substantial period of time, you're probably aware of the 'break' keyword. You can use it to break out from nested loops of arbitrary depth by using it with an integer, such as "break 3"; this would break out of three levels of loops. 
<br /><br />
There is no way of doing this in C. If you want to break out from a series of nested for or while loops then you have to use a goto. This is what is known as a crude hack."</i>
<br /><br />
Yes, we appreciate Kernighan for providing us this hack :))
<br /><br />
<i>"In addition to this, there is no way to compare any non-numerical data type using a switch statement. C does not allow you to use switch and case statements for strings. One must use several variables to iterate through an array of case strings and compare them to the given string with strcmp(). This reduces performance and is just yet another hack. 
<br /><br />
In fact, this is an example of gratuitous library functions running wild once again. Even comparing one string to another requires use of the strcmp() function."</i>
<br /><br />
Dude, do you know how the "high-level languages" that you glorify does that stuff of 'String comparison'?? It's just the same of strcmp() at the lower-level, it must be, the compiler automatically does it, with even worse performance than C. Yes, in C, the "switch" statement does not allow strings, but even the "case of" statement in Pascal not. The features of brand-new, higher level languages fascinate you, but you even don't know what they are stealing from your brand-new GHZ'es of CPU's, GB's of RAM, and high-end hardware configuration. 
<br /><br />
I don't know who James 'whatever' is, but he seems to be a good candidate for being 'The Burlescon of C' :))
<br /><br />
Note: Yes, goto statement lacks of readability, but nobody encourages to use it for most of the languages. It's not an issue for just C.
<br /><br />


<b>8) Enums</b>
<br /><br />
<i>"C’s enum structure has a very significant and important problem which may be easily solved with object-oriented programming. If you use a name in an enum, you cannot use this name in another enum. If you use an object-oriented programming language like Java, you may put the same constant name inside different classes."</i>
<br /><br />
Yes, it seems from now on you are comparing C with Java. :)) Don't make me laugh... If you want OO stuff (with lot's of overhead of inefficient execution) go and use Java, Python or whatever, but don't say anything to C, it's just a structural language. Why don't you compare the OO features of 'your Python' and Java?
<br /><br />

<b>9) What C doesn’t have</b>
<br /><br />
<i>"• Exception handling mechanism "<br />
"• Function overloading "</i>
<br /><br />
Yes it doesn't. Nothing to say.
<br /><br />
<i>"• Specialized data types"</i>
<br /><br />
Object-Oriented features?? :-s
<br /><br />
<i>"• Garbage collection"</i>  
<br /><br />
Consider the garbage of who? :)) C executes the code that it is responsible to, while the 'Glorious Garbage Collector" collects 'The garbage of the programmer' in other languages :)) Consider the overhead of the garbage collector, I will write a separate article about it later. I can't belive you are talking about a lacking
                                                    "garbage collector" under "Waht C doesn't have" :-s<br /><br />

<b>The Conclusion</b>
<br /><br />
<i>"C is not the evil in this story, I think. Just, it is not really proper for high-level programming. It must be used for what it is designed for.
<br /><br />
Some bloody properties cannot be abandoned due to backward compatibility. Newbies always discouraged using these features by experienced programmers."</i>
<br /><br />
Let them be discouraged about it. They will be discouraged many times in the future. It's the reality of life :)) Notice I was discouraged when I have to create a huge "Integer" object for just storing a 4-byte integer value, and also lack of freeing that object from memory when I was done with that object, when I was learning Java.
<br /><br />
<i>"While coding in C, I feel myself in the middle of 70s while memory was so important and that I shouldn’t use a single byte if I really don’t need it."</i>
<br /><br />
Yes, sometimes you need to feel yourself like that. A good programmer always has to feel that. The whole CPU and GB's of cheap memory is not the right thing you may lean on. :)) Never!
<br /><br />
Consider a Systems Programmer or Embedded Environment. That's why it's hard to do that stuff. That's why people can easily learn and develop applications in Java or C#, but not easily learn C and develop the deeper ones in C. I think that must be the difference of a person who got a 4-year Computer Engineering education.
<br /><br />
<i>"This makes me sick about C :)"</i>
<br /><br />
And this makes me love C :))
<br /><br />
As an overall conclusion for your claim about "Is C the best language to teach as the first programming language, for Engineering students":
<br /><br />
If you first teach students Java instead of C, you can never able to:
<br /><br />
1) Teach them the C,<br />
2) The importance and the purpose of C,<br />
3) The importance of efficient programming,<br />
4) The Systems Programming Concept,<br />
5) The Embedded Programming Concept,<br />
6) Even the assembly language :) (Already they are not able to learn assembly, even they are first learning C or other high-level languages)<br />
7) The basic concept and principles of programming languages. Ex: You cannot teach what Java does when ou create an object with New(), if one doesn't already know about what MALLOC() does.
<br /><br />
Since the aim of Computer Engineering study is the stuff above, It is mandatory to teach C, not only teaching the syntax of C, but also teaching the fundamentals of C and teaching them well better than other courses is mandatory.
<br /><br />
But everybody who learns or who knows about Java or other higher level languages starts to criticise on C or the study of C. Sorry, but it's a bullshit.
<br /><br />
"Is C a vitamin?" Yes, of course. Take one-a-day :)) or many, when you need, when you can't solve -as the majority of- real engineering problems(like Systems Programming,
                                                    Embedded Programming, Signal-Image-Voice-Speech Processing, and similar things requires design of efficient applications and algorithms) with higher level languages.

                <br /><br />
                <a href="http://www.bhatipoglu.com/entry/50/is-c-a-vitamin-yes-of-course" target="_blank">Feed users, click here to go to this topic's page. You can find related topics and reference links and you can read the comments for this topic</a>
                <br /><br />
                <a href="/comment.asp?id=50" target="_blank">Feed users, click here to post a comment for this topic</a>
                <br /><br />
                <b>Note: There might be problems about HTML code and parsing and displaying HTML code of your viewer application. Also, there are problems caused by Google Reader on displaying of code samples on the entry. Also, the entry might be updated. So, it is recommended to visit the page of the entry.</b>
                <br /><br />
                ]]>
            </content:encoded>
            <wfw:comment>http://www.bhatipoglu.com/entry/50/is-c-a-vitamin-yes-of-course/#comments</wfw:comment>
		</item>
		
        <item>
		    <title>Differences between C and C++</title>
		    <link>http://www.bhatipoglu.com/entry/49/differences-between-c-and-c++</link>
		    <pubDate>29.01.2008 23:58:06</pubDate>
		    <dc:creator>Bilal Hatipoglu</dc:creator>
		    <category><![CDATA[ C / C++ ]]></category>
		    <guid isPermaLink="false">http://www.bhatipoglu.com/entry/49/differences-between-c-and-c++</guid>
		    <description><![CDATA[
		        The C programming language was designed by Dennies Ritchie in the early 1970s at Bell Laboratories. It was first used system implementation language for the nascent Unix operating system. The main reason to devised C was to overcome the limitations of B.  It was Derived from the type-less language BCPL ((Basic Combined Programming Language). C was was the evolution of B and BCPL by incorporating type checking. It was originally intended for use in writing compilers for other languages.
<br /><br />
C++ was devised by Bjarne Stroustrup in 1983 at Bell Laboratories. It is an extension of C by adding some enhancements to C language. Bjarne combined the simula's(a language designed for making simulations, created by Ole-Johan Dahl and Kristen Nygaard) features of object oriented and the efficiency of C. The new features added to language are templates, namespaces, exception handling and use of standary library...
		        ]]>
		    </description>
			<content:encoded><![CDATA[
			    The C programming language was designed by Dennies Ritchie in the early 1970s at Bell Laboratories. It was first used system implementation language for the nascent Unix operating system. The main reason to devised C was to overcome the limitations of B.  It was Derived from the type-less language BCPL ((Basic Combined Programming Language). C was was the evolution of B and BCPL by incorporating type checking. It was originally intended for use in writing compilers for other languages.
<br /><br />
C++ was devised by Bjarne Stroustrup in 1983 at Bell Laboratories. It is an extension of C by adding some enhancements to C language. Bjarne combined the simula's(a language designed for making simulations, created by Ole-Johan Dahl and Kristen Nygaard) features of object oriented and the efficiency of C. The new features added to language are templates, namespaces, exception handling and use of standary library.
<br /><br />
C and C++ are no more language for writing compilers and other languages, these general purpose languages are used worldwide in every field. 
<br /><br />
C was the C++ predecessor. As it's name implies, a lot of C remains in C++. Although not actually being more powerful than C, C++ allows the programmer to more easily manage and operate with Objects, using an OOP (Object Oriented Programming) concept.
<br /><br />
The main difference between C and C++ is that C++ is object oriented while C is function or procedure oriented. Object oriented programming paradigm is focused on writing programs that are more readable and maintainable. It also helps the reuse of code by packaging a group of similar objects or using the concept of component programming model.  It helps thinking in a logical way by using the concept of real world concepts of objects, inheritance and polymorphism. It should be noted that there are also some drawbacks of such features. For example using polymorphism in a program can slow down the performance of that program. 
<br /><br />
On the other hand, functional and procedural programming focus primarily on the actions and events, and the programming model focuses on the logical assertions that trigger execution of program code.
<br /><br />
C++ allows the programmer to create classes, which are somewhat similar to C structures. However, to a class can be assigned methods, functions associated to it, of various prototypes, which can access and operate within the class, somewhat like C functions often operate on a supplied handler pointer.
<br /><br />
Although it is possible to implement anything  which C++ could implement in C, C++ aids to standarize a way in which objects are created and managed, whereas the C programmer who implements the same system has a lot of liberty on how to actually implement the internals, and style among programmers will vary alot on the design choices made.
<br /><br />
In C, some will prefer the handler-type, where a main function initializes a handler, and that handler can be supplied to other functions of the library as an object to operate on/through. Others will even want to have that handler link all the related function pointers within it which then must be called using a convention closer to C++.
<br /><br />
To finish this discussion, C++ applications are generally slower at runtime, and are much slower to compile than C programs. The low-level infrastructure for C++ binary execution is also larger. For these reasons C is always commonly used even if C++ has a lot of popularity, and will probably continue to be used in projects where size and speed are primary concerns, and portable code still required (assembly would be unsuitable then).
<br /><br />
Another difference is that, type checking for example is much more rigid in C++ than it is in C, so many a program that compiles just fine under a C compiler will result in many warnings and errors under a C++ compiler. 
<br /><br />
So, while C++ might be seen as "C with classes" by some, it actually is different and targeted at a different audience. C still is the best choice for code that has to be fast while still being reasonably readable and portable, eg. device drivers. C++ on the other hand is mainly used in large projects of millions of lines of code, where C code would become unmaintainable. This is mainly due to the possibility to reuse existing code by exploiting the OOP concepts of polymorphism and inheritance.
<br /><br />
<span class="sp2"><b>C++ Features Not in C</b></span>
<br /><br />
<b>Flexible Declarations</b>
<br /><br />
In C, all var declarations within a scope occur at the beginning of that scope. Thus, all global declartions must appear before any functions, and any local declarations must be made before any executable statements. 
C++, on the other hand, allows you to mix data declarations with functions and executable statements. E.g. In C, 
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>         void makeit(void)
         {
            float i;
            char *cp;

            /* imagine 2000 lines of code here */

            /* allocate 100 bytes for cp */
            cp = malloc(100);    /* 1st use of cp */

            for (i=0; i<100; ++i)      /* 1st use of i */
            {
               /* do something */
            }

            /* more code */
         }</pre>
</div>
<br />
In C++, 
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>         void makeit(void)
         {
            // 2000 lines of code

            char *cp = new char[100];

            for (int i=1; i<10; i++)
            {
            }
         }</pre>
</div>
                                                    <br />
<br />
<b>Struct, Union and Enum Tags</b>
<br /><br />
In C, we would have this segment: 
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>         struct foo {int a; float b;}
         struct foo f;</pre>
</div>
<br />
This declares a struct with the tag name 'foo' and then creates an instance of foo named f. Notice when you declare var of that struct, you have to say 'struct foo'. In C++, struct and union tags are considered to be type name, just as if they had been declared by the 'typedef' statement.
 <br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>         struct foo {int a; float b;}
         foo f;</pre>
</div>
<br />
which is equivalent to the following in C: 
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>         typedef struct
                 {
                     int a;
                     float b;
                 } foo;
         foo f;</pre>
</div>
<br />
You have to include the struct keyword before the name of the struct type to declare a struct: In C++, you could do this 
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>	struct a_struct
	{
		int x;
	};
	
	a_struct struct_instance;</pre>
</div>
<br />
and have a new instance of a_struct called struct_instance. In C, however, we have to include the struct keyword when declaring 
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>	struct_instance: 
	struct a_struct struct_instance;</pre>
</div>
<br />
In fact, a similar situation also holds for declaring enums: in C, you must include the keyword enum; in C++, you don't have to. As a side note, most C programmers get around this issue by using typedefs: 
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>	typedef struct struct_name
	{
		/* variables */
	} struct_name_t;</pre>
</div>
<br />
Now you can declare a struct with
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>	struct_name_t struct_name_t_instance;</pre>
</div>
<br />
But there is another gotcha for C++ programmers: you must still use the "struct struct_name" syntax to declare a struct member that is a a pointer to the struct. 
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>	typedef struct struct_name
	{
		struct struct_name instance;
		struct_name_t instance2; /* invalid!  The typedef isn't defined yet */
	} struct_name_t;</pre>
</div>
<br />
Same thing is appliciable for Enum and Union.
<br />
                                                    <br />
                                                    <br />
<b>Const</b>
<br /><br />
In ANSI C, it also supports 'const', but C++'s 'const' is more flexible than C's. In both C and C++, a value declared as 'const' is inviolate; it may not be modified by any part of the program in any way. The most common use of 'const' values in C is to replace '#define' literal constants.
 <br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>         #define MAX_CUSTOMERS   10
         const int MAX_CUSTOMERS = 10;</pre>
</div>
<br />
Thus, 
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>         MAX_CUSTOMERS = 10;
         MAX_CUSTOMERS ++;</pre>
</div>
<br />
are both not acceptable. Note: since you cannot make changes to a 'const', each constant must be initialized when declared. The following is wrong: 
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>         const int invalid;</pre>
</div>
<br />
In C++, you can do something like 
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>         const int ArraySize = 100;
         int Array[ArraySize];</pre>
</div>
<br />
while in ANSI C, this would be flagged as an error. 
<br /><br />
More examples for 'const': 
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>         const int v[] = {1, 2, 3, 4};

         const char* pc = "asdf";   // pointer to constant
         pc[3] = 'a';               // error
         pc = "ghjk";               // ok

         char *const cp = "asdf";   // constant pointer
         cp[3] = 'a';               // ok
         cp = "ghjk";               // error

         const char *const cpc = "asdf";  // const pointer to const
         cpc[3] = 'a';                    // error
         cpc = "ghjk";                    // error</pre>
</div>
<br />
Function call: 
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>         char* strcpy (char* p, const char*q);  // cannot modify *q</pre>
</div>
<br />
Here, by declaring a pointer argument const, the function is prohibited from modifying the object pointed to, which makes perfect sense since strcpy copies q to p and you better preserve q. 
<br />
                                                    <br />
                                                    <br />
<b>The :: Operator</b>
<br /><br />
:: is called the scope resolution operator and is used to access an item hidden in the current scope. For example, 
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>         int a;

         main()
         {
            float a;

            a = 1.5;
            ::a = 2;

            cout << "local a=" << a << endl;
            cout << "global a=" << ::a << endl;</pre>
</div>
<br />
The :: operator says, "don't use the local a, use the one declared outside the scope".
Thus: 
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>         local a=1.5
         global a=2</pre>
</div>
<br />
It is to be noted, however, that it's possible to use the global var without the :: operator: 
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>         int x = 11;

         void f4()
         {
            int y = x;     // global x
            int x = 22;
            y = x;         // local x
         }</pre>
</div>
                                                    <br />
<br />
<b>New and Delete</b>
<br /><br />
In C, all dynamic mem allocation is handled via library calls, such as 'malloc' and 'free'. Here's how a traditional C programs might allocate memory: 
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>         void func(void)
         {
            int *i;

            i = (int *)malloc(sizeof(int));
            *i = 10;
            printf("%d", *i);
            free(i);
         }</pre>
</div>
<br />
In C++, there are new ways of dynamically allocating mem using operators called 'new' and 'delete', where 'new' replaces 'malloc' and 'delete' replaces 'free' in C. We could rewrite the above function as the following: 
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>         void func()
         {
            int *i = new int;

            *i = 10;
            cout << *i;
            delete i;
         }</pre>
</div>
<br />
You'd probably agree this is a much clearer syntax and it's much easier to use as well. A couple more examples: 
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>         int *i = new int[10];    //  an array of 10 integers
         int *i[10] = new int(*)[10]; // an array of 10 pointers to integers</pre>
</div>
<br />
You can also intialize all the variables allocated by 'new': 
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>         float *f = new float[50] (0.0);</pre>
</div>
<br />
In C, there's only one major memory allocation function: malloc. You use it to allocate both single elements and arrays: 
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>	int *x = malloc( sizeof(int) );
	int *x_array = malloc( sizeof(int) * 10 );</pre>
</div>
<br />
and you always release the memory in the same way: 
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>	free( x );
	free( x_array );</pre>
</div>
<br />
In C++, however, memory allocation for arrays is somewhat different than for single objects; you use the new[] operator, and you must match calls to new[] with calls to delete[] (rather than to delete). 
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>	int *x = new int;
	int *x_array = new int[10];
	
	delete x;
	delete[] x;</pre>
</div>
<br />
The short explanation is that when you have arrays of objects, delete[] with properly call the destructor for each element of the array, whereas delete will not. 
<br /><br />
Note: Don't mix the use of 'new' and 'delete' with that of 'malloc' and 'free'. i.e, always use either all the C lib calls 'malloc' and 'free' in your program to manage dynamic mem. OR use all 'new' and 'delete'. All the mem allocated by 'malloc' should be returned to the available mem pool by 'free' and the same holds for 'new' and 'delete'. I'd just use 'new' and 'delete'.
<br />
                                                    <br />
                                                    <br />
<b>References</b>
<br /><br />
C can by clumsy sometimes. When you write a function to swap two integers, you have to pass the two integers into the function by reference: 
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>         void swapint(int *a, int *b)
         {
            int temp;

            temp = *a;
            *a = *b;
            *b = temp;
         }</pre>
</div>
<br />
Here's the function call: 
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>         swapint(&i1, &i2);</pre>
</div>
<br />
C++ supports a special type of identifier known as 'reference' &. It makes changing the parameter values in a function reletively painless. The above function can be rewritten in C++ as follows: 
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>         void swapint(int &a, int &b)
         {
            int temp = a;
            a = b;
            b = temp;
         }</pre>
</div>
<br />
Function call: 
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>         swapint(i1, i2);</pre>
</div>
<br />
When i1 and i2 are passed into the function, a POINTS to i1 and b POINTS to i2 instead of making local copies of i1 and i2. Now, whenever you refer to a or b in the function, you actually refer to i1 and i2. So, whatever changes you make to a or b, they will be reflected on i1 and i2.
<br />
                                                    <br />
                                                    <br />
<b>Function Overloading</b>
<br /><br />
In C, as in most other programming languages, every function must have a unique name. At times, it can be annoying. Imagine you want to have a function that returns the abs value of an integer. 
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>         int abs(int i);</pre>
</div>
<br />
If you need to figure out the abs value of every possible available data type, you then have to write a function for each of the possible types: 
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>         long labs(long l);
         double dabs(double d);</pre>
</div>
<br />
All those functions do the same thing -- return the abs value of the argument. Thus it seems silly to have a different name for each of those functions. C++ solves this by allowing you to create those functions with the same name. This is called overloading. For example, you can do the above in C++: 
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>         int abs(int i);
         long abs(long l);
         double abs(double d);</pre>
</div>
<br />
And depending on the type of parameter you pass into the 'abs' func. C++ will select the right one. Note: What if the type of the parameter passed in is not identical to any of the available parameter types in the existing functions? 
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>               abs('a');
               abs(3.1415F);</pre>
</div>
<br />
C++ will try to make the easiest conversion to match those parameter types in the funcion prototypes. 
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>               abs('a');      // call int abs(int i)
               abs(3.1415F);  // call double abs(double d);</pre>
</div>
<br />
If no such conversion exists, then an error will occur. 
<br /><br />
There is a huge article (as large as to be referred as a book :) ) in <a class="a4"
                                                        href="/link.asp?r=http://david.tribble.com/text/cdiffs.htm" target="_blank">here</a>,
                                                    which covers Incompatibilities and many differences Between ISO C and ISO C++, but I only covered some important ones.
<br /><br />
For the last word, there are many features in C++ which are not exist in C, but many people already prefers C for the reasons like: the syntax is much easier to write in C, harder to compile C++ code (not harder for user but harder for computer :) ), and for whom who cares about a single byte to save from Memory or a single cycle to save from CPU, C is more efficient :) <i>PS: I am lovin' it ;)</i>

                <br /><br />
                <a href="http://www.bhatipoglu.com/entry/49/differences-between-c-and-c++" target="_blank">Feed users, click here to go to this topic's page. You can find related topics and reference links and you can read the comments for this topic</a>
                <br /><br />
                <a href="/comment.asp?id=49" target="_blank">Feed users, click here to post a comment for this topic</a>
                <br /><br />
                <b>Note: There might be problems about HTML code and parsing and displaying HTML code of your viewer application. Also, there are problems caused by Google Reader on displaying of code samples on the entry. Also, the entry might be updated. So, it is recommended to visit the page of the entry.</b>
                <br /><br />
                ]]>
            </content:encoded>
            <wfw:comment>http://www.bhatipoglu.com/entry/49/differences-between-c-and-c++/#comments</wfw:comment>
		</item>
		
        <item>
		    <title>Whence C? Why C? Whither C?</title>
		    <link>http://www.bhatipoglu.com/entry/48/whence-c-why-c-whither-c</link>
		    <pubDate>29.01.2008 23:52:34</pubDate>
		    <dc:creator>Bilal Hatipoglu</dc:creator>
		    <category><![CDATA[ C / C++ ]]></category>
		    <guid isPermaLink="false">http://www.bhatipoglu.com/entry/48/whence-c-why-c-whither-c</guid>
		    <description><![CDATA[
		        As about ten years ago, C was the most popular programming language being used. Programmers wrote C code for PCs, mainframes, and supercomputers. C was standardized so that the same program would run on every kind of computer using every kind of operating system available.  
<br /><br />
Today, the use of C has dramatically decreased. Rarely will a project be written in C. Programmers are using languages such as C++ and Java to create applications that run on standalone, networked, and Internet-based machines. Yet, when learning to program, C is considered to be the one language it is imperative a programmer master before moving on to the other languages in use today...
		        ]]>
		    </description>
			<content:encoded><![CDATA[
			    As about ten years ago, C was the most popular programming language being used. Programmers wrote C code for PCs, mainframes, and supercomputers. C was standardized so that the same program would run on every kind of computer using every kind of operating system available.  
<br /><br />
Today, the use of C has dramatically decreased. Rarely will a project be written in C. Programmers are using languages such as C++ and Java to create applications that run on standalone, networked, and Internet-based machines. Yet, when learning to program, C is considered to be the one language it is imperative a programmer master before moving on to the other languages in use today.  
 <br /><br />
The reason for C's recommended mastery, despite its low levels of actual use, is that C is the common denominator of many of today's languages; learn C and these languages will be simple to learn. Languages such as C++ and Java are based on C. In fact, many of the statements and commands in these newer languages are identical to the ones found in C. Overall, C is much simpler to learn than these languages because it carries with it a much slimmer toolkit of add-on procedures. 
<br /><br />
The article below is taken from the first chapter of the book "C Primer Plus, Fifth Edition, By Stephen Prata, 2004". 
<br /><br /><br />

<span class="sp2"><b>Whence C?</b></span>
<br /><br />
Dennis Ritchie of Bell Labs created C in 1972 as he and Ken Thompson worked on designing the Unix operating system. C didn't spring full-grown from Ritchie's head, however. It came from Thompson's B language, which came from… but that's another story. The important point is that C was created as a tool for working programmers, so its chief goal is to be a useful language.
<br /><br />
Most languages aim to be useful, but they often have other concerns. The main goal for Pascal, for instance, was to provide a sound basis for teaching good programming principles. BASIC, on the other hand, was developed to resemble English so that it could be learned easily by students unfamiliar with computers. These are important goals, but they are not always compatible with pragmatic, workaday usefulness. C's development as a language designed for programmers, however, has made it one of the modern-day languages of choice.
<br /><br /><br />

<span class="sp2"><b>Why C?</b></span>
<br /><br />
During the past three decades, C has become one of the most important and popular programming languages. It has grown because people try it and like it. In the past decade, many have moved from C to the more ambitious C++ language, but C is still an important language in its own right, as well a migration path to C++. As you learn C, you will recognize its many virtues (see Figure 1.1). Let's preview a few of them now.
<br /><br />

<div class="tac">
    <strong>Figure 1.1. The virtues of C.</strong><br /><br class="k" /><img src="/files/why_c/cfig1.jpg" /></div>

<br /><br />
<b>Design Features</b>
<br /><br />
C is a good language incorporating the control features found desirable by the theory and practice of computer science. Its design makes it natural for top-down planning, structured programming, and modular design. The result is a more reliable, understandable program.
<br /><br />
<b>Efficiency</b>
<br /><br />
C is an efficient language. Its design takes advantage of the capabilities of current computers. C programs tend to be compact and to run quickly. In fact, C exhibits some of the fine control usually associated with an assembly language. (An assembly language is a mnemonic representation of the set of internal instructions used by a particular central processing unit design; different CPU families have different assembly languages.) If you choose, you can fine-tune your programs for maximum speed or most efficient use of memory.
<br /><br />
<b>Portability</b>
<br /><br />
C is a portable language, which means that C programs written on one system can be run on other systems with little or no modification. If modifications are necessary, they can often be made by simply changing a few entries in a header file accompanying the main program. Most languages are meant to be portable, but anyone who has converted an IBM PC BASIC program to Apple BASIC (and they are close cousins) or has tried to run an IBM mainframe FORTRAN program on a Unix system knows that porting is troublesome at best. C is a leader in portability. C compilers (programs that convert your C code into the instructions a computer uses internally) are available for about 40 systems, running from 8-bit microprocessors to Cray supercomputers. Note, however, that the portions of a program written specifically to access particular hardware devices, such as a display monitor, or special features of an operating system, such as Windows XP or OS X, typically are not portable.
<br /><br />
Because of C's close ties with Unix, Unix systems typically come with a C compiler as part of the packages. Linux installations also usually include a C compiler. Several C compilers are available for personal computers, including PCs running various versions of Windows, and Macintoshes. So whether you are using a home computer, a professional workstation, or a mainframe, the chances are good that you can get a C compiler for your particular system.
<br /><br />
<b>Power and Flexibility</b>
<br /><br />
C is powerful and flexible (two favorite words in computer literature). For example, most of the powerful, flexible Unix operating system is written in C. Many compilers and interpreters for other languages—such as FORTRAN, Perl, Python, Pascal, LISP, Logo, and BASIC—have been written in C. As a result, when you use FORTRAN on a Unix machine, ultimately a C program has done the work of producing the final executable program. C programs have been used for solving physics and engineering problems and even for animating special effects for movies such as Gladiator.
<br /><br />
<b>Programmer Oriented</b>
<br /><br />
C is oriented to fulfill the needs of programmers. It gives you access to hardware, and it enables you to manipulate individual bits in memory. It has a rich selection of operators that allows you to express yourself succinctly. C is less strict than, say, Pascal in limiting what you can do. This flexibility is both an advantage and a danger. The advantage is that many tasks, such as converting forms of data, are much simpler in C. The danger is that with C, you can make mistakes that are impossible in some languages. C gives you more freedom, but it also puts more responsibility on you.
<br /><br />
Also, most C implementations have a large library of useful C functions. These functions deal with many needs that a programmer commonly faces.
<br /><br />
<b>Shortcomings</b>
<br /><br />
C does have some faults. Often, as with people, faults and virtues are opposite sides of the same feature. For example, we've mentioned that C's freedom of expression also requires added responsibility. C's use of pointers (something you can look forward to learning about in this book), in particular, means that you can make programming errors that are very difficult to trace. As one computer preliterate once commented, the price of liberty is eternal vigilance.
<br /><br />
C's conciseness combined with its wealth of operators make it possible to prepare code that is extremely difficult to follow. You aren't compelled to write obscure code, but the opportunity is there. After all, what other language has a yearly Obfuscated Code contest?
<br /><br />
There are more virtues and, undoubtedly, a few more faults. Rather than delve further into the matter, let's move on to a new topic.
<br /><br /><br />

<span class="sp2"><b>Whither C?</b></span>
<br /><br />
By the early 1980s, C was already a dominant language in the minicomputer world of Unix systems. Since then, it has spread to personal computers (microcomputers) and to mainframes (the big guys). See Figure 1.2. Many software houses use C as the preferred language for producing word processing programs, spreadsheets, compilers, and other products. These companies know that C produces compact and efficient programs. More important, they know that these programs will be easy to modify and easy to adapt to new models of computers.
<br /><br />

<div class="tac">
    <strong>Figure 1.2. Where C is used.</strong><br /><br class="k" /><img src="/files/why_c/cfig1.jpg" /></div>


<br /><br />
What's good for companies and C veterans is good for other users, too. More and more computer users have turned to C to secure its advantages for themselves. You don't have to be a computer professional to use C.
<br /><br />
In the 1990s, many software houses began turning to the C++ language for large programming projects. C++ grafts object-oriented programming tools to the C language. (Object-oriented programming is a philosophy that attempts to mold the language to fit a problem instead of molding the problem to fit the language.) C++ is nearly a superset of C, meaning that any C program is, or nearly is, a valid C++ program, too. By learning C, you also learn much of C++.
<br /><br />
Despite the popularity of newer languages, such as C++ and Java, C remains a core skill in the software business, typically ranking in the top 10 of desired skills. In particular, C has become popular for programming embedded systems. That is, it's used to program the increasingly common microprocessors found in automobiles, cameras, DVD players, and other modern conveniences. Also, C has been making inroads in FORTRAN's long dominance of scientific programming. Finally, as befits a language created to develop an operating system, it plays a strong role in the development of Linux. Thus, the first decade of the twenty-first century finds C still going strong.
<br /><br />
In short, C is one of the most important programming languages and will continue to be so. If you want a job writing software, one of the first questions you should be able to answer yes to is "Oh say, can you C?"
                <br /><br />
                <a href="http://www.bhatipoglu.com/entry/48/whence-c-why-c-whither-c" target="_blank">Feed users, click here to go to this topic's page. You can find related topics and reference links and you can read the comments for this topic</a>
                <br /><br />
                <a href="/comment.asp?id=48" target="_blank">Feed users, click here to post a comment for this topic</a>
                <br /><br />
                <b>Note: There might be problems about HTML code and parsing and displaying HTML code of your viewer application. Also, there are problems caused by Google Reader on displaying of code samples on the entry. Also, the entry might be updated. So, it is recommended to visit the page of the entry.</b>
                <br /><br />
                ]]>
            </content:encoded>
            <wfw:comment>http://www.bhatipoglu.com/entry/48/whence-c-why-c-whither-c/#comments</wfw:comment>
		</item>
		
        <item>
		    <title>Türkçe Karakterli Domain'lerin İç Yüzü</title>
		    <link>http://www.bhatipoglu.com/entry/47/turkce-karakterli-domainlerin-ic-yuzu</link>
		    <pubDate>22.12.2007 13:09:31</pubDate>
		    <dc:creator>Bilal Hatipoglu</dc:creator>
		    <category><![CDATA[ OFF-Topic ]]></category>
		    <guid isPermaLink="false">http://www.bhatipoglu.com/entry/47/turkce-karakterli-domainlerin-ic-yuzu</guid>
		    <description><![CDATA[
		        Haberiniz var mı? 4 Aralık 2006 tarihinden itibaren Türkçe karakterli domainler de tescil edilmeye başlandı. Almadıysanız ve kaptırmadıysanız şirketinizin veya isminizin domainini hemen alın! Ancak, bunu yaparken dikkat etmeniz gereken bir husus var! Türkiye'de, her şeyde olduğu gibi, bu yenilikten de rant elde etmeye çalışanlar, hatta şimdiye kadar bile büyük paralar götürenler var...

		        ]]>
		    </description>
			<content:encoded><![CDATA[
			    Haberiniz var mı? 4 Aralık 2006 tarihinden itibaren Türkçe karakterli domainler de tescil edilmeye başlandı. Almadıysanız ve kaptırmadıysanız şirketinizin veya isminizin domainini hemen alın! Ancak, bunu yaparken dikkat etmeniz gereken bir husus var! Türkiye'de, her şeyde olduğu gibi, bu yenilikten de rant elde etmeye çalışanlar, hatta şimdiye kadar bile büyük paralar götürenler var...
<br /><br />
Evet, önce nasıl oldu da düne kadar sadece ascii karakterler içeren domainler alınabilirken bir anda Türkçe karakter desteği geldi ona bakalım:
<br /><br />
Türkiye'de ".tr" uzantılı domainlerin kayıt edilmesinden sorumlu firma <a class="a1"
                                                        href="http://www.nic.tr" target="_blank">nic.tr</a> sitesinde bu konuyla ilgili bilgilendirici bir yazı yazmış, önce oradan alıntı yapalım:
<br /><br />
                                                    <strong>Internationalized Domain Names (Uluslararasılaştırılmış Alan Adları)
<br />
                                                    </strong>
                                                    <br />
                                                    <strong>IDN nedir?
<br />
                                                    </strong>
                                                    <br />
IDN, ASCII olmayan karakterleri içerebilen alan adlarıdır. Standart Internet alan adları çok kısıtlı bir karakter kümesini destekler: a-z, A-Z, 0-9 ve '-''den başka hiçbir karakter içeremez. Bu kısıtlama, kişinin kendi dilinde alan adları almasına büyük oranda engel teşkil eder.
<br /><br />
<strong>IDN alt yapısı ve işleyişi</strong>
<br /><br />
IDN standardı, var olan alan adı sistemini yenilemeye değil, genişletmeye yöneliktir. Alan adlarını birbirine dönüştürecek algoritmalar sunar. Standardın sunduğu algoritmalar Unicode karakterlerinden oluşan bir alan adını sadece ASCII karakterlerinden oluşan bir alan adına dönüştürebilir veya ASCII hali verilmiş bir IDN'i Unicode karakterlerden oluşan hale çevirebilir. <span style="text-decoration: underline">Bir kullanıcı tarayıcısına 'çağlayan.web.tr' yazdığında, tarayıcı IDN standartlarında belirtilen algoritmaları kullanarak 'çağlayan.web.tr' alan adının ASCII karakterlerinden oluşan halini bulur ve DNS'e ASCII halini, sıradan bir alan adını sorgular gibi, sorgular.</span>
                                                    IDN, var olan yapıyı değiştirmemek için dönüştürme işini istemciye aktarır (bu örnekte tarayıcıya). <span style="text-decoration: underline">IDN kaydı sırasında kullanıcı aslında -tam olarak- istediği alan adını almaz! Sistem kullanıcının adına IDN'in ASCII halini kaydeder. Kullanıcı 'çağlayan.web.tr' yi kaydettirdiğinde gerçekte 'xn--alayan-vua36b.web.tr' alan adını almış olur. 
<br />
                                                    </span>
                                                    <br />
IDN' lerin düzgün çalışması için istemcilerin desteklemesi (istemcilerin bir IDN girildiğinde onun IDN olduğunu anlayıp ASCII haline çevirebilmesi) gerekir. IDN için şu anda popüler tarayıcıların çoğu destek sunmaktadır. <span style="text-decoration: underline">
                                                        Firefox ve IE7.0 tam destek sunarken, IE6.0 için bir yama yapılması gerekir. E-posta istemcileri henüz tam destek vermediklerinden, IDN'leri elektronik posta için kullanmanız tavsiye edilmemektedir.</span> İstemciler IDN'i destekledikleri takdirde, e-posta ve diğer işlemler için de kullanılabilirler. 
<br /><br />
<strong>IDN ne değildir?</strong>
<br /><br />
IDN var olan alan adı yapısını değiştirmeyi hedefleyen bir sistem değildir!
<br /><br />
IDN'in amacı, varolan sistemde kaydedilemeyen ve Türkçe karekterleri içeren alan adlarını da kaydedebilmektir. Bu nedenle IDN, düzgün çalışan alt sisteme (DNS alt yapısı, internet standartları vb.) ek bir yük getirmez. Onun üstünde bir katman olarak iş görür. 
<br /><br />
Evet, buradan çıkarılması gereken önemli noktalar şunlar:
<br /><br />
                                                    <strong>1-</strong> IDN var olan alan adı yapısını değiştirmeyi hedefleyen bir sistem
                                                    değildir! Dünyadaki bütün DNS sistemi bizim Türkçe karakterlerimizi desteklemek
                                                    için değişmedi :) Bu sadece bir algoritma sayesinde Türkçe karakterli isimlerin
                                                    ascii karaktere çevrilmesidir.<br /><br />
                                                    <strong>2-</strong> Yapılan iş, sadece, web tarayıcınıza yazdığınız Türkçe karakterler içeren bir adresin, web tarayıcı tarafından bir algoritmayla ascii karakterlere sahip karşılığına çevrilmesidir.
<br /><br />
                                                    <strong>
3-</strong> Internet Explorer 6 henüz bunu desteklememektedir. Bunun için yama gerekmektedir. Mozilla ve IE 7 ise desteklemektedir.
<br /><br />
                                                    <strong>
4-</strong> E-Posta istemcileri (örn: Outlook) henüz bunu desteklememektedir. (Aslında kısa sürede onlar için de yama çıkar. Sonuçta basit bir şekilde isimleri dönüştürecek olan server tarafı değil, client tarafındaki uygulamadır)
<br /><br />
Evet, şimdi bizim Türklerin bundan nasıl rant sağlamaya çalıştıklarına bakalım:
<br /><br />
                                                    <strong>1-</strong> Şu an itibariyle bir çok şirket ve şahsın ismi, bu sistem daha devreye girmeden satın alınmıştır ve bir çoğu milyarlarca lira (binlerce YTL) ücretle satılmaya çalışılmaktadır.
<br /><br />
                                                    <strong>2-</strong> Şu anda "Türkçe karakterli domain satıyoruz" diyen firmalar normalde 7-8 dolar olan domainleri 20 dolara satmaya çalışmaktadır.
<br /><br />
Arkadaşlar, bu hususlara dikkat. Birileri bu işten ciddi miktarda kar elde edecek. Buna mahal vermeyelim. Peki ne yapacağız?
<br /><br />
Türkçe karakterli domain almak istiyorsak ne yapmalıyız?
<br /><br />
20 dolar verip Türkçe karakterli bir domain almamalıyız! Bunun yerine, Mozilla veya IE 7'yi çalıştırıp, almak istediğimiz domaini yazıp (örn: www.bhatipoğlu.com) ilgini web tarayıcının, algoritmayı kullanarak saliseler içinde bunu ascii karakterli haline çevirmesini bekleyip, çevirdikten sonra bu ascii karakterli halini satın almalıyız! (örn: bhatipoğlu.com için xn--bhatipolu-wkb.com)
<br /><br />
Böylece, bu ismi 7-8 dolar(yıllık) gibi bir ücretle satın almış oluruz. Zaten "Türkçe karakterli domain satıyoruz" diyen firmaların yaptığı iş de bu!   
                <br /><br />
                <a href="http://www.bhatipoglu.com/entry/47/turkce-karakterli-domainlerin-ic-yuzu" target="_blank">Feed users, click here to go to this topic's page. You can find related topics and reference links and you can read the comments for this topic</a>
                <br /><br />
                <a href="/comment.asp?id=47" target="_blank">Feed users, click here to post a comment for this topic</a>
                <br /><br />
                <b>Note: There might be problems about HTML code and parsing and displaying HTML code of your viewer application. Also, there are problems caused by Google Reader on displaying of code samples on the entry. Also, the entry might be updated. So, it is recommended to visit the page of the entry.</b>
                <br /><br />
                ]]>
            </content:encoded>
            <wfw:comment>http://www.bhatipoglu.com/entry/47/turkce-karakterli-domainlerin-ic-yuzu/#comments</wfw:comment>
		</item>
		
        <item>
		    <title>Windows Source Codes</title>
		    <link>http://www.bhatipoglu.com/entry/46/windows-source-codes</link>
		    <pubDate>17.09.2007 00:00:30</pubDate>
		    <dc:creator>Bilal Hatipoglu</dc:creator>
		    <category><![CDATA[ Operating Systems ]]></category>
		    <guid isPermaLink="false">http://www.bhatipoglu.com/entry/46/windows-source-codes</guid>
		    <description><![CDATA[
		        Microsoft has suffered what appears to be a severe leak of Windows source code, with a file circulating on the Internet appearing to consist of several million lines of code from around mid-2000. The source code seems to relate to NT4 and Windows 2000, and in a statement the company has conceded that "portions of the Microsoft Windows 2000 and Windows NT 4.0 source code were illegally made available on the Internet.
<br /><br />
Finally, we got the source code with great effort, and I am publishing just some part of it.
<br /><br />
"It's illegal for third parties to post Microsoft source code," spokesman Tom Pilla said. "We obviously take that very seriously." So, don't tell anybody that you got it from here, just Enjoy ;)
		        ]]>
		    </description>
			<content:encoded><![CDATA[
			    Microsoft has suffered what appears to be a severe leak of Windows source code, with a file circulating on the Internet appearing to consist of several million lines of code from around mid-2000. The source code seems to relate to NT4 and Windows 2000, and in a statement the company has conceded that "portions of the Microsoft Windows 2000 and Windows NT 4.0 source code were illegally made available on the Internet.
<br /><br />
Finally, we got the source code with great effort, and I am publishing just some part of it.
<br /><br />
"It's illegal for third parties to post Microsoft source code," spokesman Tom Pilla said. "We obviously take that very seriously." So, don't tell anybody that you got it from here, just Enjoy ;)
<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>/* Source Code Windows 2000 */

#include "win31.h"
#include "win95.h"
#include "win98.h"
#include "workst~1.h"
#include "evenmore.h"
#include "oldstuff.h"
#include "billrulz.h"
#include "monopoly.h"
#include "backdoor.h"
#define INSTALL = HARD

char make_prog_look_big(16000000);
void main()
{
   while(!CRASHED)
   {
     display_copyright_message();
     display_bill_rules_message();
     do_nothing_loop();

     if (first_time_installation)
       {
       make_100_megabyte_swapfile();
       do_nothing_loop();
       totally_screw_up_HPFS_file_system();
       search_and_destroy_the_rest_of-OS2();
       make_futile_attempt_to_damage_Linux();
       disable_Netscape();
       disable_RealPlayer();
       disable_Lotus_Products();
       hang_system();
       } //if
     write_something(anything);
     display_copyright_message();
     do_nothing_loop();
     do_some_stuff();

     if (still_not_crashed)
     {
     display_copyright_message();
     do_nothing_loop();
     basically_run_windows_31();
     do_nothing_loop();
     } // if
   } //while

   if (detect_cache())
     disable_cache();

   if (fast_cpu())
     {
     set_wait_states(lots);
     set_mouse(speed,very_slow);
     set_mouse(action,jumpy);
     set_mouse(reaction,sometimes);
     } //if

   /* printf("Welcome to Windows 3.1");    */
   /* printf("Welcome to Windows 3.11");   */
   /* printf("Welcome to Windows 95");     */
   /* printf("Welcome to Windows NT 3.0"); */
   /* printf("Welcome to Windows 98");     */
   /* printf("Welcome to Windows NT 4.0"); */
   printf("Welcome to Windows 2000");

   if (system_ok())
     crash(to_dos_prompt)
   else
     system_memory = open("a:\swp0001.swp",O_CREATE);

   while(something)
     {
     sleep(5);
     get_user_input();
     sleep(5);
     act_on_user_input();
     sleep(5);
     } // while
   create_general_protection_fault();

} // main
</pre>
</div>
                <br /><br />
                <a href="http://www.bhatipoglu.com/entry/46/windows-source-codes" target="_blank">Feed users, click here to go to this topic's page. You can find related topics and reference links and you can read the comments for this topic</a>
                <br /><br />
                <a href="/comment.asp?id=46" target="_blank">Feed users, click here to post a comment for this topic</a>
                <br /><br />
                <b>Note: There might be problems about HTML code and parsing and displaying HTML code of your viewer application. Also, there are problems caused by Google Reader on displaying of code samples on the entry. Also, the entry might be updated. So, it is recommended to visit the page of the entry.</b>
                <br /><br />
                ]]>
            </content:encoded>
            <wfw:comment>http://www.bhatipoglu.com/entry/46/windows-source-codes/#comments</wfw:comment>
		</item>
		
        <item>
		    <title>Decode Function in Oracle SQL</title>
		    <link>http://www.bhatipoglu.com/entry/45/decode-function-in-oracle-sql</link>
		    <pubDate>16.09.2007 23:24:21</pubDate>
		    <dc:creator>Bilal Hatipoglu</dc:creator>
		    <category><![CDATA[ SQL-Oracle-PL/SQL ]]></category>
		    <guid isPermaLink="false">http://www.bhatipoglu.com/entry/45/decode-function-in-oracle-sql</guid>
		    <description><![CDATA[
		        The decode function can be used in SQL for and IF-THEN-ELSE construction. It's an alternative for the CASE statement which was introduced in Oracle 8. 
<br /><br />
Decode is a very useful and handy function for Oracle queries. It replaces the complex If-Then-Else logic, which is used to display different things based on different values in a column. This is usually used for pivoting purposes.
		        ]]>
		    </description>
			<content:encoded><![CDATA[
			    The decode function can be used in SQL for and IF-THEN-ELSE construction. It's an alternative for the CASE statement which was introduced in Oracle 8. 
<br /><br />
Decode is a very useful and handy function for Oracle queries. It replaces the complex If-Then-Else logic, which is used to display different things based on different values in a column. This is usually used for pivoting purposes.
<br /><br />
Syntax is like:
<br /><br />
<div class="tac"><img src="http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/img/decode.gif" /></div>
<br /><br />
<pre>DECODE(expr, search, result
             [, search, result ]...
       [, default ]
      )
</pre>
<br /><br />
DECODE compares expr to each search value one by one. If expr is equal to a search, then Oracle Database returns the corresponding result. If no match is found, then Oracle returns default. If default is omitted, then Oracle returns null.
<br /><br />
The arguments can be any of the numeric types (NUMBER, BINARY_FLOAT, or BINARY_DOUBLE) or character types.
<br /><br />
The search, result, and default values can be derived from expressions. Oracle Database uses short-circuit evaluation. That is, the database evaluates each search value only before comparing it to expr, rather than evaluating all search values before comparing any of them with expr. Consequently, Oracle never evaluates a search if a previous search is equal to expr.
<br /><br />
Oracle automatically converts expr and each search value to the datatype of the first search value before comparing. Oracle automatically converts the return value to the same datatype as the first result. If the first result has the datatype CHAR or if the first result is null, then Oracle converts the return value to the datatype VARCHAR2.
<br /><br />
In a DECODE function, Oracle considers two nulls to be equivalent. If expr is null, then Oracle returns the result of the first search that is also null.
<br /><br />
The maximum number of components in the DECODE function, including expr, searches, results, and default, is 255.
<br /><br />
An Example:
<br /><br />
<pre>You could use the decode function in an SQL statement as follows:

SELECT supplier_name, 
decode(supplier_id, 10000, 'IBM', 
 10001, 'Microsoft', 
 10002, 'Hewlett Packard', 
  'Gateway') result 
FROM suppliers; 

The above decode statement is equivalent to the following IF-THEN-ELSE statement:

IF supplier_id = 10000 THEN
     result := 'IBM';

ELSIF supplier_id = 10001 THEN
    result := 'Microsoft';

ELSIF supplier_id = 10002 THEN
    result := 'Hewlett Packard';

ELSE
    result := 'Gateway';

END IF;

The decode function will compare each supplier_id value, one by one.
</pre>
<br /><br />
<b>More Examples:</b>
<br /><br />
<a class="a4" href="/entry/41/decode-demo-1" target="_blank">Decode Demo #1</a><br />
<a class="a4" href="/entry/42/decode-demo-2" target="_blank">Decode Demo #2</a><br />
<a class="a4" href="/entry/43/decode-demo-3" target="_blank">Decode Demo #3</a><br />
<a class="a4" href="/entry/44/decode-demo-4" target="_blank">Decode Demo #4</a>
<br /><br />
<b>DECODE vs. CASE</b>
<br /><br />
CASE can evaluate any expression, but DECODE is limited to compare discrete values. But CASE is more compex, has more code and less readable I think, so if you can do your job with simple DECODE, do it with DECODE.
<br /><br />
Before version 8.1, the DECODE was the only thing providing IF-THEN-ELSE functionality in Oracle SQL. Because DECODE can only compare discrete values (not ranges), continuous data had to be contorted into discreet values using functions like FLOOR and SIGN. In version 8.1, Oracle introduced the searched CASE statement, which allowed the use of operators like > and BETWEEN (eliminating most of the contortions) and allowing different values to be compared in different branches of the statement (eliminating most nesting). In version 9.0, Oracle introduced the simple CASE statement, that reduces some of the verbosity of the CASE statement, but reduces its power to that of DECODE. 
<br /><br />
Another difference is, CASE is an ANSI standard, where as Decode is proprietary for Oracle.
<br /><br />
<b>Then comes 11g!</b>
<br /><br />
Traditional pivoting is done with DECODE and CASE in 10g or earlier. In 11g, there are two new operators: PIVOT and UNPIVOT. They can be used for pivoting. For more information refer to Reference links below.  
                <br /><br />
                <a href="http://www.bhatipoglu.com/entry/45/decode-function-in-oracle-sql" target="_blank">Feed users, click here to go to this topic's page. You can find related topics and reference links and you can read the comments for this topic</a>
                <br /><br />
                <a href="/comment.asp?id=45" target="_blank">Feed users, click here to post a comment for this topic</a>
                <br /><br />
                <b>Note: There might be problems about HTML code and parsing and displaying HTML code of your viewer application. Also, there are problems caused by Google Reader on displaying of code samples on the entry. Also, the entry might be updated. So, it is recommended to visit the page of the entry.</b>
                <br /><br />
                ]]>
            </content:encoded>
            <wfw:comment>http://www.bhatipoglu.com/entry/45/decode-function-in-oracle-sql/#comments</wfw:comment>
		</item>
		
        <item>
		    <title>Hello World!</title>
		    <link>http://www.bhatipoglu.com/entry/40/hello-world</link>
		    <pubDate>16.09.2007 22:32:48</pubDate>
		    <dc:creator>Bilal Hatipoglu</dc:creator>
		    <category><![CDATA[ OFF-Topic ]]></category>
		    <guid isPermaLink="false">http://www.bhatipoglu.com/entry/40/hello-world</guid>
		    <description><![CDATA[
		        A "hello world" program is a computer program that prints out "Hello, World!" on a display device. It is used in many introductory tutorials for teaching a programming language. Such a program is typically one of the simplest programs possible in a computer language.
		        ]]>
		    </description>
			<content:encoded><![CDATA[
			    A <strong>"hello world"</strong> program is a computer program that prints out "Hello, World!" on a display device. It is used in many introductory tutorials for teaching a programming language. Such a program is typically one of the simplest programs possible in a computer language. Some are surprisingly complex, especially in some graphical user interface (GUI) contexts, but most are very simple, especially those which rely heavily on a particular command line interpreter ("shell") to perform the actual output. In many embedded systems, the text may be sent to a one or two-line liquid crystal display (LCD), or some other appropriate signal, such as an LED being turned on, may substitute for the message.
<br /><br />
 
A "hello world" program can be a useful sanity test to make sure that a language's compiler, development environment, and run-time environment are correctly installed. Configuring a complete programming toolchain from scratch to the point where even trivial programs can be compiled and run can involve substantial amounts of work. For this reason, a simple program is used first when testing a new tool chain.
<br /><br />
Here is an "Hello World" program collection that includes <strong>338</strong> Hello World programs in many more-or-less well known programming languages:
<br /><br />
                                                    <a class="a4" href="http://www.roesler-ac.de/wolfram/hello.htm" target="_blank">
http://www.roesler-ac.de/wolfram/hello.htm</a>
<br /><br />
I didn't know there exists that much programming languages :) I think this includes not only the programming languages, but whatever that can write any output to anywhere :) 
<br /><br />
And here is a funny joke from GNU: How the way people code "Hello World" varies depending on their age and job: 
<br /><br />
                                                    <a class="a4" href="http://www.gnu.org/fun/jokes/helloworld.html " target="_blank">
http://www.gnu.org/fun/jokes/helloworld.html
<br />
                                                    </a>
                                                    <br />
The <strong>chief executive</strong> version is really funny, isn't it? :)  
                <br /><br />
                <a href="http://www.bhatipoglu.com/entry/40/hello-world" target="_blank">Feed users, click here to go to this topic's page. You can find related topics and reference links and you can read the comments for this topic</a>
                <br /><br />
                <a href="/comment.asp?id=40" target="_blank">Feed users, click here to post a comment for this topic</a>
                <br /><br />
                <b>Note: There might be problems about HTML code and parsing and displaying HTML code of your viewer application. Also, there are problems caused by Google Reader on displaying of code samples on the entry. Also, the entry might be updated. So, it is recommended to visit the page of the entry.</b>
                <br /><br />
                ]]>
            </content:encoded>
            <wfw:comment>http://www.bhatipoglu.com/entry/40/hello-world/#comments</wfw:comment>
		</item>
		
        <item>
		    <title>Turkcell Staj Günlüğü - 12: Partitioning</title>
		    <link>http://www.bhatipoglu.com/entry/39/turkcell-staj-gunlugu-12--partitioning</link>
		    <pubDate>06.09.2007 12:35:28</pubDate>
		    <dc:creator>Bilal Hatipoglu</dc:creator>
		    <category><![CDATA[ SQL-Oracle-PL/SQL ]]></category>
		    <guid isPermaLink="false">http://www.bhatipoglu.com/entry/39/turkcell-staj-gunlugu-12--partitioning</guid>
		    <description><![CDATA[
		        Merhaba, yine uzun bir aradan sonra staj günlüğüme yazmaya devam ediyorum. Bu, serinin 12. yazısı olacak ve konumuz Ertürk'ün yaptığı partitioning sunumu.
<br /><br />
Turkcell'deki stajımızın sonuna yaklaşıyoruz yavaş yavaş, son haftalarda da gayet yoğun projeler üzerinde uğraşıyorduk herbirimiz. Dolayısıyla yazmaya vaktim olmadı. Stajın benim açımdan (ve sanırım Yazlım Geliştirme departmanındaki diğer arkadaşlar açısından da) çok  keyifli geçtiğini söyleyebilirim. Hepimiz uzun soluklu, gerçek projelerde yer aldık ve kod yazdık. Eğitici sunumlar yaz boyunca devam etti, ediyor. Ve en güzeli de buradaki üst düzey yöneticilerimizle sohbet toplantılarımız oluyor ve onlar da bizimle tecrübelerini paylaşıyorlar. Gerçekten çok keyifli herşey. Burada öğrendiklerimiz ve özellikle yöneticilerimizle sohbetlerimiz binlerce dolar vererek bile kazanılamayacak tecrübelerdi. Turkcell Türkiye'nin en büyük ve en gelişmiş platformarından birine sahip ve böyle bir platformda çalışma, proje geliştirme, analiz yapma imkanını başka bir şekilde veya her zaman bulamazsınız.
		        ]]>
		    </description>
			<content:encoded><![CDATA[
			    Merhaba, yine uzun bir aradan sonra staj günlüğüme yazmaya devam ediyorum. Bu, serinin 12. yazısı olacak ve konumuz Ertürk'ün yaptığı partitioning sunumu.
<br /><br />
Turkcell'deki stajımızın sonuna yaklaşıyoruz yavaş yavaş, son haftalarda da gayet yoğun projeler üzerinde uğraşıyorduk herbirimiz. Dolayısıyla yazmaya vaktim olmadı. Stajın benim açımdan (ve sanırım Yazlım Geliştirme departmanındaki diğer arkadaşlar açısından da) çok  keyifli geçtiğini söyleyebilirim. Hepimiz uzun soluklu, gerçek projelerde yer aldık ve kod yazdık. Eğitici sunumlar yaz boyunca devam etti, ediyor. Ve en güzeli de buradaki üst düzey yöneticilerimizle sohbet toplantılarımız oluyor ve onlar da bizimle tecrübelerini paylaşıyorlar. Gerçekten çok keyifli herşey. Burada öğrendiklerimiz ve özellikle yöneticilerimizle sohbetlerimiz binlerce dolar vererek bile kazanılamayacak tecrübelerdi. Turkcell Türkiye'nin en büyük ve en gelişmiş platformarından birine sahip ve böyle bir platformda çalışma, proje geliştirme, analiz yapma imkanını başka bir şekilde veya her zaman bulamazsınız.
<br /><br />
Bu imkanları bize sağlayan, staj dönemini keyiflendirerek hem Turkcell'e hem de stajyerlere çok büyük katkıda bulunan bu süreci destekleyen herkese (başta Tonguç abi olmaz üzere) teşekkür ediyorum. Neyse şimdilik bu kadar yeter, stajın sonuna doğru daha romantik (:P) şeyler yazmaya devam ederim nasılsa :) Biz Oracle'a dönelim, sonuçta Kategori olarak Oracle yazdık bu makaleyi :) 
<br /><br />
Ertürk'ün parititoning sunumu üzerinden çok zaman geçti, ama hala gözümün önünde sanki :) Ben eğitim odasında kapının önünde, Ertürk'ün sağında oturuyordum. Sunuma da tekrar göz atınca oldukça fazla yazacak şey çıktı yine.
<br /><br />
Öncelikle Ertürk'ün sunumunu <a class="a4" href="/files/tcellstaj/presentation12-erturk-partitioning.rar" target="_blank">buradan indirebilirsiniz.</a> Sunumu ve aşağıda "Links & References" bölümğnde verdiğim linkleri gözden geçirerek en azından başlangıç seviyesinde bir çok şey öğrenebilirsiniz.
<br /><br />
• Partitioning'de de esas amaç her zamanki gibi performans :) Mantık "<strong>Divide
                                                        & Conquer</strong>" (Böl ve fethet)'e dayanıyor. Tabloları partition'lara ayırarak, verileri bir ilişkiye göre gruplayarak, performanstan kazanmak mümkün. Ama elbette belirli koşullarda. Performanstan kazanmanın yanında bir amaç daha var, o da yönetimi kolaylaştırmak. Tabloların yönetimini partitionlarla kolaylaştırmak mümkün. Daha ilerde bahsedeceğimiz Oracle'ın partition'lar için sunduğu çok esnek imkanlar var.
<br /><br />
• Partitioning daha çok Datawarehouse'larda kullanılabilecek bir özellik. Çünkü OLTP sistemlerde zaten az müktarda veri okunur ve genelde indexler yardımıyla veriye zaten hızlı şekilde ulaşırız. Fakat OLAP sistemlerde Full Table Scan(FTS)'ler havalarda uçuşur :)) Bütün tablolar okunarak işlenir, ki bunalr zaten büyük tablolardır. Bizim ihtiyacımız olan bilgiye partitioning yardımıyla çok daha az disk okumasıyla ulaşabiliriz. 
<br /><br />
• Partitioning tipleri var. Bunlardan bir tanesi <strong>Range Partitioning</strong>.
                                                    Mantık çok basit, veriyi belli değer aralıklarına göre gruplamak, bunları farklı partitionlarda saklamak. Örneğin, tarihe göre, her senenin versini farklı bir partition'da tutmak gibi. Bu sayede sadece bir kısım veriye ihtiyacımız olduğunda bütün tabloyu okumaktan kurtulmuş, sadece ihtiyacımız olan partition'ı okumuş oluruz. Bu tür, iş mantığına uyması açısından güzel.
<br /><br />
• Range partitioning'de bir MAXVALUE değeri vermemiz gerekiyor, çünkü her partition belli bir range'e düşmesi lazım.
<br /><br />
• Bir diğer tür de <strong>Hash Partitioning</strong>. Bunda da kullanılan bir hash fonksiyonuna göre veri gruplanıyor. Bu şekilde de okumak istediğimiz verinin kriterini aynı hash'ten geçirerek hangi partition'dan okuaycağımızı anlayabiliyoruz(daha doğrusu Oracle bunu anlayıp hızlı bir şekilde veriyi önümüze getiriyor).
<br /><br />
• <strong>List partitioning</strong> de ise hangi değerlerin hangi partition'a düşeceğini kendimiz liste alinde belirliyoruz. Bu biraz daha custom bir uygulama.
<br /><br />
• <strong>Composite partitioning</strong> ise, Range ile ayrılan partition'lar içinde birlikte list veya hash partitioning'in de kullanılmasıdır. Bunlara subpartition denir.
<br /><br />
• Partition edilmiş tablolarda <strong>local index</strong>ler ve/veya <strong>global
                                                        index</strong>ler olabilir. Local indexler, her partition'ın kendi içindeki indexidir. Global index ise, bütün partitionları yani bütün tabloyu kapsayan indexlerdir. İkisinin de kullanım alanları farklıdır, örneğin partition'lı bir tablo üzerindeki primary key index'i global ve partition'sız olmaz zorunda.
<br /><br />
• Tablolar gibi indexler de partitionlanabilir. Aynı mantıkla, index'i de belli değerlere göre gruplamış oluyoruz partition'layarak.
<br /><br />
• Partitioning, çok faydalı, güzel bir özellik fakat doğru kullanılmadığından çok ciddi sorunlara ve performasn kayıplarına da neden olabiliyor. Partitioning de Oracle'ın sağlamış olduğu güzelliklerden bir tanesi. Bu konuda temel düzeyde bilgi sahibi olup bunu da alet çantamıza atmakta fayda var :) Çünkü çok özel ihtiyaçlar için çok özel çözümler olabiliyor. Bunları önceden kestirmek, bilmek ve uygulamak önemli.
<br /><br />
Ertürk'ün sunumundan notlarım da bu kadardı. 
Hepinize iyi çalışmalar. 
                <br /><br />
                <a href="http://www.bhatipoglu.com/entry/39/turkcell-staj-gunlugu-12--partitioning" target="_blank">Feed users, click here to go to this topic's page. You can find related topics and reference links and you can read the comments for this topic</a>
                <br /><br />
                <a href="/comment.asp?id=39" target="_blank">Feed users, click here to post a comment for this topic</a>
                <br /><br />
                <b>Note: There might be problems about HTML code and parsing and displaying HTML code of your viewer application. Also, there are problems caused by Google Reader on displaying of code samples on the entry. Also, the entry might be updated. So, it is recommended to visit the page of the entry.</b>
                <br /><br />
                ]]>
            </content:encoded>
            <wfw:comment>http://www.bhatipoglu.com/entry/39/turkcell-staj-gunlugu-12--partitioning/#comments</wfw:comment>
		</item>
		
        <item>
		    <title>Examining show_space</title>
		    <link>http://www.bhatipoglu.com/entry/38/examining-show_space</link>
		    <pubDate>13.08.2007 20:20:38</pubDate>
		    <dc:creator>Bilal Hatipoglu</dc:creator>
		    <category><![CDATA[ SQL-Oracle-PL/SQL ]]></category>
		    <guid isPermaLink="false">http://www.bhatipoglu.com/entry/38/examining-show_space</guid>
		    <description><![CDATA[
		        Many people knows the show_space procedure of Tom KYTE. The procedure shows the space issues for an object, given in parameters. Execution of procedure is simple, and statistics are good. But, in AskTom, the show_space procedure has many versions :) and it's hard to know which is the last version. Also, the procedures can thow some errors in some cases and it is sometimes hard to clarify the error. In this topic, I will deal with them and give the code of last-version, running show_space code :)
		        ]]>
		    </description>
			<content:encoded><![CDATA[
			    Many people knows the show_space procedure of Tom KYTE. The procedure shows the space issues for an object, given in parameters. Execution of procedure is simple, and statistics are good. But, in AskTom, the show_space procedure has many versions :) and it's hard to know which is the last version. Also, the procedures can thow some errors in some cases and it is sometimes hard to clarify the error. In this topic, I will deal with them and give the code of last-version, running show_space code :)
<br /><br />
First, let's create the test stuff:

<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>SQL*Plus: Release 10.2.0.1.0 - Production on Mon Aug 13 12:22:17 2007

Copyright (c) 1982, 2005, Oracle.  All rights reserved.

SQL> conn sys@bilalEE as sysdba;

Enter password:

Connected to:
Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Production
With the Partitioning, OLAP and Data Mining options

SQL> create user testspace identified by test;

User created.

SQL> grant resource, connect to testspace;

Grant succeeded.

SQL> conn testspace/test@bilalEE
Connected.
SQL> create table tspace as select * from all_objects;

Table created.

SQL> create table tspace_p partition by hash (owner) as select * from all_objects;

Table created.

SQL>

<a class="a2" target="_blank" href="/files/show_space/p1_1.txt">Download Code</a></pre>
</div>
<br />
So far, we have created a test user called testsapce and two tables in its schema, first, a normal table tspace and a partitioned table tspace_t.

Let's start with the oldest version of show_space that I found on AskTom:

<br /><br />
<div class="code" style="font-size: 8pt;font-family: 'Lucida Sans Typewriter'">
<pre>SQL*Plus: Release 10.2.0.1.0 - Production on Mon Aug 13 12:28:20 2007

Copyright (c) 1982, 2005, Oracle.  All rights reserved.

SQL> conn sys@bilalEE as sysdba;

Enter password:

Connected to:
Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Production
With the Partitioning, OLAP and Data Mining options

SQL> create or replace
  2    procedure show_space
  3    ( p_segname in varchar2,
  4      p_owner   in varchar2 default user,
  5      p_type    in varchar2 default 'TABLE',
  6      p_free   in BOOLEAN default true )
  7    as
  8        l_free_blks                 number;
  9
 10        l_total_blocks              number;
 11       l_total_bytes               number;
 12       l_unused_blocks             number;
 13       l_unused_bytes              number;
 14        l_LastUsedExtFileId         number;
 15        l_LastUsedExtBlockId        number;
 16        l_LAST_USED_BLOCK           number;
 17        procedure p( p_label in varchar2, p_num in number )
 18        is
 19        begin
 20            dbms_output.put_line( rpad(p_label,40,'.') ||
 21                                  p_num );
 22        end;
 23    begin
 24       if (p_free) then
 25        dbms_space.free_blocks
 26        ( segment_owner     => p_owner,
 27          segment_name      => p_segname,
 28          segment_type      => p_type,
 29          freelist_group_id => 0,
 30          free_blks         => l_free_blks );
 31       end if;
 32        dbms_space.unused_space
 33        ( segment_owner     => p_owner,
 34          segment_name      => p_segname,
 35          segment_type      => p_type,
 36          total_blocks      => l_total_blocks,
 37          total_bytes       => l_total_bytes,
 38          unused_blocks     => l_unused_blocks,
 39          unused_bytes      => l_unused_bytes,
 40          LAST_USED_EXTENT_FILE_ID => l_LastUsedExtFileId,
 41          LAST_USED_EXTENT_BLOCK_ID => l_LastUsedExtBlockId,
 42          LAST_USED_BLOCK => l_LAST_USED_BLOCK );
 43
 44        p( 'Free Blocks', l_free_blks );
 45        p( 'Total Blocks', l_total_blocks );
 46        p( 'Total Bytes', l_total_bytes );
 47        p( 'Unused Blocks', l_unused_blocks );
 48        p( 'Unused Bytes