C Objective

1. What is the output of the program given below     
     #include<stdio.h> 
     main() 
     { 
             char i=0; 
             for(;i>=0;i++) ; 
             printf("%d\n",i); 
     } 

Output: -128

2. Which one MUST be correct in the following statements ? 
     a) All Identifiers are keywords 
     b) All Keywords are Identifiers 
     c) Keywords are not Identifiers 
     d) Some keywords are Identifiers 

Output: c


3.How much memory is allocated by the following definition ? 
    int (*x)[10]; 

Output: 4 bytes

4.What is the memory allocated by the following definition ?
   
 int (*x)(); 

Output: 4 bytes

5.What is the Output of the Program ?
   
main() 
   { 
         int i = 1 ; 
         printf(i ?"one" : "zero") ; 
   } 
a) one 
b) zero 
c) error 
d) both and b 

Output: a


6.What is the Output of the Program ? 
   main() 
   {  
       int i = 1 ; 
       printf("%d",i ? 1 : 0) ; 
   } 
a) 1 
b) 0 
c) error 
d) none of the above 

Output: a


7.What is the output for the program given below 
    typedef enum grade{GOOD,BAD,WORST,BAD}; 
    main() 
    { 
           BAD g1; 
           g1=1; 
           printf("%d",g1); 
    } 

Output:
      error (cant define twice BAD)

8.Give the output for the following program.
    
    #define STYLE1 char 
    main() 
    { 
          typedef char STYLE2; STYLE1 x; 
          STYLE2 y; 
          clrscr(); 
          x=255; 
          y=255; 
          printf("%d %d\n",x,y); 
     } 

Output: -1-1

9.Which of 'Arrays' or 'pointers' are faster ?
    
    a) Arrays 
    b) pointers 
    c) Both take same time 
    d) Can't say 

Output: a


10.In the following program 
     #include<stdio.h> 
     main() 
     { 
          char *pDestn,*pSource="I Love India"; 
          pDestn=malloc(strlen(pSource)); 
          strcpy(pDestn,pSource); 
          printf("%s",pDestn); free(pDestn); 
     } 
    a) Free() fails 
    b) Strcpy() fails 
    c) prints I love India <Garbage> 
    d) error

Output: c

Recursion

It is a function that once called in main function will call itself until the exit condition is satisfied.
Program to find factorial of a number using recursion. 
           #include<stdio.h> 
           void main() 
           { 
                    int n,res; 
                    printf("enter the no "); 
                    scanf("%d",&n); 
                    res=fact(n); 
                    printf("Factorial is:%d",res); 
           } 
           int fact(int n) 
           { 
                    if((n== 1)||(n==0)) 
                           return 1; 
                    else 
                           return(n*fact(n-1)); 
           } 

Working:
              If n=5 
                       5*fact(4) 
                       4*fact(3) 
                       3*fact(2) 
                       2*fact(1) 
                       1*fact(0) 
output=120 

Advantages: 
  • Reduces the code size. 
  • Represents compact programming. 
Disadvantages: 
  • Exit condition is a must for recursive statements else leads to stack overflow. 
  • Slower than looping statements. 

Function calls also have memory requirements. They need to store values for parameters, local variables, and an address for a return value. This memory comes from the stack during the function execution. After the function has completed, the memory is released back to the stack. 

During recursion, function calls continue to require more and more stack memory which does not get released until the recursive chain terminates. Stack overflow results when memory allocations are beyond what the stack is able to provide. So if a function has too many levels of recursive calls, one can run out of memory.
In general, a recursive function will consume more stack space (since it's really a large set of function calls), while an iterative solution won't. This also means that an iterative solution, in general, will be fast. 
Conclusion:
Recognize that recursion has its costs and cannot be used without boundaries.

Function Pointers

Function Pointers: A function pointer is a variable which is used to hold the starting address of a functions and the same can be used to invoke a function. It is also possible to pass address of different functions at different times thus making the function more flexible and abstract. 

So the function pointers can be used to simplify code by providing a simple way to select a function to execute based on run-time values. Function pointers do always point to a function having a specific signature. Thus, all functions used with the same function pointer must have the same parameters and return type.


Uses of Function Pointers:
  • Function pointers are the only way for "Interrupt programming". In UNIX all the Interrupts are called using function pointers. This is mainly used in system programming. 
          If a process wishes to handle certain signals then in the code, the process has to register 
          a signal handling function to the kernel. 
          The following is the prototype of a signal handling function :
           void <signal handler funcname> (int sig)

          The signal handler function has void return type and accepts a signal number            
           corresponding to the signal that needs to be handled. 

          To get the signal handler function registered to the kernel, the signal handler function            
           pointer is passed as second argument to the ‘signal’ function. 
          The prototype of the 
            signal function is : void (*signal(int signo, void (*func )(int)))(int);

  • One of the major application of the function pointer is call back function. 
          A callback is done just like a normal function call would be done: You just use the name of 
          the function pointer instead of a function name. 
          void qsort( ... , int(_USERENTRY *cmpFunc)(const void*, const void*))
          {
                  /* sort algorithm - note: item1 and item2 are void-pointers */
                          int bigger=cmpFunc(item1, item2); // make callback
                 /* use the result */
          }

  • Function pointer is also used in function pointer table. 
          #include <stdio.h>
          #include <stdlib.h>
          void f1(void);
          void f2(void);
          void f3(void);
          void f4(void);
          int main(void)
          {
                    void (*table[])(void)={&f1,&f2,&f3,&f4}; /* table of function pointers */
                    void (**p)(void); /* pointer to a function pointer */
                    p=table;
                    while(1)
                   {
                               (*(*p))(); /* Call function @p */
                               ++p;
                    };
          }
         void f1(void){puts("F1 CALLED");return;};
         void f2(void){puts("F2 CALLED");return;};
         void f3(void){puts("F3 CALLED");return;};
         void f4(void){puts("F4 CALLED"); exit(0);};

  • A function pointer is used to pass a function as an argument to another function, or to store a function as a data item, for example a list of functions can be implemented as an array of pointers to functions 
         Passing Function Pointer as an argument
               #include <stdio.h>
               #include<stdlib.h> 
               void joy(int (*debug) () ) 
               { 
                     Debug(“joy\n”); 
               } 
               Int main() 
               { 
                     joy(printf); 
               } 
         
         Calling the function using Function Pointer
               #include<stdio.h> 
               int func (int a, int b)                
               { 
                      printf("\n a = %d\n",a); 
                      printf("\n b = %d\n",b); 
                     return 0; 
                } 
               int main(void) 
                { 
                       int(*fptr)(int,int); // Function pointer 
                       fptr = func; // Assign address to function pointer 
                       func(2,3); 
                       fptr(2,3); 
                     return 0; 
                 } 
          Output: a = 2;b = 3; 
                       a = 2;b = 3;

Loops

LOOPS: 
  • For loop
  • while loop
  • do while loop
To execute a set of instructions repeatedly until a particular condition is being satisfied.

For Loop:
       
       The for is usually appropriate for loops in which the initialization and increment are single  
       statements and logically related, since it is more compact than while and it keeps the loop 
       control statements together in one place. 

Syntax:
        
          for (expr1; expr2; expr3) 

Example program using for loop: 
       main() 
       { 
            int counter,a[10]; 
            for(counter=0;counter<10;counter++) 
            { 
                     printf(“Enter a[%d]=”,counter); 
                     scanf(“%d\n”,a[counter]); 
            } 
           printf(“Array elements:”); 
           for(counter=0;counter<10;counter++) 
                  printf(“%d”,a[counter]); 
       } 

Explanation:
        
         In above program array a length 10.It occupies 20 bytes in memory. 
         Counter is normal integer variable. It is used to read and display the array values. 
         First FOR LOOP is used to read the array values. 
         Second FOR LOOP is used to display the array values. In this second FOR LOOP using 
         one line. So, no need of brace brackets 

While Loop: 
The expression is evaluated. If it is non-zero, statement is executed and expression is reevaluated. 

This cycle continues until expression becomes zero, at which point execution resumes after statement.

Syntax:
        
          while (expression) 
              statement 
Example program using while loop: 
       main() 
       { 
              intcounter,a[10]; 
              counter=0; 
              while(counter<10) 
              { 
                      printf(“Enter a[%d]=”,counter); 
                      scanf(“%d\n”,a[counter]); 
                      counter+=1; 
              } 
             printf(“Array elements:”); 
             counter=0; 
             while(counter<10) 
             { 
                     printf(“%d”,a[counter]); 
                     counter+=1; 
            } 
       } 

Explanation:
 In above program array a length 10.It occupies 20 bytes in memory. 
Counter is normal integer variable. It is used to read and display the array values. 

Before using counter variable to initialize counter. Then use it in WHILE LOOP.
First WHILE LOOP is used to read the array values. 
Second WHILE LOOP is used to display the array values. 

Do While Loop: 
       In do while loop first execute the statements then it checks the condition. 

Syntax:
        do{ 
                 Statement1; 
                  ... 
                 Statement n; 
             }while(condition); 

Example program using for loop:
        main() 
        { 
                 int counter; 
                 counter=0; 
                 do 
                 { 
                        printf(“%d”,counter); 
                  }while(counter>0); 
         } 
 

Conclusion:
In FOR LOOP:          No need to initialize variable before the LOOP 
In WHILE LOOP: 
          To initialize the variable before the LOOP 
           Increment/decrement the variable within the LOOP 
In DO WHILE LOOP: 
           Once it execute If the condition is TRUE/FALSE. 
     

1.What is the difference between while loop and for loop in C language?

while loop - used for looping until a condition is satisfied and when it is unsure how many times the code should be in loop
for loop - used for looping until a condition is satisfied but it is used when you know how many times the code needs to be in loop

Enum Variables

Enumeration (enum): An enum is a user-defined type consisting of a set of named constants called enumerators. 
For e.g.the colors of the rainbow would be mapped like this 

         enum rainbowcolors
         {
           Red, 
                      Orange, 
                      Yellow, 
                      Green, 
                      Blue, 
                      Indigo, 
                      Violet 
         }; 

Now internally, the compiler will use an int to hold these and if no values are supplied, red will be 0, orange is 1 etc. It maintains a table containing data, mapped with an integer associated with it.

Enumerators are stored by compiler as an integers: by default, first enumerator is 0, next enumerator value is previous enumerator value + 1.


You aren't stuck with these compilers generated values; you can assign your own integer constant to them as shown here.

         enum rainbowcolors
         { 
                       Red=1, 
                       Orange=2, 
                       Yellow=3, 
                       Green=4, 
                       Blue =8, 
                       Indigo =8, 
                       Violet =16
         } ; 

Having blue and indigo with the same value isn't a mistake as enumerators might include synonyms such as scarlet and crimson.


Enum Declaration:           
 In C, the variable declaration must be preceded by the word enum as in 
                     enum rainbowcolors trafficlights= red; 

C++ has enumeration types that are directly inherited from C's and work mostly like these, except that an enumeration is a real type in C++, giving additional compile-time checking. Also (as with structs) the C++ "enum" keyword is automatically combined with a "typedef", so that instead of calling the type "enum name", one simply calls it "name."
This can be simulated in C using a typedef: "typedef enum {TYPE1, TYPE2} name;"

Advantages: 

  • They restrict the values that the enum variable can take. 
  • They force you to think about all the possible values that the enum can take. 
  • They are a constant rather than a number, increasing readability of the sourcecode.