Friday, 16 March 2012

Functions


Definition
Features of functions
Types of functions
Syntax
Category of Functions

Functions Definition:

It is a collection of executable statements which performs a specific operation is called functions

Features of Functions:
  • We can achieve Modularity by using functions. Modularity means Process of taking a larger problem (software or program), understanding it, and then breaking it into smaller, more manageable parts.
  • Each part, called a module (task i.e function), has its own well-refined task.
  • All modules work through a central module, called main.
  • Reusability Code.
Types of functions:

1. Predefined Functions (Library Functions or Built-in Functions)
2. User Defined Function




Predefined functions are provided by the system (at the time of C software installation will be available automatically) and available in Library.

Ex: scanf(), printf(), sqrt(),exit(0),...

How to use Predefined Functions in your program?
Include appropriate header files before calling the functions.
Ex:
#include<stdio.h> //this is header
void main()
{
 printf("I'm predefined function\n");
}


double sqrt(double) ;

present in <math.h> that computes the square root of the argument passed to it.

2. User Defined Function:

Now we are talking about the user defined functions. Which is defined by the user or programmer is called user defined function.

Parts of a function

1. Function Declaration or Function Prototype
2. Function Definition
3. Function Call

1. Function Declaration or Function Prototype

Syntax (or) Function defination:

return_type  function_name(arguments (optional))
{
  //body of the function
  statements;
  statements;
  return statement; //optional
}

Ex:
int add(int a,int b)
{
  int c;
  c=a+b;
  return(c);
}

3. Function Call:

void main()
{
 int add(int,int);
 int a,b,c;
 a=2;
 b=3;
 c=add(a,b); //calling function
 printf("c=%d\n",c);
}

There are two ways of calling the function or
Communication with Function:

When we are calling the function, we can pass (send) arguments or parameters in function call to the function definition in two ways:

1. Call by Value 
2. Call by Reference

Call By Value:

Actual parameters are to the function. Whatever the modifications are done in function, those changes are not reflects in calling function.

Ex: add(a,b);
Example Program:
void main()
{
 int add(int,int);
 int a,b,c;
 a=2;
 b=3;
 c=add(a,b); //calling function
 printf("c=%d\n",c);
}
int add(int a,int b)
{
  int c;
  c=a+b;
  return(c);
}

Call By Reference:

Addresses of the parameters are copied to the function. Whatever the modifications are done in function, those changes are reflects in calling function.

Use & (ampersand) operator is used in the actual parameter.
Advantages of the call by reference we can send more than one value from the function to calling function.

Ex: swap(&a,&b);

Example Program:
void main()
{
 void swap(int *,int*);
int a,b;
a=2;
b=3;
swap(&a,&b);
printf("a=%d\nb=%d\n",a,b);
}
void swap(int *x,int *y)
{
 int temp=x;
 x=y;
 y=temp;
}




Interview Questions

Is it possible to execute code even after the program exits the main() function?              
What is the difference between the functions rand(),random(),srand() and randomize()?           
How to see return value of main function?         
How do we get Square root of any number Without using sqrt() function?          
Write a Program to convert decimal to binary no.             
Can you use the function fprintf()to display the output on the screen? 
What is a static function?             
How to print a statement without using printf() in c?      
How would you use bsearch()function to search a name stored in array of pointers to string?    
Does there exist any other function which can be used to convert an integer or a float to a string          
Have you heard of "mutable" keyword?              
What is an argument ? differentiate between formal arguments and actual arguments?               
Differentiate between a linker and linkage?       
Is using exit() the same as using return?               
Why should I prototype a function?       
What is meant by malloc function           
How can send unlimited no of arguments to a function, eg printf function can take any no of arguments              
What is the purpose of main( ) function?             
How would you use the functions randomize()and random()?   
How to convert decimal to octal and hexadecimal in c program?

Monday, 12 March 2012

Pointers

Definition: pointer is variable which stores the address of the existing variable/array/pointer/structure/union.


What is pointer? List the advantages of pointers

Ans:

1.       We can return more than one value from a function
2.       Indirect accessing
3.       It provides dynamic memory management
4.       To pass arrays and strings more conveniently from one function to another function
5.       It provides program execution speed
6.       To manipulate arrays more easily by moving pointers to them instead of moving the arrays themselves

#include<stdio.h>
#include<conio.h>
void main()
{
 int a;
 int *p;
 p=&a;
 printf("enter any value\n");
 scanf("%d",&a);
 printf("Indirect accessing of a=%d\n",*p);
 printf("Direct accessing of variable a=%d\n",a);
 printf("Address of variable a %u\n",&a);
 printf("value of pointer p=%u\n",p);
 getch();
}
/*
Output:
enter any value a=4;
Indirect accessing of variable a=4
Direct accessing of variable a=4
Address of variable a =1000
value of pointer p=1000
*/

Difference between address operator and dereference operators?

Address operator
Dereferencing operators
1.       Address operator is &
Ex: &a where a is a variable
Dereferencing operator is *
Example: *a where a is pointer
2.       It is used to initialize pointer variable

It is used to declare a pointer varialbe

3.       It is a unary operator
It is also unary operator
4.       It returns the address of variable
It returns the value at that address

Difference between Pointer and Array?
A pointer variable is one that holds an address and can be changed to point to another object of the pointer’s type.

An Array name is interpreted as  the base address of the array which can not be changed.  It is a Pointer constant.


Size of Pointer:

Size of any pointer is 2 bytes, irrespective of types
Sizeof(int *)=2 bytes
Sizeof(float*)=2 bytes

---------------------------------------------------------------------------------------------------------------                                 Interview Question on Pointers

1. When do you use Pointers?

we use pointer to function when
1.we want to pass address in function
2.in case of array we can access whole array in function's definiton by passing it's base address



1. What does it mean when a pointer is used in an if statement?
2. When would you use a pointer to a function?
3. Why should we assign NULL to the elements (pointer) after freeing them?
4. What is file pointer and its working method?
5. What is indirection?
6. Following declarations are same const char *s; char const *s;
7. Difference between :- 1) NULL pointer and NULL macro ?
8. What is the difference between far and near?
9. In the following code, what is p2? typedef int* ptr ptr p1, p2;
10. Write a c program to find out the area of a circle using pointer. 11. Why should we assign NULL to the elements (pointer) after freeing them ?
12. What do you mean by normalisation of pointers
13. What is a void pointer?
14. Between a long pointer and a char pointer , which one consumes more memory? explain
15. Can you add pointers together? Why would you?
16. How I can add two numbers in c language without using Arithmetic operators?
17. How reliable are floating-point comparisons?
18. Difference between arrays and pointers?
19. What are the disadvantages of using Pointers.
20. What is a pointer value and address?
21.How many levels of pointers can you have?
The answer depends on what you mean by "levels of pointers." If you mean "How many levels of indirection can you have in a single declaration?" the answer is "At least 12."
int i = 0;
int *ip01 = & i;
int **ip02 = & ip01;
int ***ip03 = & ip02;
int ****ip04 = & ip03;
int *****ip05 = & ip04;
int ******ip06 = & ip05;
int *******ip07 = & ip06;
int ********ip08 = & ip07;
int *********ip09 = & ip08;
int **********ip10 = & ip09;
int ***********ip11 = & ip10;
int ************ip12 = & ip11;
************ip12 = 1; /* i = 1 */
If you mean "How many levels of pointer can you use before the program gets hard to read," that's a matter of taste, but there is a limit. Having two levels of indirection (a pointer to a pointer to something) is common. Any more than that gets a bit harder to think about easily; don't do it unless the alternative would be worse.
If you mean "How many levels of pointer indirection can you have at runtime," there's no limit. This point is particularly important for circular lists, in which each node points to the next. Your program can follow the pointers forever.
22. What is indirection?
If you declare a variable, its name is a direct reference to its value. If you have a pointer to a variable, or any other object in memory, you have an indirect reference to its value. If p is a pointer, the value of p is the address of the object. *p means "apply the indirection operator to p"; its value is the value of the object that ppoints to. (Some people would read it as "Go indirect on p.")
*p is an lvalue; like a variable, it can go on the left side of an assignment operator, to change the value. If p is a pointer to a constant, *p is not a modifiable lvalue; it can't go on the left side of an assignment.

#include <stdio.h>
#include<conio.h>
void main()
{
        int a;
        int *p;
        a = 5;
        p = & a;    /* now *p == a */
        printf("i=%d, p=%P, *p=%d\n", a, p, *p);
        *p = 6;     /* same as a = 6 */
        printf("i=%d, p=%P, *p=%d\n", a, p, *p);
        getch();
}

23. When should a far pointer be used?  
24. What is :
      pointer ,
      NULL pointer ,
      dangling pointer ,
      far pointer ,
      near pointer ,
      huge pointer ,
      generic pointer and smart pointer ?           
25. What is the difference between NULL and NUL?           
26. What will be the equivalent pointer expression for referring the same element a[i][j][k][l] ?  
Are pointers integers?        
27. What is the difference between near pointer and far pointer?       
28. What is a pointer variable? 
29. Is **p and &(*p) same?     
30. What is a null pointer ?      
31. How do you insert an element into a linear list without using pointers?      
32. How are pointer variables initialized?
33. Write a c program to print the Fibonacci series using pointer? As:0,1,1,2,3,5,8,13,21........N    
34. What is a ?null pointer assignment? error? What are bus errors, memory faults, and core dumps?        
35. In the following code, what is p2? typedef int* ptr ptr p1, p2;     
36. What are the uses of pointers in c and c++ language?   
37. What is the pointers in c     
38. How to operate pointers in any pragram& how to develop our logic while implementing pointer
39. Why does malloc(0) return valid memory address ? What's the use ?     
40. How can you determine the size of an allocated portion of memory?     
41. What are advantages and disadvantages of external storage class?         
42. What is the purpose of realloc( )?            
43. What is the difference between new/delete and malloc/free? 
44. Difference between calloc() and malloc()?          
45. What is the heap?          
Ans: The heap is where malloc(), calloc(), and realloc() get memory.
Getting memory from the heap is much slower than getting it from the stack. On the other hand, the heap is much more flexible than the stack. Memory can be allocated at any time and deallocated in any order. Such memory isn?t deallocated automatically; you have to call free().


Recursive data structures are almost always implemented with memory from the heap. Strings often come from there too, especially strings that could be very long at runtime. If you can keep data in a local variable (and allocate it from the stack), your code will run faster than if you put the data on the heap. Sometimes you can use a better algorithm if you use the heap?faster, or more robust, or more flexible. It?s a tradeoff.

 If memory is allocated from the heap, it?s available until the program ends. That?s great if you remember to deallocate it when you?re done. If you forget, it?s a problem. A ?memory leak? is some allocated memory that?s no longer needed but isn?t deallocated. If you have a memory leak inside a loop, you can use up all the memory on the heap and not be able to get any more. (When that happens, the allocation functions return a null pointer.) In some environments, if a program doesn?t deallocate everything it allocated, memory stays unavailable even after the program ends.

 Heap is the term used for the memory allocation unit in C. In C++ memory allocation is done from "The Free Store". There is just difference of terminology.
Memory allocation takes place in C from heap.

Whenever u call malloc, calloc or realloc in C the memory is allocated from heap.
Memory allocated as such must be deallocated using free.

46. What? s wrong with this code?
      char*p *p=malloc(10);
   
47. Is it better to use malloc() or calloc()?    
48. How to write calloc() in terms of malloc()? ie malloc() should initialise the memory to zero after allocating it        
49. Why do we need to test wheather it is memory leak or not? How are we going to know that?      
50. What is the difference between the functions memmove() and memcpy()?