Interviews Questions, Algorithms, Aptitude, C Interview Program, C Theory Question, Aptitude Tricks, Test Series,

Showing posts with label C Theory Question. Show all posts
Showing posts with label C Theory Question. Show all posts

Saturday, 1 June 2019

Data Segments


All the variables, functions, and data structures are allocated memory into a special memory segment known as the Data Segment. The data segment is mainly divided into four different parts which are specifically allocated to different types of data defined in our C program.

Data Segments


The parts of Data segments are :

1. Data Area

It is the permanent memory area. All static and external variables are stored in the data area. The variables which are stored in the data area exist until the program exits.

2. Code Area

It is the memory area which can only be accessed by the function pointers. The size of the code area is fixed.

3. Heap Area

As we know that C supports dynamic memory allocation. C provides the functions like malloc() and calloc() which are used to allocate the memory dynamically. Therefore, the heap area is used to store the data structures which are created by using dynamic memory allocation. The size of the heap area is variable and depends upon the free space in the memory.

4. Stack Area

The stack area is divided into two parts namely: initialize and non-initialize. 
Initialize variables are given priority than non-initialize variables.


  • All the automatic variables get memory into the stack area.
  • Constants in c get stored in the stack area.
  • All the local variables of the default storage class get stored in the stack area.
  • Function parameters and return value get stored in the stack area.
  • The stack area is the temporary memory area as the variables stored in the stack area are deleted whenever the program reaches out of scope.

Inline function in C

Inline Function are those function whose definitions are small and be substituted at the place where its function call is happened. Function substitution is totally compiler choice.

Let’s take below example:

#include <stdio.h> 
  
// Inline function in C 
inline int foo() 

    return 2; 

  int main() 

      int ret; 
      // inline function call 
    ret = foo(); 
      printf("Output is: %d\n", ret); 
    return 0; 


Compiler Error:

In function `main':
undefined reference to `foo'
Why this error happened?

This is one of the side effect of GCC the way it handle inline function. When compiled, GCC performs inline substitution as part of optimisation. So there is no function call present (foo) inside main. 



Normally GCC’s file scope is “not extern linkage”. That means the inline function is never ever provided to the linker which is causing linker error, mentioned above.

How to remove this error?

To resolve this problem use “static” before inline. Using static keyword forces the compiler to consider this inline function in the linker, and hence the program compiles and run successfully.

Example:

#include <stdio.h> 
  
// Inline function in C 
static inline int foo() 

    return 2; 

  
int main() 

      int ret; 
    // inline function call 
    ret = foo(); 
      printf("Output is: %d\n", ret); 
    return 0; 
}

Output:
Output is: 2

“##” OPERATOR IN C


## is a pre-processor macro in C.

 It is used to concatenate 2 tokens into one token.
 
Example program:

#include<stdio.h>
#define concatination(a,b) a ## b

int main ()
{
   int ab = 1000;
   printf("The concatenated value is:%d \n",concatination(a,b));
   return 0;
}

Output:
 The concatenated value is: 1000

Cyclic nature of data types in C

 Some of the data types in C have special characteristic nature when a developer assign value beyond the range of the data type.
 There will be no compiler error and the value change according to a cyclic order. This is called cyclic nature and Char, int, long int data types have this property. 
Further float, double and long double data types do not have this property.

Difference between near, far and huge pointers


A virtual address is composed of the selector and offset.

A near pointer doesn't have explicit selector whereas far, and huge pointers have explicit selector. When you perform pointer arithmetic on the far pointer, the selector is not modified, but in case of a huge pointer, it can be modified.

These are the non-standard keywords and implementation specific. These are irrelevant to a modern platform.

getch() vs getche()


The getch() function reads a single character from the keyboard. It doesn't use any buffer, so entered data will not be displayed on the output screen.

The getche() function reads a single character from the keyword, but data is displayed on the output screen. Press Alt+f5 to see the entered character.

Let's see a simple example

#include<stdio.h>  
#include<conio.h>  
int main()  
{  
      
 char ch;  
 printf("Enter a character ");  

 ch=getch(); // taking an user input without printing the value.
  
 printf("\nvalue of ch is %c",ch);  
 printf("\nEnter a character again ");  

 ch=getche(); // taking an user input and then displaying it on the screen.  

  printf("\nvalue of ch is %c",ch);  
 return 0;  
}  

Output:

Enter a character
value of ch is a
Enter a character again a
value of ch is a

In the above example, the value entered through a getch() function is not displayed on the screen while the value entered through a getche() function is displayed on the screen.

Token


The Token is an identifier. It can be constant, keyword, the string literal, etc. A token is the smallest individual unit in a program. C has the following tokens:


  • Identifiers: Identifiers refer to the name of the variables.

  • Keywords: Keywords are the predefined words that are explained by the compiler.

  • Constants: Constants are the fixed values that cannot be changed during the execution of a program.

  • Operators: An operator is a symbol that performs a particular operation.

  • Special characters: All the characters except alphabets and digits are treated as special characters.

Purpose of sprintf() function


The sprintf() stands for "string print." 
The sprintf() function does not print the output on the console screen. It transfers the data to the buffer. It returns the total number of characters present in the string.

Syntax
int sprintf ( char * str, const char * format, ... );  

Let's see a simple example

 #include<stdio.h>  
int main()  
{  
 char a[20];  
 int n=sprintf(a,"javaabhigyan");  
 printf("value of n is %d",n);  
 return 0;
}  

Output:

value of n is 12

malloc() Vs calloc()













Let's see the example of malloc() function.

#include<stdio.h>  
#include<stdlib.h>  
int main(){  
  int n,i,*ptr,sum=0;    
    printf("Enter number of elements: ");    
    scanf("%d",&n);    
    ptr=(int*)malloc(n*sizeof(int));  //memory allocated using malloc    
    if(ptr==NULL)                         
    {    
        printf("Sorry! unable to allocate memory");    
        exit(0);    
    }    
    printf("Enter elements of array: ");    
    for(i=0;i<n;++i)    
    {    
        scanf("%d",ptr+i);    
        sum+=*(ptr+i);    
    }    
    printf("Sum=%d",sum);    
    free(ptr);     
return 0;  
}    

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30



Let's see the example of calloc() function.

#include<stdio.h>  
#include<stdlib.h>  
int main(){  
 int n,i,*ptr,sum=0;    
    printf("Enter number of elements: ");    
    scanf("%d",&n);    
    ptr=(int*)calloc(n,sizeof(int));  //memory allocated using calloc    
    if(ptr==NULL)                         
    {    
        printf("Sorry! unable to allocate memory");    
        exit(0);    
    }    
    printf("Enter elements of array: ");    
    for(i=0;i<n;++i)    
    {    
        scanf("%d",ptr+i);    
        sum+=*(ptr+i);    
    }    
    printf("Sum=%d",sum);    
    free(ptr);    
return 0;  
}    

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10

Sum=30

Usage of the pointer in C


  • Accessing array elements: Pointers are used in traversing through an array of integers and strings. The string is an array of characters which is terminated by a null character '\0'.

  • Dynamic memory allocation: Pointers are used in allocation and deallocation of memory during the execution of a program.

  • Call by Reference: The pointers are used to pass a reference of a variable to other function.

  • Data Structures like a tree, graph, linked list, etc: The pointers are used to construct different data structures like tree, graph, linked list, etc.


Call by value vs Call by reference in C

 Following are the differences between a call by value and call by reference are:












Example of a call by value:

#include <stdio.h>  
void change(int,int);  
int main()  
{  
    int a=10,b=20;  
    change(a,b); //calling a function by passing the values of variables.  
   
 printf("Value of a is: %d",a);  
    printf("\n");  
    printf("Value of b is: %d",b);  
    return 0;  
}  
void change(int x,int y)  
{  
    x=13;  
    y=17;  
}  

Output:

Value of a is: 10
Value of b is: 20


Example of call by reference:

#include <stdio.h>  
void change(int*,int*);  
int main()  
{  
    int a=10,b=20;  
    change(&a,&b); // calling a function by passing references of variables.  

    printf("Value of a is: %d",a);  
    printf("\n");  
    printf("Value of b is: %d",b);  
    return 0;  
}  
void change(int *x,int *y)  
{  
    *x=13;  
    *y=17;  
}  

Output:

Value of a is: 13
Value of b is: 17

Use of the function in C

Uses of C function are:


  • C functions are used to avoid the rewriting the same code again and again in our program.
  • C functions can be called any number of times from any place of our program.
  • When a program is divided into functions, then any part of our program can easily be tracked.
  • C functions provide the reusability concept, i.e., it breaks the big task into smaller tasks so that it makes the C program more understandable.

Use of a static variable in C


Following are the uses of a static variable:

  • A variable which is declared as static is known as a static variable. The static variable retains its value between multiple function calls.
  • Static variables are used because the scope of the static variable is available in the entire program. So, we can access a static variable anywhere in the program.
  • The static variable is initially initialized to zero. If we update the value of a variable, then the updated value is assigned.
  • The static variable is used as a common value which is shared by all the methods.
  • The static variable is initialized only once in the memory heap to reduce memory usage.

Local variable vs global variable in C

Following are the differences between a local

 variable and global variable:

Local variable                                       
  • Declaration:
A variable which is declared inside the function
 or block is known as a local variable.


  • Scope:
The scope of a variable is available within a
 function in which they are declared.

  • Access:
Variables can be accessed only by those
 statements inside a function in which
 they are declared.

  • Life:
Life of a variable is  created  when the function
 the block is entered and destroyed on its exit.

  • Storage
Variables are stored in a stack unless
 specified.

  • Example:
void function1(){
int x=10;
}

    Global variable

  • Declaration:
 A variable which is declared outside function or block is known as a global variable.

  • Scope:
The scope of a  variable is available throughout the program.

  • Access:
Any statement in the entire the program 
can access variables.

  • Life:
Life of a variable exists until the program 
is executing.

  • Storage
The compiler decides the storage location
 of a variable.

  • Example:
int value=20;
void function1(){
int x=10;

C Basic Question

1) What is C language?

C is a mid-level and procedural programming language. The Procedural programming language is also known as the structured programming language is a technique in which large programs are broken down into smaller modules, and each module uses structured code. This technique minimizes error and misinterpretation. 

2) Why is C known as a mother language?

C is known as a mother language because most of the compilers and JVMs are written in C language. Most of the languages which are developed after C language has borrowed heavily from it like C++, Python, Rust, javascript, etc. It introduces new core concepts like arrays, functions, file handling which are used in these languages. 

3) Why is C called a mid-level programming language?

C is called a mid-level programming language because it binds the low level and high -level programming language. We can use C language as a System programming to develop the operating system as well as an Application programming to generate menu driven customer driven billing system.

4) Who is the founder of C language?

Dennis Ritchie.

5) When was C language developed?

C language was developed in 1972 at bell laboratories of AT&T.

Assembly program in C

We can write an assembly program code inside c language program. In such case, all the assembly code must be placed inside asm{} block.

Let's see a simple assembly program code to add two numbers in the c program.

#include<stdio.h>  
void main() {  
   int a = 10, b = 20, c;  
     asm {  
      mov ax,a  
      mov bx,b  
      add ax,bx  
      mov c,ax  
   }  
   
   printf("c= %d",c);  
}  

Output:

c= 30

Note: We have executed this program on TurboC.

Command Line Arguments in C


The arguments passed from the command line are called command line arguments. These arguments are handled by the main() function.

To support command line argument, you need to change the structure of the main() function as given below.

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

Here, argc counts the number of arguments. It counts the file name as the first argument.

The argv[] contains the total number of arguments. The first argument is the file name always.

Example
Let's see the example of command line arguments where we are passing one argument with file name.

#include <stdio.h>  
void main(int argc, char *argv[] )  {  
  
   printf("Program name is: %s\n", argv[0]);  
   
   if(argc < 2){  
      printf("No argument passed through command line.\n");  
   }  
   else{  
      printf("The First argument is: %s\n", argv[1]);  
   }  
}  

Run this program as follows in Linux:

./program hello  

Run this program as follows in Windows from the command line:

program.exe hello  


Output:

Program name is: program
The first argument is: hello


If you pass many arguments, it will print only one.

./program hello c how r u  

Output:
Program name is: program
The first argument is: hello

But if you pass many arguments within the double quote, all arguments will be treated as a single argument only.

./program "hello c how r u"  

Output:

Program name is: program
The first argument is: hello c how r u

You can write your program to print all the arguments. In this program, we are printing only argv[1], that is why it is printing only one argument.

C #pragma


The #pragma preprocessor directive is used to provide additional information to the compiler. The #pragma directive is used by the compiler to offer a machine or operating-system feature.

Syntax:
#pragma token  

Different compilers can provide different usage of the #pragma directive.


The turbo C++ compiler supports following  #pragma directives.

  • #pragma argsused  
  • #pragma exit  
  • #pragma hdrfile  
  • #pragma hdrstop  
  • #pragma inline  
  • #pragma option  
  • #pragma saveregs  
  • #pragma startup  
  • #pragma warn  


Let's see a simple example to use #pragma preprocessor directive.

#include<stdio.h>  
#include<conio.h>  
  
void func() ;  
  
#pragma startup func  
#pragma exit func  
  
void main(){  
printf("\nI am in main");  
getch();  
}  
  
void func(){  
printf("\nI am in func");  
getch();  
}
  
Output:

I am in func
I am in main
I am in func

C #define


The #define preprocessor directive is used to define constant or micro substitution. It can use any basic data type.

Syntax:
#define token value  

Let's see an example of #define to define a constant.

#include <stdio.h>  
#define PI 3.14  
main() {  
   printf("%f",PI);  
}  

Output:

3.140000


Let's see an example of #define to create a macro.

#include <stdio.h>  
#define MIN(a,b) ((a)<(b)?(a):(b))  
void main() {  
   printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));    
}  

Output:

Minimum between 10 and 20 is: 10

C #include


The #include preprocessor directive is used to paste the code of given file into the current file. It is used include system-defined and user-defined header files. If included file is not found, compiler renders error.

By the use of #include directive, we provide information to the preprocessor where to look for the header files. There are two variants to use #include directive.

#include <filename>
#include "filename"

The #include <filename> tells the compiler to look for the directory where system header files are held. In UNIX, it is \usr\include directory.


The #include "filename" tells the compiler to look in the current directory from where the program is running.

#include directive example

Let's see a simple example of the #include directive. In this program, we are including stdio.h file because printf() function is defined in this file.

#include<stdio.h>  
 int main(){    
   printf("Hello C");      
   return 0;  
 }   
Output:

Hello C

#include notes:

  • Note 1: In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename.

  • Note 2: In the #include directive, the backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename.

  • Note 3: You can use the only comment after filename otherwise it will give the error.