Showing posts with label C Tutorial. Show all posts
Showing posts with label C Tutorial. Show all posts

Wednesday, September 2, 2009

Quick Tips for Loop Statement in C programming

  1. there are three types of loop such as a) for loop b) while loop and c)do-while loop the purpose of each loop are same ( to repeat some part of the program) . but why there are three type of  loop:


a)      for loop : if the loop will continue finite number of times.
b)      While loop: if the loop will continue unknown number of times .
c)      Do..while loop: if the loop will continue at least one.

  1. zero (0) evaluate to false .

  1. if 0 is used as an expression in while loop , the condition is false and loop does not executed.
  2. If 0 is used as an expression in do while the condition is false and loop execute at least once.
  3. If 0 is used as an expression in for loop the condition is false and loop is execute at least once and it is equivalent to do .. while loop.

  1. if we drop all part of the for loop it is infinite loop , and drop all parts of while  and do …while loop is an error.
  2. break statement used only with switch statement and loop statement.
  3. Terminated with semicolon(;) in for loop is infinite loop , and in while loop it is infinite and in do...while loop it is compulsory.
  4. Dropping {} in for loop is not infinite , in while it is infinite but in do while it is necessary and infinite.
  5. the frequent variable only used with loop constant.
  6. use register keyword in frequent used of variable .
     for example : register int i;
                              for(i=0;i<=100;i++)

                                                printf(“%d”,i);
  1.  for loop is pre tested , while is pre tested where as do…while is post tested .for an example: for (;8<2;)>
  2. there are three important factors are necessary for any type of loop .

a.       start value
b.      stop value
c.       step value

  1. if we drop the step value it is an infinite loop.
  2. if the loop counter value is beyond of its range then that loop is infinite loop.
  3. function recursion is the replacement of loop.  

Switch Case using tips in c programming

  1. if the case match with an expression execution start from the case.

Example : void main()
{
  int x=2;
 switch(x)
 {
  case 1:
printf(“one”);
  break;
 case 2:
printf(“two”);
 break;
 }
}

  1. if none of the case are satisfied then the default case is satisfied

example : void main()
                        int x=102;
                        switch(x)
                        {
                                    case 10: printf(“ I am a reader”);
                                    case 11:printf(“I am writer”);
                                    default: printf(“I am programmer”);
}





3.case character must be integral constant.
4.break is used to prevent the falling of control from one case to another case


5. case can in any order.
 6.In the switch statement , the keyword ‘continue ‘ cannot be used in place of ‘break’. The compiler will generate an error message . the use of continue will not take the control to the beginning of switch as one is likely to believe.

7.duplicate case is not allowed.

8. the default case is optional . if there is no match case and there is no default case , then the compiler does not report the error.
9.case character can be constant or constant expression but not variable.

10. if 0 is given as an argument in if , while and do-while , it  evaluates to false but in switch it evaluates as an expression.

11. switch case used for menu driven program

using tips If-Else statement in C programming

  1. if the expression is evaluated with true then it is replace with 1 otherwise  replaced with 0.

Example : if( 5>3)
                 Printf(“YES”);
                        Else
                 Printf(“no”);
  1. if multiple statement are given in the if expression the order of evaluation is form left to right.

Example  int a=5;
                If (a++ ,a=a-5,a--;a)
                  Printf(“yes”);
                Else
                        Printf(“NO”);
3.Nested if can be replace with logical && operator
   Example :-
       Int a=1,b=2,c=3;
      If(a==1)
   If(b==2)
If(c==3)
 Printf(“BOSS”);

  1. ternary operator (?:) sometimes replaced the if statement .

example : if (a>65)
  printf(“hi”;
else
 printf(“bye”);

using ternary operator:
a>65?printf(“hi”);printf(“bye”);
  1. hanging if is not allowed , and it always cause an error misplaced else

       example:
   if(6>2)
printf(“yes”);
printf(“no”);
else

printf(“bye”);

  1. ‘else ‘ is optional part of the if statement

  1. else(:) is compulsory in conditional operator .

example :
 64>3 ? printf(“yes”) : printf(“”);

  1. nested if is differ from multiple if

example :
nested if

int a=1,b=2,c=3;
if(a==1)
if(b==2)
if(c==3)
printf(“BOSS”);

multiple if
int avg=75;
if(( avg>=60)
printf(“first”);
if (avg>=40 && avg<60)

   printf(“second”);
if(avg>=30 && avg<40)


  1. There are other conditional statement like #if , #else , #elseif etc used with preprocessor directive
  2. alwaysuse the “else  if” instead of multiple if.

Int avg=75;
If(avg>=60)
 Printf(“first”);
If(avg>=40 && avg<60)

 Printf(“second”);
If (avg>= 30 && avg<40)>


Use else if

Int avg=75;
If(avg>=60)
 Printf(“first”);
Else If(avg>=40 )
 Printf(“second”);
Else (avg>= 30 )
…………..


            

c programming operator using tips

1.      Precedence decides which operator should be perform first

         Example:-
          P = 6 / 2 + 4 * 3

            (Operator /  and  * enjoy same priority  so it is evaluated from  Left to Right)

          P = 6 / 2  + 4 * 3   [ Operation  of   / ]

          P = 3 +  4 * 3        [ Operation of *]
     
          P = 3 + 12            [ Operation of +]
  
          P =  15
      2. Associative determine the order of evaluation

3. Left to Right  & Right to left are two associative rules used when two or more than two same  operators enjoy the same Priority.
4. There is no operators in C to find out the value of “ A  raised to  power B”.
5. comma ( ,) operator is the lowest priority form the group of 45 operator.
6. parenthesis ( ), [], . and -> having highest priority from group of 45 operators .
7. Sizeof( ) is an operator and a keyword which look like function.
8. Modules ( %) is an operator that works with only integral type.
 Example:-
      Float x ;
     X = 10.0 % 3 ;
     Printf(“ %f ”, x);  //( wrong approach )
 Int x ;
X = 10 / 3 ;
Printf ( “%d”, x) ;  // right approach

9. C does not allow “culprits”  such as ** ,//
  example :
int a=4;
a**;
printf(“%d”, a);

10. unary operator (++,--) Can apply to variable not to constants.
11.unary operator plus (+) is dummy operator.
    Int a=6;
   +a;
printf (“%d”,a);

12. some time ternary operator (?:) replace the conditional if statement.

Like  example:-
Int a=6;
If(a>5)
 Printf(“hello”);
Else
Printf(“hi”);

(a>=5)?printf(“hello”):printf(“hi”);

13.comma and parenthesis are twin brothers.

Example :

While ( (P=getch() )!= EOF)
While ( p=getch() ,!=EOF )
14. Return Keyword cannot be used with ternary operator (?:)
  void main()
  {
 int p=5;
p>65540? Return1 : return 0;
}

15.the bit wise operator work with only integer and character .

16. continuous triple plus (+++) is allowed but not more or less.
  For example:
   Int a=3 b;
    B = a+++5; // means b = a ++ + 5  which is 8

17.      More then one + is allow in same statement but space matter a lot between operator .
18.      ## operator helps to concatenate between tokens

#define m (x) printf(“yes %d”, a##x)
void main()
{
int a1=32;
int a2=30;
m(1);
m(2);
}
19.      Turboc used many punctuation know as separators like (), [],.. etc.
20.      caste operator is an operator which is a signal (force) to compiler to convert one caste to other caste .

         example :-  float x; x =  (float) 5/2;
 21. all operators in C can be overload in c++ but except ?: , .* :: etc



 
      

Thursday, January 15, 2009

Standards and Style for Coding in ANSI C

Standards and Style for Coding in ANSI C

  1.   Overview
  2.   ANSI Standard C
  3.   Fighting With C
  4.   Comments
  5.   Source File Organization
  6.   Declarations and Types
  7.   Use of the Preprocessor
  8.   Naming Conventions
  9.   Indentation and Layout
  10.   Expressions and Statements
  11.   Functions
  12.   Complexity and Performance
  13.   The Standard Library
  14.   Further Reading

Tuesday, January 13, 2009

Solitaire game Coding in C Language

#include
#include
#include
#include

this thing only do is generate the number:

int random(int x)
{
srand((int) time(NULL));
return 1 + rand() % x;
}

and this, the colors:
void cardcolr(int naipe,int cardwcolr)
{
if (naipe == 1) // Hearts
{
switch(cardwcolr)
{
case 1:
textcolor(LIGHTRED);
printf(" A\3");
break;
case 11:
textcolor(LIGHTRED);
printf(" J\3");
break;
case 12:
textcolor(LIGHTRED);
printf(" Q\3");
break;
case 13:
textcolor(LIGHTRED);
printf(" K\3");
break;
default:
textcolor(LIGHTRED);
printf(" %d\3",cardwcolr);
}
}
if (naipe == 2) // Spades
{
switch(cardwcolr)
{
case 1:
textcolor(BLACK);
printf(" A\6");
break;
case 11:
textcolor(BLACK);
printf(" J\6");
break;
case 12:
textcolor(BLACK);
printf(" Q\6");
break;
case 13:
textcolor(BLACK);
printf(" K\6");
break;
default:
textcolor(BLACK);
printf(" %d\6",cardwcolr);
}
}
if (naipe == 3) // Diamonds
{
switch(cardwcolr)
{
case 1:
textcolor(LIGHTRED);
printf(" A\4");
break;
case 11:
textcolor(LIGHTRED);
printf(" J\4");
break;
case 12:
textcolor(LIGHTRED);
printf(" Q\4");
break;
case 13:
textcolor(LIGHTRED);
printf(" K\4");
break;
default:
textcolor(LIGHTRED);
printf(" %d\4",cardwcolr);
}
}
if (naipe == 4) // Clubs
{
switch(cardwcolr)
{
case 1:
textcolor(BLACK);
printf(" A\5");
break;
case 11:
textcolor(BLACK);
printf(" J\5");
break;
case 12:
textcolor(BLACK);
printf(" Q\5");
break;
case 13:
textcolor(BLACK);
printf(" K\5");
break;
default:
textcolor(BLACK);
printf(" %d\5",cardwcolr);
}
}
}

Thursday, November 20, 2008

PN - Polish Notation & RPN - Reverse Polish Notation

Polish Notation
--------------------
The method of writing all operators either before their operation, or after them, is called Polish notation, in honor of its discoverer, the Polish mathematician Jan Lukasiewicz. When the operators are written before their operands, 
it is called the prefix form. 
When the operators come after their operands. It is called the postfix form, or, sometimes reverse Polish form or suffix form

In this context, it is customary to use the coined phrase infix form to denote the usual custom of writing binary operators between their operands.                                              
For example, the expression A + B becomes +AB in prefix form and AB+ in postfix form. 

In the expression A + B x C, the multiplication is done first, so we convert it first, obtaining first A + ( BCx ) and then ABCx+ in postfix form

The prefix form of this expression is +A x BC. The prefix and postfix forms are not related by taking mirror images or other such simple transformation. Also all parentheses have been omitted in the Polish forms.

How C programming compiler stores float values ?

How does C compiler stores float values ?


Ans: In C, the float values are stored in a mantissa and exponent form. While writing a number we specify the exponent part in the form of base 10. But, in case of C compiler, the exponent for floats is stored in the form of base 2. 
Obviously, because, computer stores the numbers in binary form. 
The C compiler follows an IEEE standard to store a float. The IEEE format expresses a floating-point number in a binary form known as `normalized' form. Normalization involves adjusting the exponent so that the "binary point" (the binary analog of the decimal point) in the mantissa always lies to the right of most significant nonzero digit. In binary representation, this means that the most significant digit of the mantissa is always a 1. This property of the normalized representation is exploited by the IEEE format when storing the mantissa. Let us consider an example of generating the normalized form of a floating point number. Suppose we want to represent the decimal number 5.375. Its binary equivalent can be obtained as shown below:

2 | 5
.375 x 2 = 0.750 0
|------
.750 x 2 = 1.500 1
2 | 2 1
.500 x 2 = 1.000 1
|------
2 | 1 0
|------
| 0 1

Writing remainders in reverse writing whole parts in the same order we get 101 order in which they are obtained we get 011 thus the binary equivalent of 5.375 would be 101.011. The normalized form of this binary number is obtained by adjusting the exponent until the decimal point is to the right of most significant 1. In this case the result is 1.01011 x 22. The IEEE format for floating point storage uses a sign bit, a mantissa and an exponent for representing the power of 2. The sign bit denotes the sign of the number: a 0 represents a positive value and a 1 denotes a negative value. The mantissa is represented in binary. Converting the floating-point number to its normalized form results in a mantissa whose most significant digit is always 1. The IEEE format takes advantage of this by not storing this bit at all. The exponent is an integer stored in unsigned binary format after adding a positive integer bias. This ensures that the stored exponent is always positive. The value of the bias is 127 for floats and 1023 for doubles. Thus, 1.01011 x 22 is represented as shown below:

--- --------------- ----------------------------------------------
| 0 | 100 0000 1 | 010 1100 0000 0000 0000 0000 |
--- ---------------- ---------------------------------------------

sign bit exponent- mantissa stored in normalized form obtained after adding a bias
127 to exponent 2

Types Sorting method

 best sorting method

Ans: There is no sorting method that is universally superior to all others. The programmer must carefully examine the problem and the desired results before deciding the particular sorting method. Some of the sorting methods are given below:

Bubble sort : When a file containing records is to be sorted then Bubble sort is the best sorting method when sorting by address is used.

Bsort : It can be recommended if the input to the file is known to be nearly sorted.

Meansort : It can be recommended only for input known to be very nearly sorted.

Quick Sort : In the virtual memory environment, where pages of data are constantly being swapped back and forth between external and internal storage. In practical situations, quick sort is often the fastest available because of its low overhead and its average behavior.

Heap sort : Generally used for sorting of complete binary tree. Simple insertion sort and straight selection sort : Both are more efficient than bubble sort. Selection sort is recommended for small files when records are large and for reverse situation insertion sort is recommended. The heap sort and quick sort are both more efficient than insertion or selection for large number of data.

Shell sort : It is recommended for moderately sized files of several hundred elements.

Radix sort : It is reasonably efficient if the number of digits in the keys is not too large.

Information Hiding in C programming language

Information Hiding in C
-----------------------------

Though C language doesn't fully support encapsulation as C++ does, there is a simple technique through which we can implement encapsulation in C. The technique that achieves this is modular programming in C. Modular programming requires a little extra work from the programmer, but pays for itself during maintenance. To understand this technique let us take the example of the popular stack data structure. There are many methods of implementing a stack (array, linked list, etc.). Information hiding teaches that users should be able to push and pop the stack's elements without knowing about the stack's implementation. A benefit of this sort of information hiding is that users don't have to change their code even if the implementation details change.

Consider the following scenario:
To be able to appreciate the benefits of modular programming and thereby information hiding, would first show a traditional implementation of the stack data structure using pointers and a linked list of structures. The main( ) function calls the push( ) and pop( ) functions.


#include 
typedef int element ;
void initialize_stack ( struct node ** ) ;
void push ( struct node **, element ) ;
element pop ( struct node * ) ;
int isempty ( struct node * ) ;
struct node
{
element data ;
struct node *next ;
} ;
void main( )
{
struct node *top ;
element num ;
initialize_stack ( &top ) ;
push ( &top, 10 ) ;
push ( &top, 20 ) ;
push ( &top, 30 ) ;
if ( isempty ( top ) )
printf ( "\nStack is empty" ) ;
else
{
num = pop ( top ) ;
printf ( "\n Popped %d", num ) ;
}
}
void initialize_stack ( struct node **p )
{
*p = NULL ;
}
void push ( struct node **p, element n )
{
struct node *r ;
r = ( struct node *) malloc ( sizeof ( struct node ) ) ;
r -> data = n ;
if ( *p == NULL )
r -> next = NULL ;
else
r -> next = *p ;
*p = r ;
}
element pop ( struct node *p )
{
element n ;
struct node *r ;
n = p -> data ;
r = p ;
p = p -> next ;
free ( r ) ;
return ( n ) ;
}
int isempty ( struct node *p )
{
if ( p == NULL )
return ( -1 ) ;
else
return ( 0 ) ;
}

Notice how the specific implementation of the data structure is strewn throughout main( ). main( ) must see the definition of the structure node to use the push( ), pop( ), and other stack functions. Thus the implementation is not hidden, but is mixed with the abstract operations.



Priority queue - Data Structures

What is a priority queue?

Ans: As we know in a stack, the latest element is deleted and in a queue the oldest element is deleted. It may be required to delete an element with the highest priority in the given set of values and not only the oldest or the newest one. A data structure that supports efficient insertions of a new element and deletions of elements with the highest priority is known as priority queue. There are two types of priority queues: an ascending priority queue is a collection of items into which items can be inserted arbitrarily and from which only the smallest item can be removed. A descending order priority queue is similar but allows only the largest item to be deleted.

Garbage collection - System Utility( programming language)

System Utility
What is garbage collection?

Ans: Suppose some memory space becomes reusable because a node is released from a linked list. Hence, we want the space to be available for future use. One way to bring this about is to immediately reinsert the space into the free-storage list. However, this method may be too time-consuming for the operating system. The operating system may periodically collect all the deleted space onto the free-storage list. The technique that does this collection is called Garbage Collection. Garbage Collection usually takes place in two steps: First the Garbage Collector runs through all lists, tagging whose cells are currently in use, and then it runs through the memory, collecting all untagged space onto the free-storage list. The Garbage Collection may take place when there is only some minimum amount of space or no space at all left in the free-storage list, or when the CPU is idle and has time to do the collection. Generally speaking, the Garbage Collection is invisible to the programmer.

Hashing or hash addressing (Searching Technique)

Data Structures
Hashing...

Hashing or hash addressing is a searching technique. Usually, search of an element is carried out via a sequence of comparisons. Hashing differs from this as it is independent of the number of elements n in the collection of data. Here, the address or location of an element is obtained by computing some arithmetic function. Hashing is usually used in file management. The general idea is of using the key to determine the address of a record. For this, a function fun( ) is applied to each key, called the hash function. Some of the popular hash functions are: 'Division' method, 'Midsquare' method, and 'Folding' method. Two records cannot occupy the same position. Such a situation is called a hash collision or a hash clash. There are two basic methods of dealing with a hash clash. The first technique, called rehashing, involves using secondary hash function on the hash key of the item. The rehash function is applied successively until an empty position is found where the item can be inserted. If the hash position of the item is found to be occupied during a search, the rehash function is again used to locate the item. The second technique, called chaining, builds a linked list of all items whose keys hash to the same values. During search, this short linked list is traversed sequentially for the desired key. This technique involves adding an extra link field to each table position.

Blog List