MY mENU


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

Wednesday, 19 December 2012

Should variables be stored in local blocks?

The use of local blocks for storing variables is unusual and therefore should be avoided, with only rare exceptions. One of these exceptions would be for debugging purposes, when you might want to declare a local instance of a global variable to test within your function. You also might want to use a local block when you want to make your program more readable in the current context.

Sometimes having the variable declared closer to where it is used makes your program more readable. However, well-written programs usually do not have to resort to declaring variables in this manner, and you should avoid using local blocks.

Monday, 15 October 2012

What is passing by reference?

Method of passing arguments to a function which takes parameter of type reference.
for example:
void swap( int & x, int & y )
{
int temp = x;
x = y;
y = temp;
}
int a=2, b=3;
swap( a, b );

Basically, inside the function there won't be any copy of the arguments "x" and "y" instead they refer to original variables a and b. so no extra memory needed to pass arguments and it is more efficient.

What is difference between template and macro??

There is no way for the compiler to verify that the macro parameters are of compatible types. The macro is expanded without any special type checking.
If macro parameter has a postincremented variable ( like c++ ), the increment is performed two times.
Because macros are expanded by the preprocessor, compiler error messages will refer to the expanded macro, rather than the macro definition itself. Also, the macro will show up in expanded form during debugging.
for example:
Macro:
#define min(i, j) (i < j ? i : j)
template:
template
T min (T i, T j)
{
return i < j ? i : j;
}

Constructor & Destructors in C

What is constructor or ctor?
Constructor creates an object and initializes it. It also creates vtable for virtual functions. It is different from other methods in a class.

What is destructor?
Destructor usually deletes any extra resources allocated by the object.

What is default constructor?
Constructor with no arguments or all the arguments has default values.

What is copy constructor?
Constructor which initializes the it's object member variables ( by shallow copying) with another object of the same class. If you don't implement one in your class then compiler implements one for you.
for example:
Boo Obj1(10); // calling Boo constructor
Boo Obj2(Obj1); // calling boo copy constructor
Boo Obj2 = Obj1;// calling boo copy constructor
When are copy constructors called?
Copy constructors are called in following cases:
a) when a function returns an object of that class by value
b) when the object of that class is passed by value as an argument to a function
c) when you construct an object based on another object of the same class
d) When compiler generates a temporary object

What will happen if any string in c is converted to integer explicitly?

 If we try to convert string into integer explicitly then string’s address will get stored in integer. 
int main()
{ 
 char *a="abhas";
 int b=(int)a;
 // now b will hold address of a 
}

Monday, 24 September 2012

Memory Leak, Union, Heap,Stack in C


What is a memory leak?
Memory leak is that when memory is allocated but its not released because of an application consume memory reducing the available memory for other applications and causing the system to page virtual memory to the hard drive showing the application or crashing the application. When the computer memory resource limits are reached.

 Explain about storage of union elements.
The key point about storage of union elements is that Union elements are use to share common memory space.

What is the difference between the Heap and the Stack?
The main difference b/n the Heap and the Stack are given below:
- In stack we create object temporary where programmer used to reserve allocation.'
- stack not have automatic garbage collection where as heap have automatic garbage collection.

How the processor registers can be used in C?


using keyword register we can use the process register in C.Basically process register is used to store variables those i want to access frequently.if these registers are not used in any other program,then those registers we used to allocate memory these variables.

What are the stream files?


We can open file in C with using stream files.which are identified with a pointer to a FILE structure, or as low-level files, which are identified with an integer handle. We can open stream files with using one of the following functions.
fopen(): Opens the specified file with the specified mode 
freopen(): Closes the file specified, then opens a new file as specified 
fdopen(): Opens a duplicate stream file for an already open low-level file

Sunday, 17 June 2012

printf() Function in C Language


What is the output of printf("%d")?
1. When we write printf("%d",x); this means compiler will print the value of x. But as here, there is nothing after %d so compiler will show in output window garbage value.
2. When we use %d the compiler internally uses it to access the argument in the stack (argument stack). Ideally compiler determines the offset of the data variable depending on the format specification string. Now when we write printf("%d",a) then compiler first accesses
the top most element in the argument stack of the printf which is %d and depending on the format string it calculated to offset to the actual data variable in the memory which is to be printed. Now when only %d will be present in the printf then compiler will calculate the correct
offset (which will be the offset to access the integer variable) but as the actual data object is to be printed is not present at that memory location so it will print what ever will be the contents of that memory location.
3. Some compilers check the format string and will generate an error without the proper number and type of arguments for things like printf(...) and scanf(...).

Thursday, 22 March 2012

What does the #include directive do?

The #include directive is used to include header files that contain the declarations to the functions used in your C program. In other words, the #include directive tells the C preprocessor to look into the include path to find the specified header file.

Why is the main() function needed in a C program?

The execution of a C program starts and ends with the main() function. Without the main() function, the computer does not know where to start to run a program.

What is the difference between the Heap and the Stack?

The main difference b/n the Heap and the Stack are given below:

- In stack we create object temporary where programmer used to reserve allocation.'
- stack not have automatic garbage collection where as heap have automatic garbage collection.

How the processor registers can be used in C?

using keyword register we can use the process register in C. Basically process register is used to store variables those i want to access frequently. if these registers are not used in any other program, then those registers we used to allocate memory these variables.

What are the stream files in C?

We can open file in C with using stream files.which are identified with a pointer to a FILE structure, or as low-level files, which are identified with an integer handle.

We can open stream files with using one of the following functions.

fopen(): Opens the specified file with the specified mode

freopen(): Closes the file specified, then opens a new file as specified

fdopen(): Opens a duplicate stream file for an already open low-lev

Is C is platform dependent or independent?

Major issue behind designing C language is that it is a small,portable programming language. It is used to implement an operating system.In past time C is a powerful tool for writing all types of program and has mechanism to achieve all most programming goals.So, we can say that C is platform dependent.

Tuesday, 20 March 2012

Convert Decimal into Hexa Decimal

Convert Decimal into Hexa Decimal:

#include
#include
#include
void main()
{
Int x, y=30, z;
 clrscr();
  printf(“Enter the number:”);
    scanf(“%d”, &x);
       printf(“\n conversion of decimal to hexadecimal number\n”);
         for(;;)
          {
           if(x= =0)
             exit(1);
               z=x%16;
                   x=x/16;
                      gotoxy(y--,5);
           switch(z)
            {
              Case 10:
                Printf(“A”); Break;
             Case 11:
                Printf(“%c”, „B?); Break;
             Case 12:
                Printf(%c”, „C”); Break;
            Case 13:
                Printf(“D”);  Break;
           Case 14:
               Printf(“E”); Break;
           Case 15:
              Printf(“F”);
           Default:
              Printf(“%d”, z);
           }
        }
    getch();
}

Output:
Enter the number: 31
Conversion of decimal to Hexa decimal number 1F

Wednesday, 15 February 2012

Loops in C programming


Loop's in C are three kinds:
 those are 1. For Loop
                 2. While Loop
                   3.do-while Loop

For Loop:
 For loop in C is the most general looping construct. The loop header contains three parts: an initialization, a continuation condition, and step.
Syntax:
               for (initialization, condition, step)
                        {
                        Statement 1;
                        Statement 2; 
                        …………...
                        Statement n;
                       }

               For statement contain three parts separated by two semicolons. The first part is known as initialization. The variable called loop control variable or index variable is initialized in this part.

              The second part is known as the condition. The condition should be a value one. The condition check can be a compound expression made up of relational expression connected by logical AND, OR.

                 The third part is known as step. It should be an arithmetic expression. The initialization need not be contained to a single variable. If more than one variable is used for initialization they are separated by commas. The step can also applied to more than one variable separated by commas.

               When for statement is encountered at first index variable is get initialized. This process is done only once during the execution of for statement. When condition is evaluated, if it is true the body of the loop will be executed. If more than one statement has to be executed it should end with a pair of braces. The condition of for loop is executed each time at the beginning of the loop. After executing the body of the loop the step is executed, again the condition is executed. If the condition become false it exit from the loop and control transferred to the statement followed by the loop.

The following example executes 10 times by counting 0..9.
for (i = 0; i < 10; i++)
        ;
While LOOP:
  The while loop evaluates the test expression before every loop, so it can execute zero times if the condition is initially false. It has the following syntax.

while (expression)
        {
        Statement 1;
        Statement 2; 
        …………...
        Statement n;
       }

               Here the initialization of a loop control variable is generally done before the loop separately. The testing of the condition is done in while by evaluating the expression within the parenthesis. If the evaluation result is true value, the block of statement within calibrates is executed. If the evaluation result is false value the block of statements within the body of loop is skipped and the loop execution get terminated with the control passing to the statement immediately following the while construct. The increment or decrement of the loop control variable is generally done within the body of the loop.

DO-While Loop:
 In this case the loop condition is tested at the end of the body of the loop. Hence the loop is executed at least once.
Syntax of do while loop is
do
     {
     Statement 1;
     Statement 2; 
     …………...
     Statement n;
    }
while(expression);     

                 Here the block of statement following the do is executed without any condition check. After this expression is evaluated and if it is true the block of statement in the body of the loop is executed again. Thus the block of statement is repeatedly executed till the expression is evaluated to false.

               

Switch Statement in C



switch statement:
 Switch statements simulate the use of multiple if statement.The switch statement is probably the single most syntactically awkward and error-prone feature of the C language. Syntax of c switch statement is
switch(expression)
          {
          case constant1:
                       statements 1;
           break;
           case constant2:
                       statements 2;
           break;
           …………………..
          default:
                       statements n;
           break;
          }


                  When the switch statement is executed, the expression in the switch statement is evaluated and the control is transferred directly to the group of statements whose case label value matches the value of the expression. Each group of statement ends with a break statement. The execution of break statement causes immediate exit from the switch statement. If break statement is not present, then the execution will falls trough all the statement in the selected case.  If none of the case-label value matches the value of expression, then none of the group within the switch statement will be selected and the control is transferred directly to the statement that follows the switch statement c.


                  The expression that forms the argument of switch is evaluated to either char or integer. Similarly the constant expression follows the keyword case should be a value int or char. That is, names of variable can also be used. Switch can test for only equality.



When case constants are evaluated from the top to down, and the first case constant that matches the switch's expression is the execution entry point. In other words, once a case constant is matched, C will execute the associated code block, and all subsequent code blocks .

Example:




goto statement:

The goto statement is used to alter the normal sequence of program execution by transferring control to some other part of the program unconditionally. In its general form, the goto statement is written as


goto label;
               where the label is an identifier that is used to label the target statement to which the control is transferred. Control may be transferred to anywhere within the current function. The target statement must be labeled, and a colon must follow the label. Thus the target statement will appear as
label:statement;


Each labeled statement within the function must have a unique label, i.e., no two statement can have the same label.




If Statement in C


if statements:
If statement is a conditional branching statement. In conditional branching statement a condition is evaluated, if it is evaluate true a group of statement is executed. The simple format of an if statement is as follows:
if (expression) 
        statement;
  If the expression is evaluated and found to be true, the single statement following the "if" is executed. If false, the following statement is skipped. Here a compound statement composed of several statements bounded by braces can replace the single statement.

if else statement:   This feature permits the programmer to write a single comparison, and then execute one of the two statements depending upon whether the test expression is true or false. The general form of the if-else statement is


if(expression)
          statement1
else
          statement2

                    Here also expression in parentheses must evaluate to (a boolean) true or false.
You can set up an if-else statement to test for multiple conditions. if-else construct, the  if, else if, else. This construct is useful where two or more alternatives are available for selection.


The syntax is
if(condition)
          statement 1;
else if (condition)
          statement 2;
          .....................
          .....................
else if(condition)
         statement n-1;
else
          statemens n ;


PassByValue and PassBy Reference in C functions


 Arguments can be passed to a function by two methods, They are

1.pass by value
2.pass by reference


Pass by Value:
                 Function in C passes all arguments by value. When a single value is passed to a function via an actual argument, the value of the actual argument is copied into the function.
 Therefore, the value of the corresponding formal argument can be altered within the function, but the value of the actual argument within the calling routine will not change. This procedure for passing the value of an argument to a function is known as passing by value.

Example:

Pass by Value



Pass by Reference:

                When passing by reference technique is used, the address of the data item is passed to the called function. Using & operator we can determine the address of the data item. Note that function once receives a data item by reference, it acts on data item and the changes made to the data item also reflects on the calling function. Here you don't need to return anything to calling function.

Example:

Pass by Reference


Recursion:

 Recursive functions are those functions, which call itself within that function. A recursive function must have the following type of statements.

1.A statement to test and determine whether the function is calling itself again.

2.A statement that calls the function itself and must be argument.

3.A conditional statement (if-else)

4.A return statement.

Example: Factorial of a number

             This is the most famous program on recursion. Many versions of this program are available.
All programs differ only in checking conditions. I prefer to write like the following one.

Recursion