Wednesday 12 November 2014

Scope Rules and Extern Variables

Q. What are the scope rules and why we use external variables and how to use them?

Ans : The scope of a variable or a function or a object is the area in the programme where we can use it. Like for example by defining a variable as global ( Outside the main function in c/c++) . We can use that variable in all over the programme.

Scope is generally divided into two broad categories.
1. Global
2. Local

There is one more category that is the external variables through which we can share the variable scope to the not only in the same programme but also in any other file by declaring it as extern variable.

1. Global :  Global scope is as name suggest that we define variable or object globally so any function can use it. Its existence last till the programme last. 

Ex:

# include <stdio.h>

int array[2];   // this is a global variable. this can be used by any of the function
int add(){

    return array[0]+array[1];
}
int main (){

    array[0]=1;
    array[1]=2;
    printf(" %d ", add());
return 0;

}

2. Local : Local scope is the local variable which we declare in different different function for use in only those function. One function can not see the local non static variable of another function.
Ex:
# include <stdio.h>


int add(int array[]){

    return array[0]+array[1];
}
int main (){
 int array[2];   // this is a local variable which can be used only by main function if we want to
                       // add numbers of the array the we have to pass the array as argument to the function
    array[0]=1;
    array[1]=2;
    printf(" %d ", add( array ));  //  passing the array as a argument
return 0;



The difference is that in first scenario every function can use the global variables so we do not have to pass it to every function which needs those variables. But in second scenario we have to  send it as argument to the function which need those variables. 

But in Second scenario variable is lost after the function returns.  Memory is being released. But in the first case all the global variable will last till the programme is not completed . So memory will not be released till the programme ends. 

External Variables:

External variable is a way to share the variables or functions or object between the files. External variable should be declared as extern in the file in which we want to use the variable of the different file. In the first file variables should be global then only other file which has an extern variable can access that variable.


How it happens?

When ever compiler sees an extern variable. It understands that this variable is defined somewhere else , this is only the declaration of it. And then it tries to find out the definition of the variable in the same file in global space and another files which we have included in the file or in the other files which are in the same folder of the file using extern variables.

Ex: in first file:

int array_ext[2];
main(){}

in second file:

extern int array_ext[];

main(){}

I am leaving the not necessary part of the code...
Then in the second file compiler gets to know that array_ext is a external variable so it tries to find its definition in other files. It gets the definition in the file and uses that information. You do not have to declare size of array again in second file. It will automatically detect every thing size ,values if are given.

Tuesday 11 November 2014

Structure vs Union vs Enumeration

Q. What is the differences between structure, union and enumeration and how  and when to use them?

Ans :  These three are different-different data structure I would say. These all three can contain different different member variables like int , float ,char etc...

Difference between structure and union is that the memory which is allocated to the structure is equal to the memory needed by its all member variables and some structure padding. I will talk about structure padding in my future posts. But the size of the memory which is allocated to the union is equal to maximum of the memory needed by its individual members. 

Structures always have their all member variables active. But in union only one of its member can be active. Only one memory block that is equal to the size of the maximum size among all the member variables are allocated but in the case of structures they are allocated the space which can handle all of its members simultaneously.

Ex.  struct Car{
             int speed;
             int engine_type;
             char model ;  // a or b or c

      }

The size of the strucure will be at least the size of all the member variables plus some structure padding for alligning the structure to memory addresses which ends at the complete nibble or byte or word etc. It depends on the processor type 32 bit or 64 bit and many other things. But for sure the size will be greater or equal to the sum of the size of all the variables here the size of Car is int(4) assume so
         
                       4+4+1(char)=9 . So size will be >=9.

Ex.
           union Car{  
             int speed;
             int engine_type;
             char model ;  // a or b or c

      }

But in union only the size of the maximum size variable will be allocated to the car and that is 4 for integer in this case. At a time Car can have only speed ,engine_type or model by using union. By using structure it will have all three attributes active at the same time.


Enumeration is also contains a single value from its all values. These all values should be of similar types. But in the case of union that can be of different types. These all values can be assigned numbers and then they will be treating as numbers. If not assigned explicitly the values will be assigned starting from 0 then 1 and so on.

Ex:     enum e { sunday, monday};

then sunday will be equal 0 and monday will be equal 1 etc....  Here e will be either monday of sunday means either 0 or 1 ....


Monday 10 November 2014

Multifile programming

Q. What is multifile programming and why we use multifile programming concept?
Ans. First of all what is multifile programming.

You might have heard of your teacher saying "use multifile programming to do this assignment".

So multifile programming is to do the programming in a manner that its all functions become reusable by just including a file in the other programme. Easier to understand and modify.

Actually in multifile programming we write the functions declarations and definitions in two different files. Function declaration in .h file or any other extension except the reserved extension like .c /.cpp etc. And then we write the functions definition in the other file but different extension .c/.cpp. Then we make the object file of that c/cpp file using command gcc -c filename.c .

Do not forget to include .h file in you .c/.cpp file. Then we write the main file . In which we use the functions which we have declared in .h and defined in .c/.cpp file.

Here it goes the complete process
1. Make a header file including all functions declaration and you can declare the global variable also here but not the static variable, I will define the reason for this in future posts.
fun.h -> contains all the function declaration and may be global variable declarations

2. Make a .c/.cpp file fun.c which implements those functions written in fun.h. Remember to add the .h file in .c/.cpp file . Do not define main function in this fun.c file . Define only the functions which we have declared in fun.h. Then do no compile it as usual ways . 
                      Compile it like gcc -c fun.c.
Because it creates a object file not and executable file. Because it do no contain main function you can not compile it usual ways. Other wise it will give error main function is missing.

3. Make a main file mainfile.c/.cpp . Which does the task what we want to do using those functions.
Now while compiling this file do not remember to add the object file we made in the second step.
Ex.   gcc -o executable mainfile.c fun.o

-o rename the executable file as executable and we add the fun.o file to the mainfile so it does not miss any function definitions. 
Then run file as ./executable.

The reason why we are doing this because.
Suppose we want to give some developer information that they can use our functions but they can not see implementation. Then we can give him/her our header files containing function declaration and the object file. No need to give fun.c to anyone. No one will knows our implementation.

Another scenario is when we want to use those function in some other file include that header file and add that object file while compiling. 
I am sorry , I explained it only as linux user.

Sunday 9 November 2014

Recursion

Q. What is recursion and why we use it?

Ans. As the name suggest recursion is to call something or do something again and again.

In programming language if a function invokes itself or in lay man language a function call itself. Then this programming paradigm is called recursion.

Recursion is very useful in some situations.  Like: finding the factorial.
But every coin has two faces. So Recursion also has some cons.

Ex:

int find_fact(int k){

       if(k==0 || k==1)
             return 1;

       else 
             return  k* finf_fact(k-1);
}

In this function we call find_fact again till we reach the termination condition which is k==1.

Before writing any recursive function we should think of what will be its terminating condition. Our calls to the same function should converge to termination point . It should not deviate away from the termination point otherwise it may go in to infinite loop.

Ex. 
if in above example I write k+1 instead of k-1 and if user send 2 as input to function then this will never going to be terminated. Because it is going away from the termination point. Recursive call should be converging to the termination point.

Any recursive function or program can be written without recursion but not other way around.

In recursive function in built stack of computer is used. It keeps all the information of the call at which line function is invoked. It puts that function frame to the top of the stack and then function returns it reach to the last address where it left the function and start evaluating again.

But as the number of calls increases the stack size increases. So for large number of inputs there might be segmentation fault due to stack overflow. So avoid the writing functions using recursion . Try to write it without recursion and use your stack so you know what is the size of the stack. Whether it is overflowing or not.

To find the complexity of the recursive function we write the recursive equation and try to solve it using Master's theorem or tree method or induction any of these or any other method.

Ex. the recursive equation of the above function is
               
T(n) = T(n-1) + C;                       

C is here some constant it may be zero or anything. It depends on the function. Here No loops in the function only just a condition and a multiplication expression so C's value here is turn to be 1.

By solving this you can get the complexity. I am leaving this is an easy exercise to do on your own.

Saturday 8 November 2014

Structure vs Class

Q. Why we use Structure or Class and when to use them ?

Ans. In the past when there was no concept of OOPS programming there was no class concept. 

Then how could we implement a real time entity (in C) and then later convert to object (in OOPS).
At that time structure was very useful to implement a real world entity in the programming. Like for example we have to make car's object or entity. Then we can use Structure name as car which can have the car's attribute. But at that time structure could not contain functions associated with the entity.

Ex.  structure definition

      Struct car {
               bool petrol;           /// It is running from petrol or diesel
               int engine_type;
               long int price;
               int capacity_seat;
               ..............etc....

};

In the above structure we map the real world car to that structure with the similar attributes what a real world car would have. But we can not define the function of the car in that structure and that is the main difference between the C structure and C++ class concept.

There is no concept of access specifier in C structure but in C++ concept of access specifier is there. A member or a member function of a class can either be public, private or protected depending upon the needs.

Ex.
            Class car{
             
             private:
               bool petrol;           /// It is running from petrol or diesel
               int engine_type;
               long int price;
               int capacity_seat;
               /////..............etc....
             public:
               // constructor which makes an object of the car
               car(int a, bool b, ////etc.....){

               }

             // destructor which destruct the object
            
             ~ car(){
                // some implementation
                  }

           } ;

In class we can define the function also. There is a concept of the constructor and destructor in oops.

Mainly differences are

                         Structure  in C                                                       Class in OOPS (C++)

1.       Do not contain function of the entity.             May contain functions of Object.

2.       No concept of access modifier.                       Member can be public , private or protected

3.       No constructor or destructor.                           Every class contains a constructor and 
                                                                                   destructor either  in 
                                                                                   built or user defined .

Friday 7 November 2014

Array vs Link List

Q. What is the difference between array and linked list and when to use them?

Ans : Both are data structures. Data structures are used to store and processed data in some order in efficient way.

Arrays are static data structure. Static means we have to define the size of the array while initializing the arrays. Later on we can not modify the size of arrays.

Ex:   int array[10];

Here array is an array of 10 integers. We can not increase the size of the array at run time. But we can access any element of the array randomly. We do not have to traverse the whole array.

Ex:  array[1]=1;


Instead link list is a dynamic data structure. We do not have to define the size of the link list at the time of initialization. We can increase the size dynamically at run time. We implement the link list by using pointers and pointers can be allocated memory easily at running time.

In link list we can not access any element randomly we have to traverse the all the elements which are before the target element. So complexity of accessing element in link list are much more than the array.

Difference in the complexity of Searching and Sorting varies with the algorithms used to do the mentioned tasks. Generally we use the array when we know the size of the input otherwise we go for the link list.






Thursday 6 November 2014

Write a function

Q. How to write a function and why we need them?
Ans. First of all why we need function.

Suppose we have to write a programme for L.C.M. (least common multiple) for two integers . We wrote the programme without using function and someone now ask to write the same programme for more than two integers. But now we cannot use the same programme for it. But If we would have written that programme in a function then we could have used that function for extension.

If we have to find the l.c.m. twice in the same programme then we have to write the code twice if we are not making a function of the l.c.m.


There are more advantages.
1. We don't have to rewrite the code again and again. (Code length is reduced)
2. We can use those function in other programmes but if do not write in functions we can not re use them. (Extendability)
3. Easy to read and understand. (User and programmer friendly)


How to write functions?

Functions always have their prototype. Means what is the function's name and what function take as argument and what does function return etc.. I will explain it in the next part.

Prototype:(function declaration)
Return_type function_name ( function's arguments);

Ex.  int add(int val1, int val2);

In this prototype function's return type is int means function will return a integer. Function name is add and it takes two argument val1 and val2. It is just a prototype. Function will also have a body. In which we define what function really does?

(function definition)
Ex.
 int add(int val1, int val2){             //function body starts
      int result= val1+val2;
      return result;

}

Function's body is written between the paranthesis. Here we define a temporarily variable which is not necessary. We add the two values and return the result through return keyword.

We could have written it this way also.

int add(int val1,int val2){
       return val1+val2;
}

This is also correct. It automatically allocate a temporarily variable and calculate the result and then return the result.

Prototype is not necessary if you define function before it is used. But now in new gcc compiler (2014) there is no need to write prototype or declaration . You can directly define function anywhere in the programme. Remember it is true only for the latest gnu gcc compiler.


Related Posts

Related Posts Plugin for WordPress, Blogger...