Monday 22 December 2014

Error:Changes are not reflected in Code Blocks / Taking too long to show changes in code blocks

The first issue is that some time in windows while working on codes block Changes are not reflected even after closing the prior executable , compiling and running again. The Problem is that the prior executable is not properly closed.

Solution1:You have to go to Task Manager and find that executable and close it from task manager. Then compile the programme again and then run, Changes will be reflected. It worked for me. 


The second issue is that some time it takes two long to running a programme in codes block even after programme is just a small one. The issue is that Antivirus is scaning that executable for viruses. So it is taking too long to show response.

Solution2: Go to your antivirus's setting. Find the exception tab. And add the path where you are saving your programmes. So that antivirus will not check for viruses in that folder again and you will see result as fast as it should be.

I hope it helps..

If you are getting any other error in code blocks post it in comment. I will try to answer that.

Thursday 18 December 2014

Type Conversion/ Type Casting

Q. What is Type Conversion, how and when it happens?
Ans. When we write an expression in any language it would have some operators and operands. When there are two different types of operands (like: int and float) along with an operator(like: + or * etc.) then the operands are converted to a common type according to some rules( specifically in C ).

Example:
long int j=100000000000;
int i=10;
long int k=i+j;

then the value of i is automatically converted in to long for evaluating the expression and result will be long int. 
Note: the value of i is still 10 and type of i is still int. It just change the value of i to the long int temporarily for the expression evaluation.

      This conversion is called type conversion. It is happening by default automatically so it is called automatic type conversion. Which converts the "narrower range(like int)" operand to a "wider range (like long int)" operator. In this type of conversion no information is lost.

     We can forcefully convert any "wider range operand" to a "narrower range operand". The compiler will not give an error. But there is always a drawback of losing information in this type of conversion.
Ex: 
long int j=100000000000;
int i=(int) j;  /// type casting , converting value of j in to range of integer.

in this type of code compiler may not give an error but the value of i will not be equal to the value of j because j is containing value which is beyond the range of the integer variable. It is called type casting.

General Rules for automatic conversion( in C):
1. If one of the operand is long double, other will be converted to the long double.
2. Else if one of the operand is double, other will be converted to the double.
3. Else if one of the operand is float, other will be converted to the float.
4 .Else char and short int is converted in to int.

5. Then, if either operand is long, other will be converted in to long.

Note: So while doing type casting on your own always take care of not converting a wider range operand to a narrower range operand. Otherwise some information may be lost.
 Type conversion can be done while calling a function also.
Ex:
int m=10;
sqrt((double)m);

The in build function sqrt of the math.h library expect a double argument to it. If we want to find sqrt of an int then we can convert it to double while calling function. The value is converted to double and then send to the function.

Note: Again the value and the type of the m is still not changed.

 Stay tuned for the new posts and leave comment or ask questions if u have any :)


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.


Thursday 9 October 2014

Trap in operating system

Q. What is trap and an example of trap which we use in daily life?

Ans. Trap is a type of interrupt which is used to communicate with processor. It can be hardware or software either. Generally it is a hardware interrupt with manual access. 

Main thing is that the priority of Trap is always higher than the any kind of other interrupt . If once a trap is occurred processor will execute the instruction corresponding to that trap in any kind of situation.

Ex: The example of a trap which we use in our daily life is the power button in laptops. In whatever condition if we push that button it shutdown the pc.

Wednesday 8 October 2014

Macros

Q. Why we use macros?
Ans. First of all What is macros?

Macros are used to define something before the execution starts and its values are never changed during the execution.

Ex:  in c/c++

#define max_size 100
#ifndef
#include<something.h>
#end if

Imagine the scenario you write a program where you assume the size of the input to 1000 at max and u use every where 1000 . Then some one asked you to modify that program for 10000 elements then you have to go to all places where you write that 1000 and replaced it by 10000 instead of that we can use macros we define variable in starting outside the main function and use that variable in our function if some one asked to change the size we change only that variable and the changes at all the places are taken care of automatically.

Macros are predefine variables or function. Compiler replaces all the macros in its pre processing with its corresponding values in the entire program.



Explain public static void main(string [] args)

Q. The question comes here is why java's main function has all the keyword like public, static  and void?

Ans. First start with public is because of scope of the main function so that it can be called out of the class . If it would be private or something else compiler can not invoke the main function out of the class.

Second static is because when main function is called there will be no object of the class so if we want to call a method of a class without initializing the object of that class then we have to make that method static. Static function can be called without initializing the object of that class.

Void is the return type of main function we can not change it because main function will not return anything in java. If it would then to whom it will return something?? Think about it......

And the argument is the array of string objects which it expects.

Argument to main function in C/C++

Q. What is the use of passing argument to main function?
Ans.
      First of all we can define main function in three different format in c/c++.
      int main(int argc,char * argv[]);
      int main(void);
      int main();

Instead of int return type we can have any other pre defined data type as return type of main function.

We start with the first prototype, here main function excepts two arguments one is of type int and other is of type array of pointers. First of all these arguments are used for passing the input together when we start executing the program. We don't have to pass the first argument it automatically counts how many argument we have passed while executing the program and that will be stored in argc.

Second argument argv[] is array of character pointers which stores the inputs which we have sent with execution. for ex. argv[0] will have first argument and argv[1] will have second argument .


In the second prototype it does not except any argument if we passes a argument the compiler will give an error.

Third one is similar to the second one but the difference is that in third one we can pass as many argument we want it will not give an error but in the second one it will give an error while we pass an argument to main function using terminal (linux users).

Two main function in java

Q. The question is that can we have two main functions in java?

Ans. Yes, We can have two main function in java but the function's prototype should be different.

 For example we can have two functions like-
public static void main(string[] args);

and second one may be

public static void main(int a);


The reason for this is that when compiler/interpreter starts executing it starts with finding a function whose prototype is similar to the first one i have written have which takes argument as a array of string objects. It does not consider the second main function because it has different argument then the one which is needed. So we can have two main functions with two different arguments and one of them should be similar to the first one.

Header files

The question always comes to our mind is why we include header files?

Ans:  The answer is simple The function which we use can be define separately in .h files. .h is the extension of header files which contains the prototype of the function and also may contain the definition but for reason of abstraction we prefer to write prototype and definition in different file prototype in .h but not necessary can be written with some other extension also.

Then we write the definition to .c file compile those files make their object files and include header file to our main file and put both .h and .c file to the same folder then use the functions written in that header file. Some header files are already in-built which we can directly use like #include<stdio.h> it is a standard input output file which we can use for printf and scanf functions etc.

The advantage is our source code file's size is less. And if we want to give someone which functions are available we can give the header .h file only. No need to give .c file we can give object file so he/she will not need to understand how the implementation is happening.

Tuesday 7 October 2014

Increment operator in c

Are you ready for some serious brain storming?
Here it goes my first post.

1. What would be the output of this program while running with the gnu gcc compiler?


#include<stdio.h>

int main(int argc, char * argv[]){

      int z=2;
      int y=2;
   
      z=z++;
      y=++y;
      printf("%d  %d",z,y);
 return 0;
}

Please Before proceed to answer just think for a minute.
Think ::::


This Space is left intentionally.









Although this is undefined behavior due to absence of sequence point. I will define sequence point in my future posts. But here I am presenting one of the reasons of getting this output.




Answer is  : 2 3

Reason is : For understanding the reason behind this we have to understand the execution sequence of instruction z=z++;

For evaluation of a expression compiler generates a temporary variable and evalute the expression and store the value in the temporary variable which in the given expression is 2 because postfix operator executes after the expression is evaluated. So till now the temporay variable has value 2 
and now z becomes three due to posfix operator. And then the temporary variables value is assigned to the variable which is on the left side of the = operator which here is z itself so value 2 is assigned to z again.
Finally the value of z becomes 2.

Similarly for the value of y first expression is evaluated and in this pre increment is also evaluated so value of y becomes 3 and the value of temporary variable is also becomes 3 and now this temporary variable's value is assigned to y.
Finally the value of y becomes 3.

Related Posts

Related Posts Plugin for WordPress, Blogger...