C Questions

1.What is c?
C is a high-level and general-purpose programming language that is ideal for developing firmware or portable applications. Originally intended for writing system software, C was developed at Bell Labs by Dennis Ritchie for the Unix Operating System in the early 1970s.
2. Why C is called the mother of all language ?
C is reliable, simple and easy to use. Most of the compliers and JVMS are writtern in C language.
3.Who is the founder of C language ?
Dennis Ritche KodNest Dennis Ritchie
 
4.List down features of the C languages ?

  • It is a robust language with rich set of built-in functions and operators that can be used to write any complex program.
  • The C compiler combines the capabilities of an assembly language with features of a high-level language.
  • Programs Written in C are efficient and fast. This is due to its variety of data type and powerful operators.
  • It is many time faster than BASIC.
  • C is highly portable this means that programs once written can be run on another machines with little or no modification.
  • Another important feature of C program, is its ability to extend itself.
  • A C program is basically a collection of functions that are supported by C library. We can also create our own function and add it to C library.
  • C language is the most widely used language in operating systems and embedded system development today.

5. What is the purpose of printf and scanf in C ?
printf(): The printf() function is used to print the integer, character, float and string values on to the screen.
Following are the format specifier:

  • %d: It is a format specifier used to print an integer value.
  • %s: It is a format specifier used to print a string.
  • %c: It is a format specifier used to display a character value.
  • %f: It is a format specifier used to display a floating point value.

scanf(): The scanf() function is used to take input from the user.
6. What do you understand by word static variable ?
    Static variables are the variables which retain their values between the function calls. They are initialized only once their scope is within the function in which they are defined.
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 the memory usage.

7. What is Pointer ?
Pointers are variables which stores the address of another variable. That variable may be ascalar (including another pointer), or an aggregate (array or structure). The pointed-to object may be part of a larger object, such as a field of a structure or an element in an array.
For example:

  1. Data_type *p;  

The above syntax tells that p is a pointer variable that holds the address number of a given data type value.

Example of pointer
#include <stdio.h>
 int main()  {  
  int *p; //pointer of type integer.  
  int a=5;  
  p=&a;  
  printf("Address value of 'a' variable is %u",p);  
  return 0;
 }
 Output:Address value of 'a' variable is 428781252

8. Write a note on use of pointer ?
Pointer is used in the following cases
        i) It is used to access array elements.
       ii) It is used for dynamic memory allocation.
       iii) It is used in Call by reference
       iv) It is used in data structures like trees, graph, linked list etc.

  • 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.

9. What is Structure ?
Structure constitutes a super data type which represents several different data types in a single unit. A structure can be initialized if it is static or global.

  • The structure members can be accessed only through structure variables.
  • Structure variables accessing the same structure but the memory allocated for each variable will be different.

Syntax of structure

struct structure_name
{
  Member_variable1;
 Member_variable2
.
.
}[structure variables];

Let’s see a simple example.

#include <stdio.h>
struct student
{
    char name[10];       // structure members declaration.
    int age;
}s1;      //structure variable
int main()
{
    printf("Enter the name");
    scanf("%s",s1.name);
    printf("\n");
    printf("Enter the age");
    scanf("%d",&s1.age);
    printf("\n");
    printf("Name and age of a student: %s,%d",s1.name,s1.age);
    return 0;
}
Output:
Enter the name ABC

10. What is Union ?
Union is a collection of heterogeneous data type but it uses efficient memory utilization technique by allocating enough memory to hold the largest member. Here a single area of memory contains values of different types at different time. A union can never be initialized.

  • In union, we can access only one variable at a time as it allocates one common space for all the members of a union.

Syntax of union

union union_name
{
Member_variable1;
Member_variable2;
.
.
Member_variable n;
}[union variables];

Let’s see a simple example

#include<stdio.h>
union data
{
    int a;      //union members declaration.
    float b;
    char ch;
};
int main()
{
  union data d;       //union variable.
  d.a=3;
  d.b=5.6;
  d.ch='a';
  printf("value of a is %d",d.a);
  printf("\n");
  printf("value of b is %f",d.b);
  printf("\n");
  printf("value of ch is %c",d.ch);
  return 0;
}
Output:
value of a is 1085485921
value of b is 5.600022
value of ch is a

11. Difference between structures and union.
A structure variable contains each of the named members, and its size is large enough to hold all the members. Structure elements are of same size.
A union contains one of the named members at a given time and is large enough to hold the largest member. Union element can be of different sizes.

Struct
Used for storing various data types that when aggregated, represent a user-defined data type.
Occupies space for each of the inner parameters.
All members store some value at any point in time.
Union
Used for storing one of many data types that are available.
Occupies space equivalent to the parameter with the highest size
Exactly one member stores a value at any particular instance

12. Difference between structures and arrays ?
Structure is a collection of heterogeneous data type but array is a collection of homogeneous data types.
Array
1-It is a collection of data items of same data type.
2-It has declaration only
3-.There is no keyword.
4- array name represent the address of the starting element.
Structure
1-It is a collection of data items of different data type.
2- It has declaration and definition
3- keyword struct is used
4-Structure name is known as tag it is the short hand notation of the declaration.
Syntax :- Array – type array_name[size];
Structure- struct sruct_name{  type element1;  type element1;
Memory :-  Array – Array elements are stored in contiguous memory location.
Structure – Structure elements may not be stored in a contiguous memory location.
Operator :-  Array – Array declaration and element accessing operator is “[ ]” (square bracket).
Structure – Structure element accessing operator is “.” (Dot operator).
Pointer :- Array – Array name points to the first element in that array so, array name is a pointer.
Structure – Structure name does not point to the first element in that structure so, structure name is not a pointer.
Access :- Array –  Array elements are accessed by their index number.
Structure – Structure elements are accessed by their names.
Objects :- Array – Objects (instances) of an array can not be created.
Structure – Structure objects (instance or structure variable) can be created.
Size :-   Array – Every element in array is of same size.
Structure – Every element in a structure is of different data type.
Bit field :- Array –Bit field can not be defined in an array.
Structure – Bit field can be defined in a structure.
UserDefined :- Array – Arrays are not user-defined they are directly declared.
&nbps &nbps Structurre – Structure is a user-defined datatype.
Searching :- Array – Searching an array element takes less time.
Structure – Searching a structure element takes comparatively more time than an array element.
13. Is function declared or defined in header file ?
Functions are declared within header file. That is function prototypes exist in a header file,not function bodies. They are defined in library (lib).
14.Difference between malloc() and calloc() ?
Malloc Calloc 1-Malloc takes one argument Malloc(a);where a number of bytes 2-memoryallocated contains garbage values 1-Calloc takes two arguments Calloc(b,c) where b no of object and c size of object
2-It initializes the contains of block of memory to zerosMalloc takes one argument, memory allocated contains garbage values.
It allocates contiguous memory locations. Calloc takes two arguments, memory allocated contains all zeros, and the memory allocated is not contiguous.

malloc()
The malloc() function allocates a single block of requested memory.
It initializes the content of the memory to zero.
It consists of two arguments.
It returns a pointer pointing to the allocated memory.
calloc()
The calloc() function allocates multiple blocks of requested memory.
It does not initialize the content of memory, so it carries the garbage value.
It consists of only one argument.
It returns a pointer pointing to the allocated memory.

15.What is macros ? Explain it advantages and disadvantages.
Macros are abbreviations for lengthy and frequently used statements. When a macro is
called the entire code is substituted by a single line though the macro definition is of several lines.
The advantage of macro is that it reduces the time taken for control transfer as in case of function. The disadvantage of it is here the entire code is substituted so the program becomes lengthy if a macro is called several times.
16. Difference between pass by reference and  pass by values.
Pass by reference passes a pointer to the value. This allows the callee to modify the variable directly.Pass by value gives a copy of the value to the callee. This allows the callee to modify the value without modifying the variable. (In other words, the callee simply cannot modify the variable, since it lacks a reference to it.)

Call by reference
When a copy of the value is passed to the function, then the original value is not modified.
Actual arguments and formal arguments are created in separate memory locations.
In this case, actual arguments remain safe as they cannot be modified.
The copies of the actual arguments are passed to the formal arguments.
Call by value
When a copy of the value is passed to the function, then the original value is modified.
Actual arguments and formal arguments are created in the same memory location.
In this case, actual arguments are not reliable, as they are modified.
The addresses of actual arguments are passed to their respective formal arguments.

17. What is static identifier ?
A file-scope variable that is declared static is visible only to functions within that file. A
function-scope or block-scope variable that is declared as static is visible only within that scope. Furthermore, static variables only have a single instance. In the case of function- or block-scope variables, this means that the variable is not ―automatic‖ and thus retains its value across function invocations.
18. Difference between arrays and linked list ?

ARRAY
Array is a collection of elements of similar data type.
In an array, elements are stored in contiguous memory location or
consecutive manner in the memory.
In array, Insertion and Deletionoperation takes more time,
as the memory locations are consecutive and fixed.
Memory is allocated as soon as the array is declared, at compile time.
It’s also known as Static Memory Allocation.
In array, each element is independent and can be accessed using it’s index value.
Array can single dimensional, two dimensional or multidimensional
Size of the array must be specified at time of array decalaration.
Array gets memory allocated in the Stack section.
Linked List
Linked List is an ordered collection of elements of same type,
which are connected to each other using pointers.
In a linked list, new elements can be stored anywhere in the memory.
In case of linked list, a new element is stored at the first free and available memory location.
Memory is allocated at runtime, as and when a new node is added.
It’s also known as Dynamic Memory Allocation.
In case of a linked list, each node/element points to the next, previous, or maybe both nodes.
Linked list can be Linear(Singly), Doubly or Circular linked list.
Size of a Linked list is variable. It grows at runtime, as more nodes are added to it.
Linked list memory gets allocated in Heap section.

19. What is enumerations ?
An enum is a keyword, it is an user defined data type. All properties of integer are applied on Enumeration data type so size of the enumerator data type is 2 byte. It work like the Integer.
It is used for creating an user defined data type of integer. Using enum we can create sequence of integer constant value.

Syntax

enum tagname {value1, value2, value3,....};

20. What is register variables ? What are the advantages of it.
If a variable is declared with a register storage class,it is known as register variable.The register variable is stored in the cpu register instead of main memory.Frequently used variables are declared as register variable as it‘s access time is faster.
21.What is typedef?
typedef is a C keyword implemented to tell the compiler for assigning an alternative name to C’s already exist data types. This keyword, typedef typically employed in association with user-defined data types in cases if the names of datatypes turn out to be a little complicated or intricate for a programmer to get or to use within programs. The typical format for implementing this typedef keyword is:
Syntax:

typedef <existing_names_of_datatype> <alias__userGiven_name>;

22.What is storage class. Explain different type of storage class.
Storage class defines the scope (visibility) and life-time of variables and/or functions within a C Program. They precede the type that they modify. We have four different storage classes in a C program −

  • auto
  • register
  • static
  • extern

The auto Storage Class

The auto storage class is the default storage class for all local variables.

{  
 int mount;   
auto int month;
}

The example above defines two variables with in the same storage class. ‘auto’ can only be used within functions, i.e., local variables.

The register Storage Class

The register storage class is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and can’t have the unary ‘&’ operator applied to it (as it does not have a memory location).

{
register int miles;

The register should only be used for variables that require quick access such as counters. It should also be noted that defining ‘register’ does not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register depending on hardware and implementation restrictions.

The static Storage Class

The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls.
The static modifier may also be applied to global variables. When this is done, it causes that variable’s scope to be restricted to the file in which it is declared.
In C programming, when static is used on a global variable, it causes only one copy of that member to be shared by all the objects of its class.

#include <stdio.h>
void func(void);
static int count = 5; /* global variable */
main() {  
 while(count--) {
    func();
  }  
 return 0;
}
/* function definition */
void func( void ) {  
 static int i = 5; /* local static variable */
  i++;
  printf("i is %d and count is %d\n", i, count);
}

When the above code is compiled and executed, it produces the following result.

i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0

 

The extern Storage Class

The extern storage class is used to give a reference of a global variable that is visible to ALL the program files. When you use ‘extern’, the variable cannot be initialized however, it points the variable name at a storage location that has been previously defined.
When you have multiple files and you define a global variable or function, which will also be used in other files, then extern will be used in another file to provide the reference of defined variable or function. Just for understanding, extern is used to declare a global variable or function in another file.
The extern modifier is most commonly used when there are two or more files sharing the same global variables or functions as explained below.
First File: main.c

#include <stdio.h>
int count ;
extern void write_extern();
main() {
  count = 5;
  write_extern();
}

Second File: support.c

#include <stdio.h>
extern int count;
void write_extern(void) {   
printf("count is %d\n", count);
}

Here, extern is being used to declare count in the second file, where as it has its definition in the first file, main.c. Now, compile these two files as follows −
$gcc main.c support.c
It will produce the executable program a.out. When this program is executed, it produces the following result −
count is 5
23. What is far pointer ? Where are we using it.
A far pointer is typically 32 bit that can access memory outside current segment.  To use this, compiler allocates a segment register to store segment address, then another register to store offset within current segment.
24. What is huge pointer ?
Huge pointer is 32bit long containing segment address and offset address. Huge pointers are normalized pointers so for any given memory address there is only one possible huge address segment: offset pair. Huge pointer arithmetic is doe with calls to special subroutines so its arithmetic slower than any other pointers.
25.What is normalized pointer ?
It is a 32bit pointer, which has as much of its value in the segment register as possible. Since a segment can start every 16bytes so the offset will have a value from 0 to F. for normalization convert the address into 20bit address then use the 16bit for segment address and 4bit for the offset address. Given a pointer 500D: 9407, we convert it to a 20bitabsolute address 549D7, Which then normalized to 549D:0007.
26.What is near pointer ?
Near pointer is used to store 16 bit addresses means within current segment on a 16 bit machine. The limitation is that we can only access 64kb of data at a time.
27. What is void pointer ?
A void pointer is a pointer that has no associated data type with it. A void pointer can hold address of any type and can be typcasted to any type.

int a = 10;
char b = 'x';
 void *p = &a;  // void pointer holds address of int 'a'
p = &b; // void pointer holds address of char 'b'

Advantages of void pointers:
1) malloc() and calloc() return void * type and this allows these functions to be used to allocate memory of any data type (just because of void *)

int main(void)
{  
  // Note that malloc() returns void * which can be    
 // typecasted to any type like int *, char *, ..
   int *x = malloc(sizeof(int) * n);
}

2) void pointers in C are used to implement generic functions in C.
  void pointers cannot be dereferenced. For example the following program doesn’t compile.

#include<stdio.h>
int main(){    
int a = 10;
    void *ptr = &a;   
 printf("%d", *ptr);   
 return 0;
}
Output:Compiler Error: 'void*' is not a pointer-to-object type

The following program compiles and runs fine.

#include<stdio.h>
int main()
{
  int a = 10;   
  void *ptr = &a;   
  printf("%d", *(int *)ptr);
   return 0;
}
Output:10

 The C Standard doesn’t allow pointer arithmetic with void pointers. However, in GNU C it is allowed by considering the size of void is 1. For example the following program compiles and runs fine in gcc.

#include<stdio.h>
int main(){
  int a[2] = {1, 2};    
  void *ptr = &a;    
  ptr = ptr + sizeof(int);  
  printf("%d", *(int *)ptr);    
  return 0;}
 Output:2

28. What is Null Pointer ?
NULL Pointer is a pointer which is pointing to nothing. In case, if we don’t have address to be assigned to a pointer, then we can simply use NULL.

#include <stdio.h>
int main(){    
// Null Pointer   
 int *ptr = NULL;    
 printf("The value of ptr is %u", ptr);   
 return 0;
}
Output :The value of ptr is 0

Important Points

  1. NULL vs Uninitialized pointer – An uninitialized pointer stores an undefined value. A null pointer stores a defined value, but one that is defined by the environment to not be a valid address for any member or object.
  2. NULL vs Void Pointer – Null pointer is a value, while void pointer is a type.

29. What is wild pointer >
A pointer which has not been initialized to anything (not even NULL) is known as wild pointer. The pointer may be initialized to a non-NULL garbage value that may not be a valid address.

int main(){
    int *p;  /* wild pointer */    
    int x = 10;    // p is not a wild pointer now  
    p = &x  
    return 0;
}

30.What is generic pointer in c ?
In C void* acts as a generic pointer. When other pointer types are assigned to generic pointer, conversions are applied automatically (implicit conversion).
31.What is static memory allocation ?
In case of static memory allocation, memory is allocated at compile time, and memory can’t be increased while executing the program. It is used in the array.
The lifetime of a variable in static memory is the lifetime of a program.
The static memory is allocated using static keyword.
The static memory is implemented using stacks or heap.
The pointer is required to access the variable present in the static memory.
The static memory is faster than dynamic memory.
In static memory, more memory space is required to store the variable.
For example:  

int a[10];

32.What is dynamic memory allocation ?
In case of dynamic memory allocation, memory is allocated at runtime and memory can be increased while executing the program. It is used in the linked list.
The malloc() or calloc() function is required to allocate the memory at the runtime.
An allocation or deallocation of memory is done at the execution time of a program.
No dynamic pointers are required to access the memory.
The dynamic memory is implemented using data segments.
Less memory space is required to store the variable.
For example  

int *p = malloc(sizeof(int)*10;

33.What is Pointer of pointer ?
A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below.
A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional asterisk in front of its name. For example, the following declaration declares a pointer to a pointer of type int −

int **var;

34.Difference between linker and linkage.
Linker converts an object code into an executable code by linking together the necessary built in functions. The form and place of declaration where the variable is declared in a program determine the linkage of variable.
35.What is modular programming ?
Modular programming is the process of subdividing a computer program into separate sub-programs.
A module is a separate software component. It can often be used in a variety of applications and functions with other components of the system. Similar functions are grouped in the same unit of programming code and separate functions are developed as separate units of code so that the code can be reused by other applications.
Object-oriented programming (OOP) is compatible with the modular programming concept to a large extent. Modular programming enables multiple programmers to divide up the work and debug pieces of the program independently.
36. What is function in C ?
A function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions.
You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division is such that each function performs a specific task.
A function declaration tells the compiler about a function’s name, return type, and parameters. A function definition provides the actual body of the function.
37. What is an argument ?
An argument is an entity used to pass data from the calling to a called function.
38. What are built in functions ?
The system provided these functions and stored in the library. Therefore it is also called Library Functions.
e.g. scanf(), printf(), strcpy, strlwr, strcmp, strlen, strcat etc.
To use these functions, you just need to include the appropriate C header files.
39. Difference between formal argument and actual argument ?
Formal Arguments.
The arguments which are mentioned in function definition are called formal argument.
These arguments are used to just hold the value that is sent by calling function.
Formal arguments are like other local variables of the function which are created when function call starts and destroyed when end function.
Actual Arguments.
The arguments which are mentioned in the function in the functin call are known as calling function.
These are the values which are actual arguments called to the function.
It can be written as constant, function expression on any function call which return a value.
ex: funct(6,9), funct(a,b)
40. Difference between Array and Pointer ?
Array
1- Array allocates space automatically
2- It cannot be resized
3- It cannot be reassigned
4- sizeof (arrayname) gives the number of bytes occupied by the array.
Pointer
1-Explicitly assigned to point to an allocated space.
2-It can be sized using realloc()
3-pointer can be reassigned.
4-sizeof (p) returns the number of bytes used to store the pointer variable p.
41. What are tokens in C ?
There are six classes of tokens: identifier, keywords, constants, string literals, operators and
other separators.
42. What is C identifiers ?
In C language identifiers are the names given to variables, constants, functions and user-define data. These identifier are defined against a set of rules.

Rules for an Identifier

  • An Identifier can only have alphanumeric characters(a-z , A-Z , 0-9) and underscore(_).
  • The first character of an identifier can only contain alphabet(a-z , A-Z) or underscore (_).
  1. Identifiers are also case sensitive in C. For example name and Name are two different identifiers in C.
  2. Keywords are not allowed to be used as Identifiers.
  3. No special characters, such as semicolon, period, whitespaces, slash or comma are permitted to be used in or as Identifier.

When we declare a variable or any function in C language program, to use it we must provide a name to it, which identified it throughout the program, for example:

int myvariable = "WorkHard";

43. What is pre increment and post increment ?
Pre-increment operator: A pre-increment operator is used to increment the value of a variable before using it in a expression. In the Pre-Increment, value is first incremented and then used inside the expression.
Syntax:

a = ++x;

Here, if the value of ‘x’ is 10 then value of ‘a’ will be 11 because the value of ‘x’ gets modified before using it in the expression.

#include <iostream>
using namespace std;
  int main(){    
  int x = 10,
  a;     
  a = ++x;
  cout << "Pre Increment Operation";      
  // Value of a will change  
  cout << "\na = " << a;  
    // Value of x change before execution of a=++x;
   cout << "\nx = " << x;  
    return 0;
}
Output :Pre Increment Operationa = 11x = 11P

Post-increment operator: A post-increment operator is used to increment the value of variable after executing expression completely in which post increment is used. In the Post-Increment, value is first used in a expression and then incremented.
Syntax:

a = x++;

Here, suppose the value of ‘x’ is 10 then value of variable ‘b’ will be 10 because old value of ‘x’ is used.

#include <iostream>
using namespace std;
int main(){
int x = 10, a;
 a = x++;
  cout << "Post Increment Operation"; // Value of a will not change
  cout << "\na = " << a; // Value of x change after execution of a=x++;
  cout << "\nx = " << x;
  return 0;
}
Output:
Post Increment Operation
a = 10
x = 11

 
44.Difference between local and global variable in C ?

Local variable
A variable which is declared inside function or block is known as a local variable.
The scope of a variable is available within a function in which they are declared.
Variables can be accessed only by those statements inside a function in which they are declared.
Life of a variable is created when the function block is entered and destroyed on its exit.
Variables are stored in a stack unless specified.
Global Variable
A variable which is declared outside function or block is known as a global variable.
The scope of a variable is available throughout the program.
Any statement in the entire program can access variables.
Life of a variable exists until the program is executing.
The compiler decides the storage location of a variable.

 
45.What is recursion in C ?
When a function calls itself, and this process is known as recursion. The function that calls itself is known as a recursive function.
Recursive function comes in two phases:

  1. Winding phase
  2. Unwinding phase

Winding phase: When the recursive function calls itself, and this phase ends when the condition is reached.
Unwinding phase: Unwinding phase starts when the condition is reached, and the control returns to the original call.
Example of recursion

#include <stdio.h>
  int calculate_fact(int);
  int main()  {  
  int n=5,f;  
  f=calculate_fact(n); // calling a function
  printf("factorial of a number is %d",f);    
  return 0;  
}
 int calculate_fact(int a)  {  
 if(a==1)    {    
   return 1;  
  }   else {
   return a*calculate_fact(a-1); //calling a function recursively.     
}
 Output:factorial of a number is 120

46. What is an array ?
An Array is a group of similar types of elements. It has a contiguous memory location. It makes the code optimized, easy to traverse and easy to sort. The size and type of arrays cannot be changed after its declaration.
Arrays are of two types:

  • One-dimensional array: One-dimensional array is an array that stores the elements one after the another.

Syntax:

 data_type array_name[size];    
  • Multidimensional array: Multidimensional array is an array that contains more than one array.

Syntax:

data_type array_name[size];

Example of an array:

#include <stdio.h>
  int main()  {
  int arr[5]={1,2,3,4,5}; //an array consists of five integer values.  
  for(int i=0;i<5;i++)  {
      printf("%d ",arr[i]);  
   }    
   return 0;
 }
 Output:1 2 3 4 5

47. Can we run a program without main() function.
Yes, we can compile, but it can’t be executed.
But, if we use #define, we can compile and run a C program without using the main() function. For example:

#include<stdio.h>
#define start main  
  void start() {
      printf("Hello");
   }

48. What is command line argument ?
The argument passed to the main() function while executing the program is known as command line argument. For example:

main(int count, char *args[])
{
 //code to  be executed
 }

49. What is the acronym for ANSI ?
The ANSI stands for ” American National Standard Institute.” It is an organization that maintains the broad range of disciplines including photographic film, computer languages, data encoding, mechanical parts, safety and more.
50.Difference between getch() and 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 charactervalue of ch is a
Enter a character again a
value of ch is a

51.Maximum length of an identifier ?
It is 32 character.
52. What is typecasting ?
The typecasting is a process of converting one data type into another is known as typecasting. If we want to store the floating type value to an int type, then we will convert the data type into another data type explicitly.
Syntax:

(type_name)expression;

53.What is infinite loop ?
A loop running continuously for an indefinite number of times is called the infinite loop.
Infinite For Loop:

for(;;){
 //code to be executed
 }

Infinite While Loop:

while(1){  
//code to be executed
  }

Infinite Do-While Loop:

do{  
//code to be executed
  }while(1);

 
54. Wap to print hello world without using a ; ?

#include<stdio.h>  
    void main(){   
   if(printf("hello world")){} // This will print  hello world on the screen.
 }

55.What is bit fields ?
In C, you can state the size of your structure (struct) or union members in the form of bits. This concept is to because of efficiently utilizing the memory when you know that your amount of a field or collection of fields is not going to exceed a specific limit or is in-between the desired range.
56. What is preprocessor ?
Preprocessor is a program which will executed automatically before passing the source program to compiler. This process is called pre-processing. The preprocessor provides the ability for the inclusion of header files, macro expansions, conditional compilation, and line control.
The C Preprocessor is not a part of compiler, it is a separate program invoked by the compiler as the first part of translation.
Commands used in preprocessor are called preprocessor directives and they begin with pond “#” symbol and should be not ended with (;).
57. What is file ?
A collection of data which is stored on a secondary device like a hard disk is known as a file.
A file is generally used as real-life applications that contain a large amount of data.
There are two problems with such applications:

  1. I) It is time-consuming and unmanageable for handling such huge amount of data,
  2. II) When the I/O terminal is used the entire data is lost if the program is terminated or the computer is being turned off. So it is a compulsion for storing the data on a permanent device.

Files are divided into two types

  1. Stream-oriented – they are standard or high-level files. They are easier to work with than the sytem-oriented data-files and are used more commonly.
  2. System-oriented – they are low-level files.

 
The library functions which are used for operating the files are:

  1. High-level file I/O functions – they do their own buffer management.
  2. Low-level file I/O functions – the buffer management is done by the programmer.

58. What is stream ?
In C all input and output is done with streams

  1. Stream is nothing but the sequence of bytes of data
  2. A sequence of bytes flowing into program is called input stream
  3. A sequence of bytes flowing out of the program is called output stream
  4. Use of Stream make I/O machine independent.

Predefined Streams :

stdin          Standard Input
stdout       Standard Output
stderr       Standard Error
59. How is filed opened in C ?

Opening a file

Before opening any file, a file pointer needs to be established.
Syntax : Establishing a file pointer

FILE *fptr;

Where, FILE is the structure which is defined in the header file <stdio.h>.

  • A file should be opened before any operation is being performed on it.
  • The fopen() function is being used for opening the file.

Syntax:

FILE *fopen(const char *filename, const char *mode);

In the above syntax, filename is the literal which is used for naming the files.
They can be accessed by using the following modes:

Mode Description
“r” It opens an existing file for reading only.
“w” It opens a new file for writing.
If the filename does not exist it will be created and
if the file already exists then its contents are deleted.
“a” It appends the existing file. If the filename does not exist it will be created.
“r+” It opens an existing file for reading and writing.
It indicates that the file is to be read before writing.
“w+” It opens a new file for reading and writing.
If a file with the current filename exists then it is destroyed and
a new file name is created.
“a+” It opens an existing file for reading and appending.
Its stream is positioned at the end of the file content.

60. How is file closed in C ?

Closing a file

  • The fclose() function is used for closing a file.
  • When this function is used the file pointer is disconnected from a file.
    Syntax:

    int fclose(FILE *fp);

    Where, fp is the file pointer that points to the file that has to be closed.
    An integer value is returned which will indicate if the function was successful or not.

  • In addition to the fclose() function we even have the fcloseall() function which will close all the streams which are open currently except the standard streams (stdin, stdout and stderr).
    Syntax:

    intfcloseall(void)

    This function will flush any of the stream buffers and will return the number of streams which are closed.

Reading a file

Following are the list of functions which are used for reading a file:
fscanf() – Syntax –

int fscanf (FILE *stream, const char *format,....);

It is used for reading the formatted data from the stream.
fgets( ) – Syntax –

char *fgets(char *str, int size, FILE *stream);

It stands for file get string. It is used for getting the string from a stream.
fgetc( ) – Syntax –

int fgetc (FILE *stream);

It will return the next character from the stream from the end of the file or an error.
fread( ) – Syntax –

int fread(void *str, size_t size, size_t num, FILE *stream);

It is used for reading data from a file.
61. What is fseek() ?
fseek(): This function is used for seeking the pointer position in the file at the specified byte.
Syntax:

fseek( file pointer, displacement, pointer position);

Where file pointer —- It is the pointer which points to the file.
displacement —- It is positive or negative.This is the number of bytes which are skipped backward (if negative) or forward( if positive) from the current position.This is attached with L because this is a long integer.

Ex:

1) fseek( p,10L,0)
0 means pointer position is on beginning of the file,from this statement pointer position is skipped 10 bytes from the beginning of the file.
2)fseek( p,5L,1)
1 means current position of the pointer position.From this statement pointer position is skipped 5 bytes forward from the current position.
3)fseek(p,-5L,1)
From this statement pointer position is skipped 5 bytes backward from the current position.
62. What is ftell() ?
This function returns the value of the current pointer position in the file.The value is count from the beginning of the file.
Syntax:

ftell(fptr);

Where fptr is a file pointer.
Example program for fseek():

#include<stdio.h>
#include<conio.h>
 void main(){
     FILE *fp;
     char ch;
     clrscr();
     fp=fopen("file1.c", "r");
     if(fp==NULL) {
        printf("file cannot be opened");   
     }else{
        printf("Enter value of n  to read last ‘n’ characters");
        scanf("%d",&n); 
        fseek(fp,-n,2);
            while((ch=fgetc(fp))!=EOF) {
                 printf("%c\t",ch);            
            }
        }  
       fclose(fp);    
       getch();
    }
OUTPUT: It depends on the content in the file.

63. What is the use of rewind() function ?
The rewind() function sets the file pointer at the beginning of the stream. It is useful if you have to use stream many times.
Syntax:

void rewind(FILE *stream)

Example:
File: rew.c

#include<stdio.h>  
#include<conio.h>
 void main(){  
 FILE *fp;  
 char c;
 clrscr();
 fp=fopen("file.txt","r");
   while((c=fgetc(fp))!=EOF){  
   printf("%c",c);
 }    
   rewind(fp);//moves the file pointer at beginning of the file
   while((c=fgetc(fp))!=EOF){  
    printf("%c",c);  
   }  
   fclose(fp);   
   getch();
   }
   Output:this is a simple textthis is a simple text

 
64. What is a stack?
A stack is one form of a data structure. Data is stored in stacks using the FILO (First In Last Out) approach. At any particular instance, only the top of the stack is accessible, which means that in order to retrieve data that is stored inside the stack, those on the upper part should be extracted first. Storing data in a stack is also referred to as a PUSH, while data retrieval is referred to as a POP.
65.What is variable initialization and why is it important?
This refers to the process wherein a variable is assigned an initial value before it is used in the program. Without initialization, a variable would have an unknown value, which can lead to unpredictable outputs when used in computations or other operations.
66.What is the use of a ‘\0’ character?
It is referred to as a terminating null character, and is used primarily to show the end of a string value.
67. Difference between = symbol and == symbol ?
The = symbol is often used in mathematical operations. It is used to assign a value to a given variable. On the other hand, the == symbol, also known as “equal to” or “equivalent to”, is a relational operator that is used to compare two values.
68. What is a nested loop?
A nested loop is a loop that runs within another loop. Put it in another sense, you have an inner loop that is inside an outer loop. In this scenario, the inner loop is performed a number of times as specified by the outer loop. For each turn on the outer loop, the inner loop is first performed.
69. What are header files and what are its uses in C programming?
Header files are also known as library files. They contain two essential things: the definitions and prototypes of functions being used in a program. Simply put, commands that you use in C programming are actually functions that are defined from within each header files. Each header file contains a set of functions. For example: stdio.h is a header file that contains definition and prototypes of commands like printf and scanf.
70. What is syntax error?
Syntax errors are associated with mistakes in the use of a programming language. It maybe a command that was misspelled or a command that must was entered in lowercase mode but was instead entered with an upper case character. A misplaced symbol, or lack of symbol, somewhere within a line of code can also lead to syntax error.
71. Can we use  “int” data type to store the value 32768? Why?
No. “int” data type is capable of storing values from -32768 to 32767. To store 32768, you can use “long int” instead. You can also use “unsigned int”, assuming you don’t intend to store negative values.
72. How do you generate random numbers in C?
Random numbers are generated in C using the rand() command. For example: anyNum = rand() will generate any integer number beginning from 0, assuming that anyNum is a variable of type integer.
73. What is debugging?
Debugging is the process of identifying errors within a program. During program compilation, errors that are found will stop the program from executing completely. At this state, the programmer would look into the possible portions where the error occurred. Debugging ensures the removal of errors, and plays an important role in ensuring that the expected program output is met.
74.What are preprocessor directives?
Preprocessor directives are placed at the beginning of every C program. This is where library files are specified, which would depend on what functions are to be used in the program. Another use of preprocessor directives is the declaration of constants.Preprocessor directives begin with the # symbol.
75.Is it possible to initialize a variable at the time it was declared?
Yes, you don’t have to write a separate assignment statement after the variable declaration, unless you plan to change it later on.  For example: char planet[15] = “Earth”; does two things: it declares a string variable named planet, then initializes it with the value “Earth”.
76.What are linked list?
A linked list is composed of nodes that are connected with another. In C programming, linked lists are created using pointers. Using linked lists is one efficient way of utilizing memory for storage.
77.What are binary trees?
Binary trees are actually an extension of the concept of linked lists. A binary tree has two pointers, a left one and a right one. Each side can further branch to form additional nodes, which each node having two pointers as well.
78. Difference between the expression “++a” and “a++”?
In the first expression, the increment would happen first on variable a, and the resulting value will be the one to be used. This is also known as a prefix increment. In the second expression, the current value of variable a would the one to be used in an operation, before the value of a itself is incremented. This is also known as postfix increment.
79. What are multidimensional arrays?
Multidimensional arrays are capable of storing data in a two or more dimensional structure. For example, you can use a 2 dimensional array to store the current position of pieces in a chess game, or position of players in a tic-tac-toe program.
80.Is it possible to create your own header files?
Yes, it is possible to create a customized header file. Just include in it the function prototypes that you want to use in your program, and use the #include directive followed by the name of your header file.
81.What is gets() function?
The gets() function allows a full line data entry from the user. When the user presses the enter key to end the input, the entire line of characters is stored to a string variable. Note that the enter key is not included in the variable, but instead a null terminator \0 is placed after the last character.
82.What is the use of a semicolon (;) at the end of every program statement?
It has to do with the parsing process and compilation of the code. A semicolon acts as a delimiter, so that the compiler knows where each statement ends, and can proceed to divide the statement into smaller elements for syntax checking.
83.  List out some of C compilers ?
There are so many compilers available in market for Windows operating system and UNIX. We are listing some of them here for your reference.

  • AMPC
  • CCS C Compiler
  • ch
  • clang
  • cygwin
  • Digital mars
  • GCC compiler
  • MikroC Compiler
  • Portable C Compiler,Power C, QuickC, Ritchie C Compiler, Small– C.

84.What is translation unit ?
A translation unit is a set of files seen by the compiler.
It includes the source code under consideration and files that are included such as header files and other disk files contain C code.
85.What is lvalue and rvalue ?
The expression appearing on right side of the assignment operator is called as rvalue. Rvalue is assigned to lvalue, which appears on left side of the assignment operator. The lvalue should designate to a variable not a constant.

Related Articles

Core Java

1. What are primitive types in Java ? byte, short, int, long, float, double, char, boolean… 2. What are tokens? Name the 5 types of tokens available in Java with an example…

C Programming

1. Wap to check if the given number is armstrong number or not. #include<stdio.h> #include<conio.h> void main(){ int a,t,l,sum=0; printf(“\nPlease enter your number\n”); scanf(“%d”,&a); t=a;…

Hackerearth-Java

     1. Challenge : Welcome to Java! Welcome to the world of Java! In this challenge, we practice printing to stdout. The code stubs…

Responses

Your email address will not be published. Required fields are marked *

KodNest Training New Batch is starting on 21st September 2020. Attend one week free demo classes.Register Now

New Report

Close