YouTube Icon

Interview Questions.

50+ Best C Interview Questions - Sep 08, 2021

fluid

50+ Best C Interview Questions

Despite being almost 50 years antique, C continues to be main the programming scene from the vanguard. The programming language has a extensive kind of packages and is likewise the foundation for a variety of modern-day, effective programming languages, such as Java, C#, and Python.

Although there are only a few job profiles these days that handiest require a excessive-level skillability in C, maximum programming jobs necessitate a terrific know-how of the C programming language's essential ideas. So, many programming task interviews involve C Interview questions and answers.

Best C Interview Questions and Answers

If you’re making ready for C programming interview questions, then you’ve landed at the proper spot. Here are forty+ quality C interview questions to help you get going for that process interview or to genuinely self-investigate how proper you’ve gotten with the overall-cause, procedural programming language:

Basic Level Interview Questions

Question: List some of the most important capabilities of the C programming language.

Answer: C supports a plethora of superb functions. Most crucial among them are:

Extensibility - Capable of adopting new capabilities.

Fast - Support for system programming permits quicker compilation and execution than popular excessive-stage languages like Java and Python.

Memory Management - Comes with integrated memory management for saving memory and optimizing reminiscence use.

Middle-Level Programming Language - Binds the gap among a device-level language and a high-stage language. It may be used for gadget programming in addition to utility programming.

Platform independence/Portability - A C application written for one device can run on other machines with little to no modifications.

Simplicity - Follows the established method. Facilitates breaking down a big, complicated software into smaller, unbiased, and clean-to-control modules (sub-applications).

Question: Please explain a header file in C? What will occur if we consist of a header document two times in a C application?

Answer: Header documents keep the definitions and set of policies governing the C programming language's exclusive integrated features. For example, the printf() and scanf() functions are described inside the stdio.H header report.

Every header file incorporates a hard and fast of predefined capabilities, meant to make programming in C easier. You need to encompass the particular header record on your C software on the way to use the capabilities defined in it. For instance, you could’t use print(), and scanf() functions without inclusive of the stdio.H header report.

When a header report is blanketed two times in a C software, the second gets unnoticed. In actual, the #, known as the encompass defend, previous a header report ensures that it is covered handiest as soon as all through the compilation manner.

Question: What do you already know about the C language, and who invented it and when?

Answer: The C language is one of the most usually used pc programming languages. The language is used by giving little by little instructions, which makes it a procedural language. It is a extensively used language that enables carry out systematic programming, lexical variable scope, and recurrent. C language, which is among the maximum famous languages, had its foundation within the early 1970s in America. American pc scientist Dennis M. Ritchie advanced it at Bell Laboratories. Since then, it has served humankind within the satisfactory feasible manner and has helped in growing several gadget packages.

Question: Why is the C language called “The mother of programming languages”?

Answer: The C language is normally called the “The mom of programming languages” as it's miles the language that forms the bases of programming. It is a time-honoured language and has been broadly used to develop some of the maximum great compilers and kernels. C language is as old as the hills, and maximum of the present day languages are nothing however an version from the C languages.

Question: What are the benefits of using C language over different programming languages?

Answer: C language has the threshold over the other programming language, which virtually makes it “The mother of programming language.” Some of the blessings of the use of C language are said underneath:

Middle – Level Language: As the C language is within the midway of a excessive-stage language and low-degree language, it brings together the capabilities of both of them. So this one of a kind function of the language makes it possible to be used for low as well as high-stage programming.

Structured Level Language: C language is a structured programming language that lets in a complex program to be divided into less difficult programs called the features. Thus making it quite a person pleasant.

Case Sensitive Language: It is a case sensitive language because of which the lower and the upper case letters are handled differently.

Portable Language: C language is a particularly flexible language that enables it for use for scripting gadget packages, which makes it part of many well known operating structures.

Powerful and Efficient Language: It is a person-pleasant language and may efficiently perform on games, photographs, organisation applications, packages that need a few calculations, and so forth.

Question: What are a number of the restrictions of C language?

Answer: As the entirety has a finite capacity, so the C language stands in no exception. The following are a number of the drawbacks of C languages:

Concept of OOPs: C language prohibits the idea of OOPs as it's miles based totally at the procedural method. (Inheritance, Polymorphism, Encapsulation, Abstraction, Data Hiding).

Run Time Checking: C language does no longer do the running checking which means that that mistakes are not detected after each line of coding, however simplest as soon as the entire coding is accomplished making it inconvenient to correct the bugs

Concept of the Namespace: C language does no longer show off Namespace's assets, so there cannot be two variables with the same name within the C language application.

Lack of Exception Handling: The language doesn’t showcase the important feature of exception coping with. The characteristic of exception managing doesn’t allow the user to locate the errors and insects whilst compiling the code.

Insufficient Level for Abstraction: C language doesn’t have a completely extensive information managing capacity, which poses a hazard to the safety of the language.

Question: What is the goal of the main () feature in C?

Answer: The fundamental () characteristic in C language to the inlet to the C application. It is the access point wherein the system of execution of this system starts. When the C application's execution initiates, the control of the program is directed toward the primary () function. It is mandatory that each C language application has a primary () characteristic. Although it is the feature that indicates the programming method, it is not the primary feature to be completed.

Question: What may be understood by variable and steady?

Answer: In C language, both constant and variable is widely used even as designing a application. The major difference is between variables, and consistent is that variable can alter its assigned fee at any point of the program. In comparison, the value of the constant remains unaltered in the course of the complete program. The price of the constant is locked all through the execution of this system. For example, pi's cost may be set as a constant at some point of the entire direction of the program.

Question: Distinguish among the header file within angular braces < > and double fees “.

Answer: Quite a distinction is observed when the header report is placed inside the angular braces < > and in the double-charges. If the header document is placed in the angular braces < >, then the compiler finds out the specific header document only within the built-in encompass direction. But if the header report is placed inside the double rates, “then the compiler tries to discover the unique header record in the main in the modern-day running directory, and if it can't be placed there, then it searches inside the integrated protected path.

Question: Does a C software assemble without the primary() characteristic succeeds in compiling? What about its execution?

Answer: Yes, a C software can be compiled even without adding the principle() function. However, it'll no longer execute with out the primary() feature.

Question: Enumerate the basic statistics kinds in C?

Answer: There are five basic statistics types in C:

int - Stores an integer wide variety

go with the flow - Stores a decimal number

double - Stores a decimal number with the highest precision

char - Stores a single man or woman

void - Stores no cost

Question: What do you imply with the aid of reserved key phrases? How many reserved key phrases are there in C?

Answer: Words which can be limited for standard use even as writing a software, i.E., for the usage of as a name for a variable, feature, shape, and so forth. Are known as reserved key phrases. Reserved keywords, additionally called reserved names, have unique meanings, i.E., they're already defined for something. The C programming language has the following 32 reserved keywords:

automobile

smash

case

char

const

keep

default

do

double

else

enum

extern

flow

for

goto

if

int

long

register

return

short

signed

sizeof

static

struct

switch

typedef

union

unsigned

void

volatile

while

Question: How are worldwide variables distinct from static variables?

Answer: Global variables are variables with global scope, i.E., they are accessible at some stage in this system, until shadowed. These variables are defined outside a function or code block. Static variables are variables allocated statically, i.E., their price can’t be modified. It is constant for the whole run of a software. They can be defined outdoor as well as inside functions. Moreover, they can be accessed from anywhere inside the program.

Question: Please evaluate static memory allocation with dynamic reminiscence allocation?

Answer: Following are the critical variations among static and dynamic modes of reminiscence allocation:

Memory growth:

In dynamic memory allocation, memory can be extended whilst executing the program. However, this isn't the case with the static memory allocation where the choice of growing memory in the course of application execution is not to be had.

Memory requirement

Static reminiscence allocation desires more memory space compared to dynamic memory allocation.

Used in

Arrays use static memory allocation even as linked lists use dynamic memory allocation.

When does it happen?

Static memory allocation takes vicinity at bring together-time, even as dynamic reminiscence allocation occurs at runtime.

Question: Can you provide an explanation for memory leak in C? Why should or not it's addressed?

Answer: Memory leak happens while a reminiscence created in a heap remains undeleted. This can cause additional memory usage and, as a result, have an effect on the performance of a program. This is exactly why the difficulty of reminiscence leak must be addressed.

Question: Please explain what do you understand by way of while(zero) and whilst(1)?

Answer: at the same time as(0) manner that the looping conditions will constantly be false, i.E., the code in the while loop will no longer be completed. On the alternative, even as(1) is an infinite loop. It runs continuously till coming across a spoil announcement mentioned explicitly.

Note: Any non-0 integer within the braces of the at the same time as loop will deliver an countless loop. For instance, at the same time as(-22) and at the same time as(24) will each yield an limitless loop.

Question: Explain the position of covered get entry to specifier?

Answer: The privacy of a covered key-word lies somewhere between the key phrases personal and public . If a category is marked as included, it is able to be accessed by way of its member functions, classes derived with public or protected access, privately derived instructions and friends of the elegance that declared these participants.

Question: What is the key-word volatile used for?

Answer: Volatile prevents the compiler from optimizing the variable or object in query. Any code can alternate the variable’s ((as an example, thread)) cost out of doors the scope of cutting-edge code at any time. This implies that the compiler has to maintain the value of a risky variable in all of the nearby copies of the variable.

Question: Explain the purpose of the ‘delete’ operator?

Answer: Delete gets rid of all the gadgets created by means of the new expression, i.E. Frees reminiscence in the heap area. The array items are deleted using the [] operator:

delete[] array;
NULL or void Pointer can be deleted as:
delete ptr;
The same is applicable for user-defined data types as well. For example,
int *var = new int;
delete var;

Question: Explain the cause of extern garage specifier.

Answer: The extern garage specifier allows declare objects that can be utilized by many source files. It describes a variable this is externally described. The definition can seem at the beginning of a block or out of doors a characteristic. There is handiest one assertion of the extern variable. If another instance is found, it is taken into consideration the same as the first one. Extern variables could have block scope or document scope relying on where they're defined.

Question: Define preprocessor.

Answer: A preprocessor is a program that produces an output which is utilized by a few other software as an input. For instance, translation is a preprocessing step and then the code is despatched for compilation.Preprocessor

Question: What are command-line arguments?

Answer: To manipulate a application from out of doors, we supply the command line argument parameter to the program whilst the primary approach is invoked. The syntax is:

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

in which argc, argv are command-line arguments.

Question: List out the differences among reference and Pointer?

Reference

Pointer

It is an alternative name for a variable.

Stores the address of a variable.

Declared using * : int *ptr.

Declared using & : int &refvar.

Cannot have null values.

Can have null values assigned.

Can be accessed through pass by value.

Uses pass by reference.

Must be initialized upon declaration, i.e. int &ref; will give an error.

No need for initialization during declaration itself, i.e. int *ptr is correct.

Shares same memory address as the original variable and takes up some space on the stack.

Has its size and memory address on the stack.

Question: Explain the various OOPs ideas in C++?

Answer: The OOPs concepts in C++ are:

Class (object): Class is an entity that represents something. It has attributes and functions. For instance, Car may be elegance having version, colour, length, and so on. As attributes and functions can be something like isSecondHand() or isAutomatic(). An item is a new example of a class that represents the real value. An object is created the use of the brand new operator.

Encapsulation: The binding of all of the homes and features is called encapsulation. For example, a category can encapsulate all the homes of comparable objects.

Polymorphism: This idea lets in reuse of capability with changes. There are  sorts: Overloading, Overriding. 

Inheritance: A magnificence that takes properties and strategies from its parents is said to inherit the discern class. For instance, Ford is a kind of Car and might use the class Car's common homes and techniques. So, it could inherit the class Car.

Abstraction: It method showing most effective the high-degree info to the end-user and hiding the real implementation details. 

Read in detail about OOPs concepts. 

Question: Write a software to print Hello World! Without using the semicolon.

Answer: We can achieve this by using the if statement without the condition:

#include <stdio.h> 
#include <conio.h>
void main() 
{ 
if 
(
printf("Hello World!")
) 
} 

Output: Hello World!

Question: Explain the various kinds of Polymorphism in C++ with examples.

Answer: There are  sorts of Polymorphism, i.E. Static and dynamic. Method overloading is an instance of static polymorphism and technique overriding is an example of dynamic polymorphism.

Compile-time (static binding): In this, we have  features with the same, but the number of arguments (parameters) is exclusive. Based at the wide variety of parameters, the compiler makes a decision which of the functions must be referred to as. Such a kind is called characteristic/operator overloading. Example:

int sum(int a, int b){ c = a+b; return c;}
int sum(int x, int y, int z){ v = x+y+z; return v;}

In the main feature, we can name any:

sum1 = sum(9,5);
sum2 = sum(9,5,3);

Note that the characteristic to be known as is determined all through bring together time.

Runtime (dynamic binding): In this, the equal characteristic is found in each the determine and the child class. When the instance of either of the lessons is created at some point of runtime, then the best approach is called. The toddler elegance accordingly overrides the feature present in the parent elegance with its personal precise implementation. Example:

class A{
    void run(){cout<<”I am in superclass A”;}
}
class B: public A{
    void run(){cout<<”I am in subclass B”;}
}

In our primary function, we will name the capabilities as:

A a;
a.run();
B b;
b.run();

The first call will print the message “I am in superclass A” and the second one will print “I am in subclass B”.

Question: Examples of Namespace in C++? 

Answer: A namespace is defined as:

namespace myNmspace
{
  int a, b; //entities
}

If the variables a & b are to be accessed from outside the namespace, then we ought to use the scope operator (::) as: myNmspace :: a. 

If we need to apply a namespace inside the present day region, we use the key-word the usage of as follows: the usage of namespace myNmspace;

Question: Explain the various operations achieved with the aid of the Pointer with examples.

Answer: A pointer stores the deal with of a variable. Suppose, 

int x = 2;

int *y; // pointer declaration – no value assigned, this is called wild Pointer
y = &x; // address of x stored in pointer y

This will keep the deal with of x into y. Note that we use the ‘&’ symbol to get the deal with.

If no address is gift to be assigned, we can factor the Pointer to NULL:

int *y = NULL; // This is called null pointer

A void pointer is used to keep the deal with of any kind of variable. It may be created as:

void *y = NULL;

A pointer may be used as a alternative for the variable fee the usage of ‘*’ symbol. For instance,

z = *y+1 is equivalent to z = x+1.

We can perform equality take a look at with recommendations:

int *a, *b; if a=b, then both are pointing to the same variable.

We can perform increment and decrement, as an example, y++, y--.

Question: Give some crucial variations between new() and malloc()?

Answer: 

new()

malloc()

It is an operator.

It is a function.

Returns a data type.

Returns void pointer.

Memory is allocated with default values through constructor.

Memory is not initialized; the default value is garbage.

New can be overloaded.

Cannot be overloaded.

The allocations cannot be resized.

Allocations can be resized using realloc.

Question: Explain the distinction between delete and delete[]?

Answer: Delete eliminates a single object from memory, while delete[] is used for de-allocating memory of an array of gadgets. The importance of having delete[] is that if we have a pointer (say ptr) to an array of size 10 (new myarr[10]) and sincerely give delete ptr, considering we don’t understand what number of gadgets ptr is pointing to, and as a result delete will simplest delete the first object. The closing nine items will not be deleted. This will cause a memory leak. Example:

// delete
int *var = new int;
delete var;
// delete[]
int *arr = new int[1];
delete[] arr;

Question: State the difference among prefix increment and postfix increment.

Answer: In prefix increment, the fee of the variable is incremented before the program execution. The variable is incremented post this system execution in postfix increment.

++a <- Prefix increment

a++ <- Postfix increment

Intermediate Level Interview Questions

Question: Please give an explanation for the idea of Dangling Pointer in C? In how many ways can a pointer act as a Dangling Pointer?

Answer: A pointer that factors to a reminiscence area that is already deleted is referred to as a hanging pointer. As in step with any other definition, a dangling pointer is a pointer that factors to a dereferenced memory place. A pointer acts as a hanging pointer in three cases:

Deallocation of memory

When the nearby variable isn’t static

When the variable is going out of scope

Initially, the dangling pointer holds a valid reminiscence deal with. Later, however, the held cope with is launched.

The Dangling Pointer Problem:

When A pointer is pointing to a memory region, and a B pointer deletes the reminiscence occupied by way of the A pointer, then the A pointer still points to the memory area, that is now not to be had. This is referred to as the dangling pointer hassle.

Question: How is the null pointer specific from a void pointer?

Answer: A pointer is initialized as NULL whilst its value isn’t recognised at the time of announcement. Generally, NULL tips do not point to a legitimate region. Unlike NULL pointers, void tips are general-motive recommendations that don't have any data kind associated with them. Void recommendations can comprise the cope with of any type of variable. So, the data kind that a void pointer factors to can be some thing.

#include <stdio.h>
#include <conio.h>
void main()
{
    int a = 22;
    int *notnullpointer = &a;
    int *nullpointer1;                                                       // Null because there is no initialization.
    int *nullpointer2 = 0;                                                // Null because initialized with 0.
    if (notnullpointer == 0) printf ("\nNot null pointer is null.");
    else printf ("\nNot null pointer is not null.");
    if (nullpointer1 == 0) printf ("\nNull pointer 1 is null.");
    else printf ("\nNull pointer 1 is not null.");
    if (nullpointer2 == 0) printf ("\nNull pointer 2 is null.");
    else printf ("\nNull pointer 2 is not null.");
    printf ("\nNot null pointer has stored the address %d.", &notnullpointer);
    printf ("\nNull pointer 1 has no valid address.");
    printf ("\nNull pointer 2 has no valid address.");
}

Output:

Not null pointer isn't null.

Null pointer 1 is null.

Null pointer 2 is null.

Not null pointer has saved the deal with 2054804456.

Null pointer 1 has no valid address.

Null pointer 2 has no valid cope with.

Unlike NULL pointers, void pointers are general-motive guidelines that don't have any statistics kind related to them. Void suggestions can incorporate the address of any type of variable. So, the data kind that a void pointer points to can be whatever. For instance:

int x = 22;
char b = 'a';
void *vp = &x; // Here the void pointer is holding address of int x
vp = &b; // Here the void pointer is holding address of char b

Question: What do you recognize via a pointer on a pointer in C?

Answer: A pointer on a pointer is a pointer containing the cope with of some other pointer. It is a shape of more than one indirections. The first pointer includes the cope with of the second one pointer, which factors to the location of the real fee.

Question: Please explain calloc() and malloc() functions?

Answer: calloc() and malloc() are library features used for allocating reminiscence dynamically, i.E., the reminiscence is allocated at some point of runtime from the heap segment. In case of a success memory allocation, a pointer to the memory block is lower back. In eventualities in which allocation fails, the two capabilities go back a NULL cost. Important differences among the calloc() and malloc() features are:

Accessing the content

If we try to access the content of memory even as using the malloc() feature, we can get both the segmentation fault blunders or rubbish values. Doing the equal will get 0 in the case of calloc() feature.

Initialization

The malloc() function allocates the reminiscence and returns a pointer to the start of the block. It doesn’t initialize the allocated memory. The calloc() function, on the other give up, not simplest allocates the memory but additionally initializes the allotted reminiscence block to 0.

Number of arguments

Unlike the malloc() feature, the calloc() characteristic has  arguments:

The quantity of blocks that are to be allotted

The size of each memory block

Question: Compare arrays with pointers within the C programming language?

Answer: Following are the diverse variations between arrays and recommendations in C:

Definition - An array is a form of facts structure that shops multiple, homogeneous elements at contiguous reminiscence places. However, a pointer is a variable that shops or points to the reminiscence deal with of a few other variable.

Initialization - It is feasible to initialize arrays on the definition. Pointers, but, can’t be initialized on the definition.

Size - While a pointer can keep the address of only a single variable, an array is able to storing more than one factors. The array length determines the full quantity of elements stored with the aid of arrays.

Question: What are the crucial differences among a structure and a union in C?

Answer: Following are the 3 critical differences between a structure and a union within the C programming language:

For the equal facts kind, a structure calls for extra memory than a union.

Modifying the fee of a member of a shape doesn’t have an effect on different members. Doing the same in a union, but, outcomes in affecting all the contributors of the union.

While most effective one detail may be accessed at a time in the union, it's miles possible to get admission to all elements of a shape simultaneously.

Check out the in-intensity assessment of union vs. Structure in C.

Question: How is skip by price exceptional from a bypass via reference?

Answer: Pass by means of price and skip via reference are also called call with the aid of price and contact by reference, respectively. In the call by means of cost, values are ship/passed to the feature as parameters. Pass by using fee is used when there may be a demand of not editing the real parameters. Address referring to the real parameters are ship/passed to the feature inside the name by means of reference. Pass by reference is used whilst there's a want for editing the actual parameters. Changes made to the arguments within the known as feature aren't reflected inside the calling function in a skip by cost. Opposite to this, changes made to the arguments inside the known as function are meditated within the calling characteristic in a bypass by reference.

Know approximately skip via reference in detail.

Question: Is #consist of "stdio.H" accurate? What’s the difference among the use of < > and " " for consisting of the header file?

Answer: Yes, #consist of "stdio.H" is accurate. The distinction among using angle brackets (<>) and double rates (" ") for together with a header file is the manner in which the compiler searches for the particular header document.

When we use angular brackets, the compiler searches for the header document best inside the built-in encompass course. When, but, double charges are used, the compiler searches for the header record first in the contemporary working directory, and then inside the integrated consist of route whilst no longer discovered in the present day running directory.

Question: How will you resolve the scope of a international symbol?

Answer: We can use the extern storage specifier for resolving the scope of a worldwide symbol. The extern keyword is used for extending the visibility or scope of variables and features. As C capabilities are visible throughout this system through default, its use with feature declaration or definition isn't required.

Question: When will we use the sign up keyword?

Answer: The sign in storage specifier, i.E., the sign in keyword, is used for storing a variable within the system register. This is generally used for closely-used variables to the likes of a loop manipulate variable. The principal rationale at the back of using the register key-word is to hurry-up this system with the aid of minimizing variable get admission to time.

Question: What do you understand by rvalue and ivalue?

Answer: The expression at the left of the assignment operator (=) is referred to as an ivalue. An rvalue is an expression on the proper side of the project operator, and it's far assigned to an ivalue.

For example,

int a = 25; 

int a is the ivalue within the above-noted example while 25 is the rvalue. While an ivalue persists past a single expression, the rvalue doesn’t persist beyond the expression using it.

Question: How are actual parameters extraordinary from formal parameters?

Answer: Actual parameters are those that are sent to the feature at the calling end. Formal parameters, but, are those that are obtained at some stage in the function definition. A formal parameter is an identifier utilized in a few feature to face for the cost this is exceeded into the characteristic by means of a caller. This actual cost that is surpassed into the characteristic via a caller is the real parameter.

Formal parameters are sure to an actual value as long as their function is energetic. The formal parameters do not keep any values while the function returns to its caller. For Example:

#include <stdio.h>
#include <conio.h>
int totalsum(int a, int b, int c)          // Formal parameters
{
    int total;
    total = a + b +c;
    return total;
}
int main()
{
    int sum;
    int a = 22;    int m = 24; int p = 28;      // Actual parameters
    sum = totalsum(a, m, p);
    printf ("The total sum is %d.", sum);
}

Output:

The overall sum is seventy four.

Another principal distinction between real parameters and formal parameters is that even as the latter are constantly variables, the previous can be expressions, characteristic calls, or even numbers. For instance, in the above instance, the following also are valid actual parameters (within the characteristic call to totalsum):

sum = totalsum (10+15, 12*2, fifty six/2);  // Actual parameters are expressions.

Sum = totalsum (a, (int) sqrt(576), p);  // One of the real parameters is a function call.

Sum = totalsum (22, 24, 28);         // Actual parameters are numbers.

Question: Please provide an explanation for a self-referential structure.

Answer: A self-referential structure carries the identical structure pointer variable as its detail. In different words, it's miles a facts structure in which the pointer points to the shape of the same statistics type. A self-referential structure is utilized in Graphs, Heaps, Linked Lists, Trees, et cetera.

Question: What do you apprehend with the aid of modular programming?

Answer: Modular approach to programming entails dividing an entire software into independent, interchangeable sub-applications, i.E., features and modules for carrying out the preferred functionality. Each of the features or modules worried in modular programming has the entirety required to execute a single component of the complete program's preferred capability.

Question: Please explain tokens in C.

Answer: Tokens are the smallest, indivisible units of a C software with awesome meanings. Following are the various styles of tokens in C:

Constants - Fixed values which could’t be changed all through the program execution.

Identifiers - This refers back to the call of the features, variables, arrays, structures, and many others.

Keywords/Reserved Names - Predefined phrases with special meanings that could’t be used as variable names.

Operators - Symbols that tell the C compiler to perform unique logical, mathematical, or relational operations.

Special Characters - All characters except the alphabets and digits are special characters.

Question: What do you apprehend by the C preprocessor?

Answer: The C compiler mechanically makes use of the C preprocessor for reworking the program, i.E., acting positive things before the actual compilation begins. The C preprocessor is a macro processor as it allows defining quick abbreviations for longer constructs, known as macros.

Question: Please explain bit fields in C.

Answer: Bit fields are variables defined with a predefined width (size) inner a structure. The general syntax of a bit discipline is:

struct {
    type [member_name] : width ;
};

type - Integer kind, consisting of int and signed int, determining how a piece field’s value is interpreted.

Member-call - Name of the bit discipline.

Width - Number of bits inside the bit discipline. Must be much less than or equal to the bit width of the specified integer kind.

Question: What are command line arguments in C?

Answer: Command line arguments are the parameters passed to the principle() function in a C application at some point of software execution. The standard use of command-line arguments is to meet the need of controlling the program from outdoor.

Observe the subsequent code,

ptr = fopen (“file address”, “mode”); 

In the main() characteristic, the variety of command line arguments is given out via the numofargs. The operating gadget updates it routinely. The args is a pointer array protecting guidelines of char kind. These point to the (command line) arguments provided to this system.

Note: When no command-line arguments are exceeded to the program, the numofargs parameter might be 1. Args[0] holds the name of the C software, args[1] factors to the first command-line argument, and args[n] factors to the remaining command-line argument.

Question: Briefly explain the various report starting modes in C?

Answer: Files are opened in a C software using the fopen() characteristic. It is described inside the stdio.H header report. The fashionable syntax of fopen() is:

ptr = fopen (“file address”, “mode”); 

It is feasible to open a record inside the following 12 one of a kind starting modes in a C application:

r - Opens a report for analyzing.

Rb - Opens a file for analyzing in binary mode.

W - Opens a record for writing.

Wb - Opens a document for writing in binary mode.

A - Opens a report for appending i.E. Including facts to the cease of the report.

Ab - Opens a file for appending in binary mode.

R+ - Opens a record for both studying and writing.

Rb+ - Opens a document for each studying and writing in binary mode.

W+ - Opens a document for both reading and writing.

Wb+ - Opens a file for each reading and writing in binary mode.

A+ - Opens a record for both reading and appending.

Ab+ - Opens a record for both studying and appending in binary mode.

Leave for r, rb, r+, and rb+ modes; the record is created if it isn't located whilst attempted to open in other modes. The fopen() returns NULL if the file doesn’t exist in these four record opening modes.

Question: Compare nearby variables and global variables.

Answer: Following are the various variations among the neighborhood and global variables:

1. Declaration

Local variables are declared interior a feature, even as worldwide variables are the variables declared outside the functions.

2. Life

The lifestyles of a nearby variable is tied with the function block wherein it's far declared. The variable is destroyed while the function exits. Global variables continue to be for the entire life of the program.

Three. Scope

The scope of a nearby variable is restricted to the feature or code block in which it's miles declared. Global variables have international scope, i.E., they may be available during the program.

4. Storage

Unless targeted explicitly, neighborhood variables are saved in a stack. The compiler itself comes to a decision the storage for a worldwide variable.

Question: What is a static variable? Why can we need it?

Answer: A variable whose cost is constant and can’t be modified in the course of program execution, i.E., it retains the stored value among a couple of function calls, is known as a static variable. The key-word static represents a static variable. A static variable is first of all initialized to zero. When the fee is up to date, it receives assigned to the static variable. It is initialized handiest once inside the reminiscence heap. We use a static variable to:

Reduce reminiscence consumption

Sharing a common cost across all functions

Question: Please explain recursion in C.

Answer: Recursion is the process while a feature calls itself, without delay or not directly. Such a function is referred to as a recursive function. There are two stages concerned with a recursive characteristic:

Winding section - It begins while the recursive function calls itself and ends as soon as the condition is reached.

Unwinding phase - Starts whilst the situation is reached, i.E., while the winding phase ends, and ends while the control returns to the original call.

Question: Can you write a C software to test whether or not an entered range is top or now not?

Answer:

#include <stdio.h>
#include <conio.h>
long factorial (int n)
{
    if (n==0)
    return 1;
    else
    return (n * factorial(n-1)); //recursion
}
void main()
{
    int number;
    long fact;
    printf("Enter a number: ");
    scanf("%d", &number);
    fact = factorial(number);
    printf("The factorial of %d is %ld!\n", number, fact);
    getch();
}

Sample output:

Enter various: 22

The range you entered isn't a top range!

Question: Please write a application for finding out the factorial of a given quantity using recursion.

Answer: 

#include <stdio.h>
#include <conio.h>
long factorial (int n)
{
    if (n==0)
    return 1;
    else
    return (n * factorial(n-1)); //recursion
}
void main()
{
    int number;
    long fact;
    printf("Enter a number: ");
    scanf("%d", &number);
    fact = factorial(number);
    printf("The factorial of %d is %ld!\n", number, fact);
    getch();
}

Sample output:

Enter more than a few: 5

The factorial of five is 120!

Advanced Level Interview Questions

Question: What is a far pointer in C?

Answer: A far pointer is a 32-bit pointer capable of having access to all the sixteen segments, i.E., the entire house memory of RAM. It can get entry to data outside the laptop reminiscence in a given phase. To use the a long way pointer, it's miles required to:

Allocate the world sign up to keep records cope with inside the phase, and

Store some other quarter sign up in the most latest area

Question: Please provide an explanation for the car keyword in C.

Answer: auto is the default garage elegance of all of the variables declared inner a code block or function. Hence, nearby variables also can be known as automated or vehicle variables. If no cost is stored in an vehicle variable, then it receives a rubbish price. Auto variables are called so because those variables allocate and deallocate reminiscence upon getting into and exiting the code block or feature wherein they're declared, respectively. Typically, there's no need to mention the car keyword explicitly.

Question: Why do we use the sprintf() characteristic?

Answer: The sprintf() function is known as string print. We use the sprintf() function to store the output on a man or woman buffer detailed inside the function, i.E., transferring facts to the buffer. The trendy syntax of the feature is:

int sprintf
(char *str, const char*string,.....); 

The sprintf() characteristic returns the whole wide variety of characters gift in the string. Here is an instance demonstrating using the sprintf() feature: 

#include <stdio.h>
#include <conio.h>
int main()
{
    char buffer[25];
    sprintf(buffer, "This string is now stored in the buffer."); /* Using the sprintf() function for storing the string in the buffer.*/
    printf("%s", buffer);
    int n = sprintf(buffer, "This string is now stored in the buffer.");
    printf("\nThe total number of characters in the string is %d.", n); // The sprintf() function returns the total number of characters in the stored string.
    return 0;
}

Output: This string is now saved within the buffer.

The general quantity of characters in the string is 40.

Question: Tell the distinction between getch() and getche() capabilities.

Answer: Both getch() and getche() functions are used for analyzing a single character from the keyboard. The distinction between the 2, but, lies in terms of displaying the output. The getche() function displays the data, the entered individual, on the output display while the getch() characteristic doesn’t. Use Alt+F5 to see the entered man or woman.

Question: Explain the distinction among near, some distance, and huge tips.

Answer: Any digital cope with has the selector and offset. While a close to pointer doesn’t have explicit selector, some distance and large pointers do. Performing pointer mathematics on the a ways pointer doesn’t bring about modifying the selector. It does, but, inside the case of a big pointer.

Question: Please outline typecasting.

Answer: Typecasting is the process of changing one facts type into any other. It is of  kinds:

1. Implicit kind casting - Also called an automatic conversion, implicit kind conversion is done robotically via the C compiler, i.E., it doesn’t require a casting operator. For instance:

#include <stdio.h>
#include <conio.h>
void main ()
{
    int x = 22;
    float b = x; //implicit type conversion
    printf(“%f”, b);
}

Output: 22.000000

2. Explicit type casting - Unlike implicit type conversion, the programmer performs explicit type casting. A type casting operator is used for telling the compiler to convert (solid) one facts kind into some other. For example:

#include <stdio.h>
#include <conio.h>
void main ()
{
    float x = 22.22;
    int b = (int) x; //explicit type conversion
    printf(“%d”, b);
}

Here, (int) is the typecasting operator.

Question: Write a C application to check whether or not an entered variety is palindrome or not.

Answer: A palindrome quantity is one that reads the identical, whether forwards or backwards. 

#include<stdio.h>    
#include<conio.h>    
void main()    
{    
    int n, r, sum=0, temp;
    printf("Enter a number: ");    
    scanf("%d",&n);    
    temp=n;    
    while(n>0)
        {
            r=n%10;
            sum=(sum*10)+r;    
            n=n/10;
        }
    if(temp==sum)
    printf("It is a palindrome number!");
    else
    printf("It is not a palindrome number!");
    getch();
}

Question: What can be understood from the null pointer and a hanging pointer?

Answer: There is a massive distinction that can be noticed in the null and the dangling pointer. The null pointer does now not in particular point to some thing. That is, it points to not anything. Whereas the dangling pointer is the only who first of all holds a legitimate cope with, but in a while, that valid address receives discharged.

Question: What are the wonderful methods of passing parameters to the function and state along with that is to be used when?

Answer: There are normally two ways of passing parameters to the feature which might be listed as follows:

Call with the aid of Reference- In this approach, the cope with of the real parameter is sent as opposed to the values. It is chosen within the case while the user doesn’t need the actual parameter to be altered with the formal parameter.

Call by means of Value- In this method, we most effective ship values to the capabilities because the parameters. It is selected if the person wants the real parameter to be altered with the formal parameter but simply for use.

Question: What is the usage of #undef preprocessor?

Answer: As consistent with the C programming language, the #undef directive's principal goal is that it acts as a guide to the preprocessor to remove all of the definitions for the unique macro. If a macro is non-unique, and #ifdef directive on that certain macro will show the result as false.

Question: What do you suggest by increments and decrement statements in C programming and how we can construct that increment and decrement statements?

Answer: There are basically  sorts of statements, increment and decrement that are supported through C. There are essentially two ways by means of which we can practice each the statements in C programming. The first one uses the increment operator ( ++ ) and the other is decrement operator ( -- ).

For instance, if we use ( x ++ ), this indicates to command increment the fee of x with a rate of one.

Question: List the difference among the source and object code.

Answer:

Source code: Source codes typically get a command from the programmer and those codes are answerable for instructing the computer regarding what to carry out? With extension .C we will shop this code in C programming.

Object code: With the extension. OBJ, we will shop the item code in C programming. This is the main difference between the 2 codes.

Question: Elaborate the method by way of which we are able to observe quote man or woman (and) in output display screen in C programming?

Answer: We all recognise that applying quote individual is the part of printf statement an so that it will observe this person in output screen, you could use the format of specifiers/ ‘ that is for a unmarried quote and /” for a double quote.

Question: What do you mean via nested loop in C programming?

Answer: When the one loop receives into the opposite loop and begins jogging that loop is known as nested loop. The outer loop will specifies the number of instances the internal loop will perform its feature and every time the primary loop performs its responsibilities.

Question: What is the use of modulus operation in C programming?

Answer: Modulus operator in C programming is an important operator on this programming because this modulus operation tells the division operation within the programming characteristic. It basically suggests the the rest cost left after the division between  numbers. It is represented with the symbol of (%).

For example:

20 % three = 2, this can be expressed as, while we divided 20 by using three we're left with the the rest of 2.

11 % 2 =1, which means that whilst we divided 11 by means of 2 we get the the rest of one.

Question: What is the overall shape that is supported with the aid of C programming? Explain its idea in detail.

Answer: It commences its manner with the preprocessor directives. These directives carry out loads of function like it answerable for specifying the header files and it additionally tells approximately the constants to be used inside the C programming procedure. The essential characteristic of this programming follows this whole procedure and that is the heading characteristic. This function plays the variable statement and the maximum essential software statements.

Question: Random document get right of entry to in C programming performs a completely important element. Why? List some of its merits.

Answer - We all realize that in each pc we keep a massive amount of big facts and whenever we take a variety of time in locating the important thing content from the big database. Still, this random get entry to file allows in solving this problem.

It facilitates to find the key records faster from a big database.

It allows indirectly transferring to goal cope with whilst there are loads of addresses in the programming.

Question: What is the role of shape kinds in C programming?

Answer: Major position played through shape types in C programming is to shop the statistics. These information are saved in line with their subject sorts. This enables us to without difficulty find the record at the time of urgent seek due to the fact we will discover all of the facts in a selected area folder. This helps to keep time and money.

Question: Is C language is a center-stage language? If sure then why is it so?

Answer: Yes C language is understood to be a center-level language. This is as it has a unique and interesting function that makes it act like a better-level language. But at the identical time, it allows to use low-stage strategies in interacting with hardware. It also helps the usage of the English type of phrases in its functioning. All such feature makes it to act as excessive-level language. Moreover, it has a unique function of storing the memory shape.

Question: What are the capabilities of reserve phrases in C programming? Elaborate on them.

Answer: Standard C language library has positive words stored in it all such phrases are known as reserve phrases. All such phrases are unique and feature a one of a kind that means so that they can't be used for some other form of cause in place of its unique purpose. Some of the examples are void and return and so forth.

Question: What are the different manipulate structures that is accompanied in the C programming?

Answer: In C programming we generally follow three kinds of manipulate structures and which might be sequence, choice and repetition.

Sequence: this manipulate shape follows the path that runs from a pinnacle to backside inside the system of execution of a software and this glide is in sequence.

Selection: In this, the codes are accomplished primarily based at the conditions of assessment as actual or fake.

Repetition: In this, this system announcement will observe the stairs of repetition. The other call of repetition is referred to as a loop shape.

Question: What is the precise meaning of debugging in C programming?

Answer: Debugging way the process that enables in allocating the errors within the programming. It may additionally prevent the system of execution. To resolve this procedure of execution, debugging w




CFG