SlideShare a Scribd company logo
Top 50 Mostly Asked C Interview Questions
and Answers
C Interview Questions and Answers: An Overview
Are you preparing for a C interview? Feeling excited but quite nervous at the same time? fear
not..! This comprehensive guide is here to guide you to demonstrate a solid grasp of C
concepts, help you to grow your problem-solving skills, and also make you feel confident to
ace your interview.
In the Programming world, C remains a foundational language for systems programming,
embedded systems, and performance-critical applications. By understanding its complexities,
you will conquer half of the programming languages that exist. Interviewers often use C-
specific terms to analyze the understanding of your C knowledge such as
Why are C Interview Questions Important?
1. Memory management: C gives you direct control over memory, which can be powerful and
challenging. Be prepared to explain concepts like pointers, dynamic allocation, and common
memory-related pitfalls.
2. Problem-solving and algorithmic thinking: Interviewers want to see how you approach
problems analytically, break them down into manageable steps, and write efficient C code
to achieve the desired outcome.
3. Best practices and coding style: Following good practices demonstrates your
professionalism and attention to detail. Be familiar with common C conventions, coding
guidelines, and readability tips.
Now that you have a solid understanding of why C interview questions and how to prepare for
them, let's see some advanced terms you might encounter in an interview. This guide covers
various categories:
1. Basics and Syntax: Test your understanding of fundamental C concepts, data types,
operators, and control flow.
2. Memory Management: Master pointers, dynamic allocation, and memory-related pitfalls.
3. Data Structures and Algorithms: Explore common C data structures (arrays, linked lists,
stacks, queues, trees, etc.) and demonstrate your ability to implement algorithms using
them.
4. Advanced Concepts: Get comfortable with preprocessor directives, bitwise operations,
unions, structures, and advanced function pointers.
5. Problem Solving and Coding: Apply your knowledge to solve real-world programming
challenges using efficient and well-structured C code.
Keep in mind for a good communicative interview Sometimes be in the interviewer's shoes too,
Don't just answer, ask! Show your genuine interest by crafting insightful questions about the
company, role, and team.
Explore the depth of C programming with our comprehensive guide to 50 C Interview
Questions and Answers. Whether you're a beginner or an experienced developer, this resource
provides valuable insights, helping you master essential concepts and excel in C-related
interviews.
C Interview Questions: A Roadmap to Success
C Interview Questions and Answers for Freshers
HTML to PDF
3. What is a token?
Tokens are the discrete components of a program. There are 6 tokens in C language, those are-
2. What are the features of the C language?
1. Why is C called a mid-level programming language?
C possesses features of both lower-level and higher-level, or assembly-level, languages. C is
hence frequently referred to be a middle-level language. One may write both a menu-driven
consumer billing system and an operating system in C.
1. Identifiers
2. Keywords
3. Constants
4. Operators
5. Special Characters
Middle-level language: Provides low-level memory access and high-level abstractions,
balancing efficiency and ease of use.
Portability: Code written in C can run on different platforms with minimal modifications.
Efficiency: Offers efficient memory management and execution speed.
Roch Standard Library: Provides a comprehensive set of functions for various tasks.
Procedural Language: Follows a structured, step-by-step approach to solving problems.
. Strings
Printf()- To print the output to the screen, use print().
Scanf()- To read formatted data from the keyboard, use scanf().
The following are a few datatype format specifiers that can be used for scanning and printing:
%d- It's a format specifier for datatypes that prints and scans integer values.
%s- This datatype format specifier is used to print and scan strings in the program.
%c- It is a format specifier for a datatype that is used to display and scan character values.
%f- The float value may be seen and scanned using the datatype format specifier %f.
In C programming, basic data types include:
Primitive Data type- There are two other categories of primitive data types: integer and
floating.
User-Defined data types- The user defines these data types to improve program
readability.
Derived data types- Data types that come from pre-built or basic data types.
The answer is "f". In C-style languages, the expression 5["zyzuv"] is equivalent to "zyzuv"
[5], which accesses the 6th character of the string "zyzuv". Therefore, the value of the
expression is "v".
5. What's the value of the expression 5["zyzuv"]?
6. What are basic data types supported in the C Programming
Language?
4. What is the use of printf() and scanf() functions? Also, explain
format specifiers?
9. What is a Preprocessor?
A software application known as a preprocessor is used to handle source files before
submitting them to be built. The preprocessor allows for the inclusion of header files, macro
expansions, conditional compilation, and line control.
7. What is a built-in function in C?
The built-in C functions scanf(), printf(), strcpy, strlwr, strcmp, strlen, strcat, and many more are
used often.
8. What do you mean by the scope of the variable?
In programming languages, scope refers to the block or region where a specified variable will
live; if the variable extends outside of that block or region, it will be immediately destroyed.
Every variable has a certain range of use. To put it simply, a variable's scope is determined by
how long it remains in the program. Three different places can define the variable. They are as
follows:
The term "built-function" refers to library functions that the system provides to developers to
help them with specific frequently performed predefined tasks, hence simplifying their lives.
For instance, printf() in C is used when you need to print your program's output to the terminal.
1. Local Variables: Located within a certain block or function
2. Global Variables: Among all the functions that the program does globally.
3. Formal parameters:These are limited to in-function parameters.
10. What are preprocessor directives in C?
Preprocessor directives in C are built-in predefined functions or macros that are performed
before program execution and serve as instructions to the compiler. The process of creating
and running a C program involves several phases. Macros, File Inclusion, Conditional
Compilation, and Other directives like #undef, #pragma, etc. are the main categories of
Preprocessor Directives.
11. What is the use of static variables in C?
In the C programming language, data values are preserved across function calls even after they
have exited their scope thanks to the usage of static variables. Static variables don't require
initialization each time they are used in a program; their values are preserved inside their
scope. Without initialization, the initial value of a static variable is set to 0.
12. What is the difference between malloc() and calloc() in the C
programming language?
The library methods malloc() and calloc() are used to allocate dynamic memory. The memory
that is allocated from the heap section while the program is running is known as dynamic
memory. The header file "stdlib.h" is what makes dynamic memory allocation in the C
programming language possible.
Parameter
Definition
Run Code >>
Malloc() It is a function that
generates a
single, fixed-size memory block.
Calloc() It is a function that allows a
single
variable to be assigned to several
memory blocks.
// C program to print initial
// value of static variable
#include <stdio.h>
int main()
{
static int var;
int x; printf("Initial value of static variable %dn", var);
printf("Initial value of variable without static %d", x);
return 0;
}
Efficiency
Usage
Number
arguments
Speed
Run Code >>
of One argument is all that is
needed.
Calloc() is slower than the
malloc() procedure.
It is quite efficient with time.
There must be two arguments.
Compared to malloc(), calloc() is slower.
It is not very time-efficient.
It serves as a signal for contiguous
memory allocation.
It
allocation indicator.
serves as a memory
Recursion in C is a programming technique where a function calls itself directly or indirectly to
solve a problem. In recursive functions, the function breaks down the problem into smaller
subproblems and calls itself with modified arguments until a base case is reached, stopping the
recursive calls.
13. What is Recursion in C?
Syntax of recursive function in the C Compiler
void do_recursion()
{
... .. ...
do_recursion();
... .. ...]
}
int main()
{
... .. ...
do_recursion();
... .. ...
}
Watch the Video - Recursion In C
Local Variables
Declared within a function or a block.
Global Variables
Variables declared outside of a function or
block.
Global Variables store the default value of zero
Local Variables store a garbage value by
default
After a block or function, the local
variables' life is terminated.
If the programmer does not specify a
variable, it is kept inside the stack.
Parameter passing is necessary for other
functions to access the local variables.
The global variable remains valid till the
execution of the program.
The compiler determines where the global
variable is stored.
Passing parameters is not necessary. During the
program, they are visible to everyone worldwide.
A pointer in C is a variable that holds the memory address of another variable. It allows direct
manipulation of memory locations, enabling dynamic memory allocation, efficient array
handling, and indirect access to data. Pointers are a fundamental feature used for tasks like
data structures and dynamic memory management.
15. What is a Pointer in C?
14. What is the difference between the Local and Global Variables
in C?
17. How can we create an Infinite loop in C?
Let's see how we create infinite loop in C
16. Define Loops in C language. What are the types of loops in C?
Loops in C are programming constructs that repeatedly execute a block of code as long as a
specified condition is true. They enable efficient iteration through data, simplifying tasks like
array manipulation or repetitive operations, ensuring code efficiency and maintainability.
Common loop types in C include for, while, and do-while.
Watch the Video - What are Loops in C?
// C program for infinite loop
// using for, while, do-while
#include
// Driver code
19. What is Typecasting in C?
Typecasting in C is the process of converting one data type into another. It allows a variable to
be treated as a different type temporarily. For example, converting an integer to a float or a
pointer from one data type to another is done using typecasting operators like (float) or (int*).
18. What is the Pointer to Pointer in C?
In C, a pointer to a pointer, also known as a double pointer, is a variable that holds the address
of another pointer variable. It allows indirect access to a memory location, providing a way to
modify pointers and dynamically allocate multi-dimensional arrays, enhancing flexibility in
memory management and data structures.
Run Code >>
(data_type)expression;
int main()
{
for (;;) {
printf("Infinite-loopn");
}
while (1) {
printf("Infinite-loopn");
}
do {
printf("Infinite-loopn");
} while (1);
return 0;
}
int **p; // pointer to a pointer which is pointing to an integer
Syntax
Output
Example
Explanation
Run Code >>
Type Casting Type Conversion
With the use of a casting operator, a programmerA compiler transforms the data type
transforms the data type into another data type. into another data type.
It may be used on incompatible as well as compatible
forms of data.
A caste operator is required in type casting to cast the
data type into another data type.
Type casting is more dependable and efficient.
Only suitable data types can be used
with type conversion.
A casting operator is not required
during type conversion.
Compared to type casting, type
conversion is less dependable and
The given C code in the C Online Compiler initializes an integer variable x with the value 97 and
then uses a for loop to print the characters corresponding to ASCII values from 97 to 122. In
the ASCII table, these values represent lowercase English letters from 'a' to 'z'.
abcdefghijklmnopqrstuvwxyz
int x;
for(x=97; x<=122; x++)
{
printf("%c", (char)x); /*Explicit casting from int to char*/
}
20. What is the Difference between Type Casting and Type
Conversion?
Syntax: destination_data_type = (target_data_type)
variable_to_be_converted;
efficient.
Syntax: int a = 20; float b; b = a; // a =
20.0000
Macro
Preprocessed macros are used.
Using a macro, the code length is enhanced.
Function
The functions are compiled.
Using a function does not affect code
length.
With a macro, execution speed is increased. Using a function results in reduced
execution speed.
Control is transferred during the
function call.
The macro name is replaced by the macro value
before compilation.
A pre-processor command that designates a group of C statements is called a macro. The pre-
processor directive defines a macro. Since macros are preprocessed, our program would not
have been compiled until after all of the macros had been preprocessed. Functions are
compiled rather than preprocessed, though.
In C programming, header files are files containing function declarations and macro definitions.
They allow code reuse by providing function prototypes to other source files. Commonly used
header files include <stdio.h> for input/output functions and <stdlib.h> for memory allocation
functions.
Header files in C serve several purposes:
C Programming Interview Questions for
Intermediates
21. What are header files in C and their uses?
22. What is the difference between macro and functions?
23. Specify different types of decision control statements in C
There are two primary techniques in C for converting strings to numbers: string streams and
the stoi() and atoi() library functions.
sscanf()-
Instead of using normal input, it reads data from a string.
In C, a structure is a user-defined data type that allows you to group variables of different data
types under a single name. It is used to represent a record containing different fields, enabling
you to store and manipulate related data more efficiently. Example
atoi()-
This method returns an integer value when it receives a character array or a string literal as
input.
In a program, each keyword is designed to carry out a certain function. They cannot be used
for reasons other than those for which they were designed since their meaning has already
been established. The programming language C has 32 keywords supported. Reserved
keywords include things like auto, else, if, long, int, switch, typedef, and so on.
A program executes each sentence one at a time, starting at the top and working down.
Depending on the circumstance, control statements are used to execute or move control from
one area of the program to another. The different types of control statements are:
Simple if statement
if...else statement
if else...if ladder
nested if...else statement
Switch statement.
26. What is a Structure in C?
25. What are Reserved Keywords in C?
24. How to convert a String to Numbers in C?
Explanation
The given C program in C Editor defines a structure student with member name, roll_no,
address, and branch. It then creates an object of this structure, initializes its members, and
prints the values of these members
Run Code >>
return 0;
}
// C Program to show the
// use of structure
#include
#include
// Structure student declared
struct student {
char name[20];
int roll_no;
char address[50];
char branch[50];
};
// Driver code
int main()
{
struct student obj;
strcpy(obj.name, "Urmi_Bose");
obj.roll_no = 19;
strcpy(obj.address, "Kolkata");
strcpy(obj.branch, "Computer Science And Engineering");
// Accessing members of student obj
printf("Name: %sn", obj.name);
printf("Roll_No: %d n", obj.roll_no);
printf("Address: %sn", obj.address);
printf("Branch: %s", obj.branch);
Syntax
Output
Example
int val = 20;Here,
union name_of_union
{
data_type name;
data_type name;
};
Name: Urmi_Bose
Roll_No: 19
Address: Kolkata
Branch: Computer Science And Engineering
val is the ‘l-value’, and 20 is the ‘r-value’.
27. What is Union in C?
In C, a union is a user-defined data type that allows different data types to be stored in the
same memory location. Unlike structures, unions use the same memory space for all members,
allowing only one member to hold a value at any given time. Unions are often used to save
memory when different data types need to share the same memory location.
28. What is an r-value and l-value?
When an object has an address or a unique position in memory, it is referred to as an "l-value."
Either the left or right side of the assignment operator(=) will display a "l-value." A data value
kept in memory at a specific location is called a "r-value." An object without a known location in
memory is referred to as an "r-value" (i.e. without an address). An expression that cannot have
a value assigned to it is known as a "r-value," and it can only appear on the right side of an
assignment operator (=).
29. What is the Call by value in C?
In C, call by value is a method of passing arguments to functions. When a function is called
with parameters, the values of the parameters are copied into the function's parameters. Any
modifications made to the parameters inside the function do not affect the original values
outside the function.
30. What is the Call by reference in C?
Call by reference in C involves passing the memory address of a variable to a function, allowing
the function to modify the actual value at that address. Changes made to the parameter inside
the function are reflected outside the function, as the function operates on the original data in
memory.
31. What is the difference between Call by Value and Call by
Reference in C?
Certainly, here are the differences between call by value and call by reference in C:
Watch the Video - Difference Between CallBy Value & CallBy Reference
Call by Value
Parameters are passed by value, meaning
the actual values are passed to the function.
Call by Reference Parameters are passed by
reference, meaning
the memory address (reference) of the actual
variable is passed.
The function receives a copy of the
argument's value, and any modifications
made inside the function do not affect the
original variable.
Suitable for basic data types like int, float,
and char, where changes made inside the
function don't reflect outside the function
scope.
The function receives the memory address of
the argument, allowing modifications inside
the function to directly affect the original
variable.
Suitable for complex data structures like
arrays and structs, where changes made
inside the function reflect outside the
function scope.
Efficient in terms of memory, as only values
are passed.
More memory-intensive, as
passing memory addresses.
it involves
In C, enumerations (enums) are user-defined data types that consist of a set of named integer
constants. Enums provide a way to create symbolic names (enumerators) for integral values,
making code more readable and understandable. Enums are often used to define sets of
related integer values with meaningful names.
32. What are the Enumerations in C?
Syntax
Example
include // Enum declaration
enum Days {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY, THURSDAY,
FRIDAY, SATURDAY }; int
main() { // Enum variable
declaration enum Days today;
// Assigning a value to the enum variable
today = WEDNESDAY;
// Printing the value of the enum variable
printf("Today is: ");
enum enumeration_name{constant1, constant2, ... };
Explanation
// Switch case to determine the day
switch (today) {
case SUNDAY:
printf("Sunday");
break;
case MONDAY:
printf("Monday");
break;
case TUESDAY:
printf("Tuesday");
break;
case WEDNESDAY:
printf("Wednesday");
break;
case THURSDAY:
printf("Thursday");
break;
case FRIDAY:
printf("Friday");
break;
case SATURDAY:
printf("Saturday");
break;
default:
printf("Invalid day");
break;
}
return 0;
}
Run Code >>
In this code in the C Online Editor, an enumeration Days is defined with the days of the week.
The program sets the today variable to WEDNESDAY and prints the corresponding day using a
switch statement.
Output
Today is: Wednesday
printf("Please Enter number of Elements: ");
scanf("%d", &num);
// C program to print Fibonacci Series
// with recursion and without recursion
#include
// Recursive Function to print
// Fibonacci Series
void Fibonacci(int num, int first, int second, int third)
{
if (num > 0) {
third = first + second;
first = second;
second = third;
printf("%d ", third);
// Recursive call for it's
// n-1 value
Fibonacci(num - 1, first, second, third)
}
}
// Driver code
int main()
{
int num;
33. Write a C program to print the Fibonacci series using recursion
and without using recursion.
Output
return 0;
}
first = second;
second = third; }
printf("%d ", third);
printf("%d %d ", 0, 1);
printf("%d %d ", 0, 1);
Fibonacci(num - 2, 0, 1, 0);
int first = 0, second = 1, third = 0;
// we are passing n-2 because we have
// already printed 2 numbers i.e, 0 and 1
// Loop will start from 2 because we have
// already printed 0 and 1
for (int i = 2; i < num; i++) {
third = first + second;
printf(
"Fibonacci Series with the help of Recursion:n");
printf("nFibonacci Series without Using Recursion:n");
Run Code >>
struct Point {
int x; int y; };
struct Point p1;
Please Enter number of Elements: 5
Fibonacci Series with the help of Recursion:
0 1 1 2 3
Fibonacci Series without Using Recursion:
0 1 1 2 3
34. What is the difference between Struct and Union in C?
Usage:
Accessing
Members:
Memory
Efficiency:
Memory
Allocation:
Struct Union
Each member in a struct has its own
memory location, and the total
memory occupied by a struct is the
sum of the sizes of its members.
Useful when different types of data
need to be stored simultaneously,
allowing access to each member
independently.
Allocates memory for each member,
which can lead to higher memory
usage when storing multiple types
of data.
Members
independently using the dot (.)
operator.
All members share the same memory
location. The size of a union is
determined by the largest member
within it.
Ideal when only one type of data needs
to be stored at a time, conserving
memory by sharing the same memory
location for different members.
Saves memory by sharing memory
space; however, accessing the correct
member is crucial to avoid data
misinterpretation.
Only one member can be accessed at a
time, using the dot (.) operator like
structs.
are accessed
Example (Struct):
Example (Union):
35. What are Static Memory Allocation and Dynamic Memory
Allocation in C?
Static memory allocation- Static memory allocation is the type of memory allocation that
occurs during compilation. Allocating static memory reduces operating time. Because
memory is allocated from the stack, it is quicker than dynamic memory allocation.
Compared to dynamic memory allocation, this form of memory allocation is less effective.
Within the
array, it is mostly favored.
Run Code >>
Run Code >>
Dynamic memory allocation- Dynamic memory allocation is the process of allocating memory
during runtime or execution. Because dynamic memory allocation uses the heap for memory
allocation, it is slower than static memory allocation. When compared to static memory
p1.x = 1;
p1.y = 2;
union Data {
int i;
float f;
char c;
};
union Data d;
d.i = 10;
printf("%d", d.i); // Output: 10
d.f = 3.14;
printf("%f", d.f); // Output: 3.140000
Run Code >>
typedef in C is used to create custom data type aliases. It allows programmers to define names
for existing data types, making the code more readable and adaptable. Custom types created
with typedef can simplify complex declarations and enhance code clarity.
You can track every memory allocation you make, plan to the point where you wish to destroy
(in a good sense) that memory, and then remove it there to prevent memory leaks. Using the
C++ smart pointer in C to connect it to GNU compilers is an additional method.
An alias name for the current complex type definition is provided by typedef. You may easily
make an alias for any type with typedef. Typedef will let you write shorter code, whether
you're
allocation, this form of memory allocation is more efficient. Most people in the linked list favor
it.
Depending on the size of the data type, assigning a variable requires space in either our heap or
RAM. Nevertheless, if a programmer uses heap memory and forgets to delta it, eventually all of
the RAM's memory will be used up and there won't be any more memory, which could result in
a
memory leak.
C Interview Questions and Answers for Experienced
36. What is a Memory Leak? How to avoid it?
37. What is typedef?
int main()
{
char * ptr = malloc(sizeof(int));
/* Do some work */
/*Not freeing the allocated memory*/
return 0;
}
typedef <existing-type> <new-type-identifiers>;
HTML to PDF
declaring a sophisticated function pointer, structure, or simple integer.
38. Write a C program to check whether a number is prime or not.
// C program to check if a //
number is prime #include
#include // Driver code
int main()
{
int num;
int check = 1;
printf("Enter a number: n");
scanf("%d", &num);
// Iterating from 2 to sqrt(num)
for (int i = 2; i <= sqrt(num); i++) {
// If the given number is divisible by
// any number between 2 and n/2 then
// the given number is not a prime number
if (num % i == 0) {
check = 0;
break;
}
}
if (num <= 1) {
check = 0;
}
if (check == 1) {
printf("%d is a prime number", num);
}
else {
printf("%d is not a prime number", num);
}
return 0;
}
Run Code >>
Source Code
The programmer creates the source code.
Object Code
A translator such as a compiler can produce
object code.
Low-level programming is incomprehensible to
humans.
Compared to source code, object code has
more statements and cannot be changed.
Object code is system-specific and modifiable.
High-level, easily understood by humans
code.
Compared to object code, source code is
easier to modify and has fewer statements.
Source code is not system-specific and is
subject to change over time.
A function that uses pass-by-reference can change a variable without copying it. Since the
provided parameter and variable share the same memory address, any modifications made
to the argument will also affect the variables.
Explanation
This C program checks whether a given number is prime or not. It takes an input number,
iterates from 2 to the square root of the input, and checks for divisibility. If the number is
divisible by any value in this range, it's not prime. If it's less than or equal to 1, it's not prime
either. The result is displayed accordingly.
40. What is Pass-by-Reference in functions?
39. How is Source Code different from Object Code?
Example
// C program to change a variable
// using pass by reference
#include
// * used to dereference the variable
void change(int* num)
Output
Explanation
Run Code >>
In this code, the change function takes a pointer to an integer as a parameter and modifies the
value stored at that memory location. The address of the num variable is passed to the change
function using the & operator. As a result, the value of num inside the main function is changed
to 34.
Value of num before passing is: 12
{
// value of num changed to 34
*num = 34;
}
// Driver code
int main()
{
int num = 12;
printf("Value of num before passing is: %dn", num);
// Calling change function by passing address
change(&num);
printf("Value of num after changing with the help of "
"function is: %d",
num);
return 0;
}
Value of num after changing with the help of function is: 34
41. What is an auto keyword?
Run Code >>
In the C programming language, each local variable in a function is referred to as an automatic
variable. For every variable declared inside a function or block, the default storage class is
Auto. Access to auto variables is restricted to the block or function in which they have been
defined. With the aid of pointers, we may use them outside of their intended usage. Auto
keywords by default have a garbage value.
This code uses the printf function inside the if statement condition. The printf function returns
the number of characters printed. Since the string "Hello - World" has a non-zero length, the
condition evaluates to true and the empty block { } under if is executed, leading to the printing
of "Hello - World".
42. Write a program to print “Hello-World” without using a
semicolon.
Output
Explanation
Hello - World
// C program to print hello-world
// without using semicolon
#include
// Driver code
int main()
{
// This will print the hello-world
// on the screen without giving any error
if (printf(“Hello - World”)) {
}
return 0;
}
43. Explain Modifiers in C
In the C language, modifiers are keywords that are used to alter the meaning of fundamental
data types. They outline how much memory should be set aside for the variable. There are
five types of modifiers, which are
44. Write a program to print the factorial of a given number with
the help of recursion.
Run Code >>
1. long
2. short
3. signed
4. unsinged
5. long long
// C program to find factorial
// of a given number
#include <stdio.h>
// Function to find factorial of
// a given number
unsigned int factorial(unsigned int n)
{
if (n == 0)
return 1;
return n * factorial(n - 1);
} // Driver code
int main()
{
int num = 5;
printf("Factorial of %d is %d", num, factorial(num));
return 0;
}
Output
Explanation
In C programming, both #include "..." and #include <...> are used to include header files, but they
differ in their search paths and usage:
#include "..." (Double Quotes): The C preprocessor searches the predefined list of system
directories for the filename before checking user-specified directories (directories can be
added to the predefined list by using the -I option).
#include <...> (Angle Brackets): The preprocessor follows the search path given for the
#include <filename> form after first searching in the same directory as the file containing the
directive. Include programmer-defined header files using this way.
Using double quotes ("...") is generally preferred for including project-specific headers, while
angle brackets (<...>) are used for standard library or system headers to distinguish between
user-defined and system-provided header files.
This C program calculates the factorial of a given number using recursion. The factorial function
recursively calculates the factorial: n! = n * (n-1)!. In the main function, the program calculates
the factorial of 5. The program computes 5! Which is equal to 5 * 4 * 3 * 2 * 1 = 120, and prints
the result.
Factorial of 5 is 120
// C program to determine whether
// the given number is Armstrong
// or not
#include
// Driver code
int main()
46. Write a program to check an Armstrong number.
45. What is the difference between #include "..." and #include
<...>?
Output
Explanation
Run Code >>
This C program checks if a given number is an Armstrong number or not. It calculates the sum
of cubes of its digits and compares it with the original number. If they are equal, it's an
Armstrong number. 1^3 + 5^3 + 3^3 = 153, which matches the original number.
{
int n; printf("Enter Number n");
scanf("%d", &n);
int var = n;
int sum = 0;
// Loop to calculate the order of
// the given number while (n > 0) {
int rem = n % 10; sum = (sum) + (rem
* rem * rem); n = n / 10; }
// If the order of the number will be
// equal to the number then it is
// Armstrong number.
if (var == sum) {
printf("%d is an Armstrong number n", var);
}
else {
printf("%d is not an Armstrong number", var);
}
return 0;
}
153 is an Armstrong number
include <stdio.h> #include <stdlib.h> // Node structure representing a node in
the linked list struct Node { int data; struct Node* next;
};
// Function to merge two sorted linked lists
struct Node* mergeSortedLists(struct Node* list1, struct Node* list2) {
if (list1 == NULL) return list2;
if (list2 == NULL) return list1;
if (list1->data < list2->data) {
list1->next = mergeSortedLists(list1->next, list2);
return list1;
} else {
list2->next = mergeSortedLists(list1, list2->next);
return list2;
}
}
// Function to create a new node with given data
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to print the merged linked list
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
47. Merge two sorted Linked Lists in C
Output
Explanation
Run Code >>
In this program, two sorted linked lists (list1 and list2) are merged into a new sorted linked list
(mergedList). The merged list is then printed.
return 0;
}
First sorted linked list: 1 3 5
Second sorted linked list: 2 4 6
printf("n");
}
// Driver code
int main() {
struct Node* list1 = createNode(1);
list1->next = createNode(3);
list1->next->next = createNode(5);
struct Node* list2 = createNode(2);
list2->next = createNode(4);
list2->next->next = createNode(6);
printf("First sorted linked list: ");
printList(list1);
printf("Second sorted linked list: ");
printList(list2);
struct Node* mergedList = mergeSortedLists(list1, list2);
printf("Merged sorted linked list: ");
printList(mergedList);
Merged sorted linked list: 1 2 3 4 5 6
48. What is the use of an extern storage specifier?
In the C language, the extern keyword is used to increase the visibility of C variables and
functions. External can be shortened to extern. When a specific file wants to access a
variable from any other file, it is used. Variables containing the extern keyword are simply
declared, not defined, which increases duplication. There is no need to declare or create
extern functions because they are visible by default throughout the program.
50. How is import in Java different from #include in C?
49. What is the difference between getc(), getchar(), getch() and
getche() in C?
1. getc():
Reads a character from the specified file stream (e.g., stdin, file).
Requires stdio.h header.
Offers flexibility for reading from different input sources.
2. getchar():
Reads a character from the standard input stream (stdin).
Requires stdio.h header.
Commonly used for simple character input from the keyboard.
3. getch():
Reads a character from the keyboard without echoing it to the screen.
Typically used in older MS-DOS and Windows environments.
Requires conio.h header (non-standard and not portable).
4. getche():
Reads a character from the keyboard and echoes it to the screen.
Similar to getch(), but it displays the input character.
Requires conio.h header (non-standard and not portable).
Note: getch() and getche() are not standard C functions and are not recommended for portable
and modern C programming. Prefer using getc() or getchar() for standard and portable input
operations.
Not understanding the question correctly: Listen carefully and rephrase if needed.
Beginner: Understanding core concepts like variables, operators, control flow, and
functions.
Intermediate: Pointers, arrays, structures, memory allocation, and recursion.
Advanced: Algorithms, data structures (linked lists, trees), bit manipulation, and operating
system concepts.
C interview questions can range from basic syntax and data types to complex memory
management and design patterns. They are typically categorized as:
Import is a keyword, but #include is a statement processed by pre-processor software.
#include increases in the size of the code.
Related Interview Articles:
C++ interview questions
C# interview questions
Java interview questions
Javascript Interview Questions
JQuery Interview Questions
In conclusion, mastering these top 50 C language interview questions is pivotal for aspiring
programmers. These insights into fundamental concepts, data structures, and algorithms
equip candidates with the knowledge needed to succeed in technical interviews. Practice,
understanding, and confidence in these areas will undoubtedly pave the way to a successful
C programming career. You can also consider doing our C programming tutorial from
ScholarHat to upskill your career.
Conclusion
FAQs
Q1. What are the different levels of difficulty in C interview
questions?
Q2. What are some common mistakes candidates make in C
interviews?
Being unfamiliar with basic C concepts: Brush up on the fundamentals.
Not explaining their thought process: Talk through your approach even if stuck.
Poor code quality: Write clean, readable, and well-commented code.
Lack of confidence: Practice and showcase your enthusiasm for C programming.
Improving problem-solving skills for C interview questions involves regular practice and
exposure to a variety of coding challenges. Utilize online platforms, coding competitions, and
resources such as textbooks and tutorials to enhance your problem-solving abilities.
To prepare for a C programming interview, it's essential to review core concepts such as data
types, operators, arrays, pointers, and memory management. Additionally, practice solving
coding problems and familiarize yourself with common algorithms and data structures
implemented in C.
In a C interview, you can expect a mix of theoretical questions to assess your understanding of
concepts and practical coding problems to evaluate your problem-solving skills. Questions may
range from basic syntax and language features to more complex algorithms and data
manipulation tasks.
Q3. How should I prepare for a C programming interview?
Q4. What types of questions can I expect in a C interview?
Q5. How can I improve my problem-solving skills for C interview
questions?
HTML to PDF

More Related Content

PPTX
Direct linking loaders
PPTX
Os unit 3
PPTX
Machine Learning Interview Questions 2024 | ML Interview Questions And Answer...
PDF
System Design.pdf
PPTX
Interfacing With High Level Programming Language
PDF
Linker and Loader Explained
PPTX
Computer Science PowerPoint Presentation
PDF
Compiler design-lab-manual v-cse
Direct linking loaders
Os unit 3
Machine Learning Interview Questions 2024 | ML Interview Questions And Answer...
System Design.pdf
Interfacing With High Level Programming Language
Linker and Loader Explained
Computer Science PowerPoint Presentation
Compiler design-lab-manual v-cse

What's hot (20)

PPT
Minimization of Boolean Functions
PPTX
Special Cases in Simplex Method
PDF
Daa notes 3
PPTX
Topological Sort Algorithm.pptx
ODP
D Flip Flop
PPTX
Chapter1p1
PPTX
PPTX
D flip Flop
PPTX
15 puzzle problem using branch and bound
PPSX
Intelligent Sudoku Solver
PPTX
Minimum Modes and Maximum Modes of 8086 Microprocessor
PPTX
Booth’s algorithm.(a014& a015)
PPTX
Inference in First-Order Logic
PPTX
PPTX
Agents and environments
PPTX
push down automata
PPT
Logic families
PPTX
Problem Formulation in Artificial Inteligence Projects
PPTX
Np hard
PPTX
design of accumlator
Minimization of Boolean Functions
Special Cases in Simplex Method
Daa notes 3
Topological Sort Algorithm.pptx
D Flip Flop
Chapter1p1
D flip Flop
15 puzzle problem using branch and bound
Intelligent Sudoku Solver
Minimum Modes and Maximum Modes of 8086 Microprocessor
Booth’s algorithm.(a014& a015)
Inference in First-Order Logic
Agents and environments
push down automata
Logic families
Problem Formulation in Artificial Inteligence Projects
Np hard
design of accumlator
Ad

Similar to C Interview Questions PDF By Scholarhat.pdf (20)

PDF
C interview questions
PDF
C question-bank-ebook
PDF
Top C Language Interview Questions and Answer
PDF
C interview-questions-techpreparation
PDF
Interview Questions For C Language
PDF
Basic Information About C language PDF
PPTX
Interview Questions For C Language .pptx
PPTX
C programming tutorial for Beginner
PPTX
C programming interview questions
PDF
C question-answer-bank
PDF
C basic questions&amp;ansrs by shiva kumar kella
PDF
C Language Interview Questions: Data Types, Pointers, Data Structures, Memory...
PPTX
c-introduction.pptx
PDF
Learn c language Important topics ( Easy & Logical, & smart way of learning)
PPTX
Cprogramminginterviewquestions 120622074544-phpapp01
DOCX
interview questions.docx
PDF
C interview-questions-techpreparation
PDF
C Interview Questions for Fresher
PDF
C interview-questions-techpreparation
PDF
C interview Question and Answer
C interview questions
C question-bank-ebook
Top C Language Interview Questions and Answer
C interview-questions-techpreparation
Interview Questions For C Language
Basic Information About C language PDF
Interview Questions For C Language .pptx
C programming tutorial for Beginner
C programming interview questions
C question-answer-bank
C basic questions&amp;ansrs by shiva kumar kella
C Language Interview Questions: Data Types, Pointers, Data Structures, Memory...
c-introduction.pptx
Learn c language Important topics ( Easy & Logical, & smart way of learning)
Cprogramminginterviewquestions 120622074544-phpapp01
interview questions.docx
C interview-questions-techpreparation
C Interview Questions for Fresher
C interview-questions-techpreparation
C interview Question and Answer
Ad

More from Scholarhat (20)

PDF
React Redux Interview Questions PDF By ScholarHat
PDF
React Redux Interview Questions PDF By ScholarHat
PDF
React Router Interview Questions PDF By ScholarHat
PDF
JavaScript Array Interview Questions PDF By ScholarHat
PDF
Java Interview Questions PDF By ScholarHat
PDF
Java Interview Questions for 10+ Year Experienced PDF By ScholarHat
PDF
Infosys Angular Interview Questions PDF By ScholarHat
PDF
DBMS Interview Questions PDF By ScholarHat
PDF
API Testing Interview Questions PDF By ScholarHat
PDF
System Design Interview Questions PDF By ScholarHat
PDF
Python Viva Interview Questions PDF By ScholarHat
PDF
Linux Interview Questions PDF By ScholarHat
PDF
Kubernetes Interview Questions PDF By ScholarHat
PDF
Collections in Java Interview Questions PDF By ScholarHat
PDF
CI CD Pipeline Interview Questions PDF By ScholarHat
PDF
Azure DevOps Interview Questions PDF By ScholarHat
PDF
TypeScript Interview Questions PDF By ScholarHat
PDF
UIUX Interview Questions PDF By ScholarHat
PDF
Python Interview Questions PDF By ScholarHat
PDF
OOPS JavaScript Interview Questions PDF By ScholarHat
React Redux Interview Questions PDF By ScholarHat
React Redux Interview Questions PDF By ScholarHat
React Router Interview Questions PDF By ScholarHat
JavaScript Array Interview Questions PDF By ScholarHat
Java Interview Questions PDF By ScholarHat
Java Interview Questions for 10+ Year Experienced PDF By ScholarHat
Infosys Angular Interview Questions PDF By ScholarHat
DBMS Interview Questions PDF By ScholarHat
API Testing Interview Questions PDF By ScholarHat
System Design Interview Questions PDF By ScholarHat
Python Viva Interview Questions PDF By ScholarHat
Linux Interview Questions PDF By ScholarHat
Kubernetes Interview Questions PDF By ScholarHat
Collections in Java Interview Questions PDF By ScholarHat
CI CD Pipeline Interview Questions PDF By ScholarHat
Azure DevOps Interview Questions PDF By ScholarHat
TypeScript Interview Questions PDF By ScholarHat
UIUX Interview Questions PDF By ScholarHat
Python Interview Questions PDF By ScholarHat
OOPS JavaScript Interview Questions PDF By ScholarHat

Recently uploaded (20)

PDF
Classroom Observation Tools for Teachers
PDF
1_English_Language_Set_2.pdf probationary
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
Practical Manual AGRO-233 Principles and Practices of Natural Farming
PPTX
Introduction to Building Materials
PDF
Paper A Mock Exam 9_ Attempt review.pdf.
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PDF
LNK 2025 (2).pdf MWEHEHEHEHEHEHEHEHEHEHE
PPTX
Orientation - ARALprogram of Deped to the Parents.pptx
PPTX
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
PPTX
Radiologic_Anatomy_of_the_Brachial_plexus [final].pptx
PDF
RMMM.pdf make it easy to upload and study
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
A powerpoint presentation on the Revised K-10 Science Shaping Paper
PDF
Hazard Identification & Risk Assessment .pdf
PPTX
Chinmaya Tiranga Azadi Quiz (Class 7-8 )
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PPTX
UNIT III MENTAL HEALTH NURSING ASSESSMENT
PDF
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
Classroom Observation Tools for Teachers
1_English_Language_Set_2.pdf probationary
Chinmaya Tiranga quiz Grand Finale.pdf
Practical Manual AGRO-233 Principles and Practices of Natural Farming
Introduction to Building Materials
Paper A Mock Exam 9_ Attempt review.pdf.
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
LNK 2025 (2).pdf MWEHEHEHEHEHEHEHEHEHEHE
Orientation - ARALprogram of Deped to the Parents.pptx
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
Radiologic_Anatomy_of_the_Brachial_plexus [final].pptx
RMMM.pdf make it easy to upload and study
Supply Chain Operations Speaking Notes -ICLT Program
A powerpoint presentation on the Revised K-10 Science Shaping Paper
Hazard Identification & Risk Assessment .pdf
Chinmaya Tiranga Azadi Quiz (Class 7-8 )
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
UNIT III MENTAL HEALTH NURSING ASSESSMENT
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf

C Interview Questions PDF By Scholarhat.pdf

  • 1. Top 50 Mostly Asked C Interview Questions and Answers C Interview Questions and Answers: An Overview Are you preparing for a C interview? Feeling excited but quite nervous at the same time? fear not..! This comprehensive guide is here to guide you to demonstrate a solid grasp of C concepts, help you to grow your problem-solving skills, and also make you feel confident to ace your interview. In the Programming world, C remains a foundational language for systems programming, embedded systems, and performance-critical applications. By understanding its complexities, you will conquer half of the programming languages that exist. Interviewers often use C- specific terms to analyze the understanding of your C knowledge such as Why are C Interview Questions Important?
  • 2. 1. Memory management: C gives you direct control over memory, which can be powerful and challenging. Be prepared to explain concepts like pointers, dynamic allocation, and common memory-related pitfalls. 2. Problem-solving and algorithmic thinking: Interviewers want to see how you approach problems analytically, break them down into manageable steps, and write efficient C code to achieve the desired outcome. 3. Best practices and coding style: Following good practices demonstrates your professionalism and attention to detail. Be familiar with common C conventions, coding guidelines, and readability tips. Now that you have a solid understanding of why C interview questions and how to prepare for them, let's see some advanced terms you might encounter in an interview. This guide covers various categories: 1. Basics and Syntax: Test your understanding of fundamental C concepts, data types, operators, and control flow. 2. Memory Management: Master pointers, dynamic allocation, and memory-related pitfalls. 3. Data Structures and Algorithms: Explore common C data structures (arrays, linked lists, stacks, queues, trees, etc.) and demonstrate your ability to implement algorithms using them. 4. Advanced Concepts: Get comfortable with preprocessor directives, bitwise operations, unions, structures, and advanced function pointers. 5. Problem Solving and Coding: Apply your knowledge to solve real-world programming challenges using efficient and well-structured C code. Keep in mind for a good communicative interview Sometimes be in the interviewer's shoes too, Don't just answer, ask! Show your genuine interest by crafting insightful questions about the company, role, and team. Explore the depth of C programming with our comprehensive guide to 50 C Interview Questions and Answers. Whether you're a beginner or an experienced developer, this resource provides valuable insights, helping you master essential concepts and excel in C-related interviews. C Interview Questions: A Roadmap to Success C Interview Questions and Answers for Freshers HTML to PDF
  • 3. 3. What is a token? Tokens are the discrete components of a program. There are 6 tokens in C language, those are- 2. What are the features of the C language? 1. Why is C called a mid-level programming language? C possesses features of both lower-level and higher-level, or assembly-level, languages. C is hence frequently referred to be a middle-level language. One may write both a menu-driven consumer billing system and an operating system in C. 1. Identifiers 2. Keywords 3. Constants 4. Operators 5. Special Characters Middle-level language: Provides low-level memory access and high-level abstractions, balancing efficiency and ease of use. Portability: Code written in C can run on different platforms with minimal modifications. Efficiency: Offers efficient memory management and execution speed. Roch Standard Library: Provides a comprehensive set of functions for various tasks. Procedural Language: Follows a structured, step-by-step approach to solving problems.
  • 4. . Strings Printf()- To print the output to the screen, use print(). Scanf()- To read formatted data from the keyboard, use scanf(). The following are a few datatype format specifiers that can be used for scanning and printing: %d- It's a format specifier for datatypes that prints and scans integer values. %s- This datatype format specifier is used to print and scan strings in the program. %c- It is a format specifier for a datatype that is used to display and scan character values. %f- The float value may be seen and scanned using the datatype format specifier %f. In C programming, basic data types include: Primitive Data type- There are two other categories of primitive data types: integer and floating. User-Defined data types- The user defines these data types to improve program readability. Derived data types- Data types that come from pre-built or basic data types. The answer is "f". In C-style languages, the expression 5["zyzuv"] is equivalent to "zyzuv" [5], which accesses the 6th character of the string "zyzuv". Therefore, the value of the expression is "v". 5. What's the value of the expression 5["zyzuv"]? 6. What are basic data types supported in the C Programming Language? 4. What is the use of printf() and scanf() functions? Also, explain format specifiers?
  • 5. 9. What is a Preprocessor? A software application known as a preprocessor is used to handle source files before submitting them to be built. The preprocessor allows for the inclusion of header files, macro expansions, conditional compilation, and line control. 7. What is a built-in function in C? The built-in C functions scanf(), printf(), strcpy, strlwr, strcmp, strlen, strcat, and many more are used often. 8. What do you mean by the scope of the variable? In programming languages, scope refers to the block or region where a specified variable will live; if the variable extends outside of that block or region, it will be immediately destroyed. Every variable has a certain range of use. To put it simply, a variable's scope is determined by how long it remains in the program. Three different places can define the variable. They are as follows: The term "built-function" refers to library functions that the system provides to developers to help them with specific frequently performed predefined tasks, hence simplifying their lives. For instance, printf() in C is used when you need to print your program's output to the terminal. 1. Local Variables: Located within a certain block or function 2. Global Variables: Among all the functions that the program does globally. 3. Formal parameters:These are limited to in-function parameters.
  • 6. 10. What are preprocessor directives in C? Preprocessor directives in C are built-in predefined functions or macros that are performed before program execution and serve as instructions to the compiler. The process of creating and running a C program involves several phases. Macros, File Inclusion, Conditional Compilation, and Other directives like #undef, #pragma, etc. are the main categories of Preprocessor Directives.
  • 7. 11. What is the use of static variables in C? In the C programming language, data values are preserved across function calls even after they have exited their scope thanks to the usage of static variables. Static variables don't require initialization each time they are used in a program; their values are preserved inside their scope. Without initialization, the initial value of a static variable is set to 0. 12. What is the difference between malloc() and calloc() in the C programming language? The library methods malloc() and calloc() are used to allocate dynamic memory. The memory that is allocated from the heap section while the program is running is known as dynamic memory. The header file "stdlib.h" is what makes dynamic memory allocation in the C programming language possible. Parameter Definition Run Code >> Malloc() It is a function that generates a single, fixed-size memory block. Calloc() It is a function that allows a single variable to be assigned to several memory blocks. // C program to print initial // value of static variable #include <stdio.h> int main() { static int var; int x; printf("Initial value of static variable %dn", var); printf("Initial value of variable without static %d", x); return 0; }
  • 8. Efficiency Usage Number arguments Speed Run Code >> of One argument is all that is needed. Calloc() is slower than the malloc() procedure. It is quite efficient with time. There must be two arguments. Compared to malloc(), calloc() is slower. It is not very time-efficient. It serves as a signal for contiguous memory allocation. It allocation indicator. serves as a memory Recursion in C is a programming technique where a function calls itself directly or indirectly to solve a problem. In recursive functions, the function breaks down the problem into smaller subproblems and calls itself with modified arguments until a base case is reached, stopping the recursive calls. 13. What is Recursion in C? Syntax of recursive function in the C Compiler void do_recursion() { ... .. ... do_recursion(); ... .. ...] } int main() { ... .. ... do_recursion(); ... .. ... }
  • 9. Watch the Video - Recursion In C Local Variables Declared within a function or a block. Global Variables Variables declared outside of a function or block. Global Variables store the default value of zero Local Variables store a garbage value by default After a block or function, the local variables' life is terminated. If the programmer does not specify a variable, it is kept inside the stack. Parameter passing is necessary for other functions to access the local variables. The global variable remains valid till the execution of the program. The compiler determines where the global variable is stored. Passing parameters is not necessary. During the program, they are visible to everyone worldwide. A pointer in C is a variable that holds the memory address of another variable. It allows direct manipulation of memory locations, enabling dynamic memory allocation, efficient array handling, and indirect access to data. Pointers are a fundamental feature used for tasks like data structures and dynamic memory management. 15. What is a Pointer in C? 14. What is the difference between the Local and Global Variables in C?
  • 10. 17. How can we create an Infinite loop in C? Let's see how we create infinite loop in C 16. Define Loops in C language. What are the types of loops in C? Loops in C are programming constructs that repeatedly execute a block of code as long as a specified condition is true. They enable efficient iteration through data, simplifying tasks like array manipulation or repetitive operations, ensuring code efficiency and maintainability. Common loop types in C include for, while, and do-while. Watch the Video - What are Loops in C? // C program for infinite loop // using for, while, do-while #include // Driver code
  • 11. 19. What is Typecasting in C? Typecasting in C is the process of converting one data type into another. It allows a variable to be treated as a different type temporarily. For example, converting an integer to a float or a pointer from one data type to another is done using typecasting operators like (float) or (int*). 18. What is the Pointer to Pointer in C? In C, a pointer to a pointer, also known as a double pointer, is a variable that holds the address of another pointer variable. It allows indirect access to a memory location, providing a way to modify pointers and dynamically allocate multi-dimensional arrays, enhancing flexibility in memory management and data structures. Run Code >> (data_type)expression; int main() { for (;;) { printf("Infinite-loopn"); } while (1) { printf("Infinite-loopn"); } do { printf("Infinite-loopn"); } while (1); return 0; } int **p; // pointer to a pointer which is pointing to an integer Syntax
  • 12. Output Example Explanation Run Code >> Type Casting Type Conversion With the use of a casting operator, a programmerA compiler transforms the data type transforms the data type into another data type. into another data type. It may be used on incompatible as well as compatible forms of data. A caste operator is required in type casting to cast the data type into another data type. Type casting is more dependable and efficient. Only suitable data types can be used with type conversion. A casting operator is not required during type conversion. Compared to type casting, type conversion is less dependable and The given C code in the C Online Compiler initializes an integer variable x with the value 97 and then uses a for loop to print the characters corresponding to ASCII values from 97 to 122. In the ASCII table, these values represent lowercase English letters from 'a' to 'z'. abcdefghijklmnopqrstuvwxyz int x; for(x=97; x<=122; x++) { printf("%c", (char)x); /*Explicit casting from int to char*/ } 20. What is the Difference between Type Casting and Type Conversion?
  • 13. Syntax: destination_data_type = (target_data_type) variable_to_be_converted; efficient. Syntax: int a = 20; float b; b = a; // a = 20.0000 Macro Preprocessed macros are used. Using a macro, the code length is enhanced. Function The functions are compiled. Using a function does not affect code length. With a macro, execution speed is increased. Using a function results in reduced execution speed. Control is transferred during the function call. The macro name is replaced by the macro value before compilation. A pre-processor command that designates a group of C statements is called a macro. The pre- processor directive defines a macro. Since macros are preprocessed, our program would not have been compiled until after all of the macros had been preprocessed. Functions are compiled rather than preprocessed, though. In C programming, header files are files containing function declarations and macro definitions. They allow code reuse by providing function prototypes to other source files. Commonly used header files include <stdio.h> for input/output functions and <stdlib.h> for memory allocation functions. Header files in C serve several purposes: C Programming Interview Questions for Intermediates 21. What are header files in C and their uses? 22. What is the difference between macro and functions? 23. Specify different types of decision control statements in C
  • 14. There are two primary techniques in C for converting strings to numbers: string streams and the stoi() and atoi() library functions. sscanf()- Instead of using normal input, it reads data from a string. In C, a structure is a user-defined data type that allows you to group variables of different data types under a single name. It is used to represent a record containing different fields, enabling you to store and manipulate related data more efficiently. Example atoi()- This method returns an integer value when it receives a character array or a string literal as input. In a program, each keyword is designed to carry out a certain function. They cannot be used for reasons other than those for which they were designed since their meaning has already been established. The programming language C has 32 keywords supported. Reserved keywords include things like auto, else, if, long, int, switch, typedef, and so on. A program executes each sentence one at a time, starting at the top and working down. Depending on the circumstance, control statements are used to execute or move control from one area of the program to another. The different types of control statements are: Simple if statement if...else statement if else...if ladder nested if...else statement Switch statement. 26. What is a Structure in C? 25. What are Reserved Keywords in C? 24. How to convert a String to Numbers in C?
  • 15. Explanation The given C program in C Editor defines a structure student with member name, roll_no, address, and branch. It then creates an object of this structure, initializes its members, and prints the values of these members Run Code >> return 0; } // C Program to show the // use of structure #include #include // Structure student declared struct student { char name[20]; int roll_no; char address[50]; char branch[50]; }; // Driver code int main() { struct student obj; strcpy(obj.name, "Urmi_Bose"); obj.roll_no = 19; strcpy(obj.address, "Kolkata"); strcpy(obj.branch, "Computer Science And Engineering"); // Accessing members of student obj printf("Name: %sn", obj.name); printf("Roll_No: %d n", obj.roll_no); printf("Address: %sn", obj.address); printf("Branch: %s", obj.branch);
  • 16. Syntax Output Example int val = 20;Here, union name_of_union { data_type name; data_type name; }; Name: Urmi_Bose Roll_No: 19 Address: Kolkata Branch: Computer Science And Engineering val is the ‘l-value’, and 20 is the ‘r-value’. 27. What is Union in C? In C, a union is a user-defined data type that allows different data types to be stored in the same memory location. Unlike structures, unions use the same memory space for all members, allowing only one member to hold a value at any given time. Unions are often used to save memory when different data types need to share the same memory location. 28. What is an r-value and l-value? When an object has an address or a unique position in memory, it is referred to as an "l-value." Either the left or right side of the assignment operator(=) will display a "l-value." A data value kept in memory at a specific location is called a "r-value." An object without a known location in memory is referred to as an "r-value" (i.e. without an address). An expression that cannot have a value assigned to it is known as a "r-value," and it can only appear on the right side of an assignment operator (=).
  • 17. 29. What is the Call by value in C? In C, call by value is a method of passing arguments to functions. When a function is called with parameters, the values of the parameters are copied into the function's parameters. Any modifications made to the parameters inside the function do not affect the original values outside the function. 30. What is the Call by reference in C? Call by reference in C involves passing the memory address of a variable to a function, allowing the function to modify the actual value at that address. Changes made to the parameter inside the function are reflected outside the function, as the function operates on the original data in memory. 31. What is the difference between Call by Value and Call by Reference in C? Certainly, here are the differences between call by value and call by reference in C: Watch the Video - Difference Between CallBy Value & CallBy Reference Call by Value Parameters are passed by value, meaning the actual values are passed to the function. Call by Reference Parameters are passed by reference, meaning the memory address (reference) of the actual variable is passed. The function receives a copy of the argument's value, and any modifications made inside the function do not affect the original variable. Suitable for basic data types like int, float, and char, where changes made inside the function don't reflect outside the function scope. The function receives the memory address of the argument, allowing modifications inside the function to directly affect the original variable. Suitable for complex data structures like arrays and structs, where changes made inside the function reflect outside the function scope.
  • 18. Efficient in terms of memory, as only values are passed. More memory-intensive, as passing memory addresses. it involves In C, enumerations (enums) are user-defined data types that consist of a set of named integer constants. Enums provide a way to create symbolic names (enumerators) for integral values, making code more readable and understandable. Enums are often used to define sets of related integer values with meaningful names. 32. What are the Enumerations in C? Syntax Example include // Enum declaration enum Days { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }; int main() { // Enum variable declaration enum Days today; // Assigning a value to the enum variable today = WEDNESDAY; // Printing the value of the enum variable printf("Today is: "); enum enumeration_name{constant1, constant2, ... };
  • 19. Explanation // Switch case to determine the day switch (today) { case SUNDAY: printf("Sunday"); break; case MONDAY: printf("Monday"); break; case TUESDAY: printf("Tuesday"); break; case WEDNESDAY: printf("Wednesday"); break; case THURSDAY: printf("Thursday"); break; case FRIDAY: printf("Friday"); break; case SATURDAY: printf("Saturday"); break; default: printf("Invalid day"); break; } return 0; } Run Code >>
  • 20. In this code in the C Online Editor, an enumeration Days is defined with the days of the week. The program sets the today variable to WEDNESDAY and prints the corresponding day using a switch statement. Output Today is: Wednesday printf("Please Enter number of Elements: "); scanf("%d", &num); // C program to print Fibonacci Series // with recursion and without recursion #include // Recursive Function to print // Fibonacci Series void Fibonacci(int num, int first, int second, int third) { if (num > 0) { third = first + second; first = second; second = third; printf("%d ", third); // Recursive call for it's // n-1 value Fibonacci(num - 1, first, second, third) } } // Driver code int main() { int num; 33. Write a C program to print the Fibonacci series using recursion and without using recursion.
  • 21. Output return 0; } first = second; second = third; } printf("%d ", third); printf("%d %d ", 0, 1); printf("%d %d ", 0, 1); Fibonacci(num - 2, 0, 1, 0); int first = 0, second = 1, third = 0; // we are passing n-2 because we have // already printed 2 numbers i.e, 0 and 1 // Loop will start from 2 because we have // already printed 0 and 1 for (int i = 2; i < num; i++) { third = first + second; printf( "Fibonacci Series with the help of Recursion:n"); printf("nFibonacci Series without Using Recursion:n"); Run Code >>
  • 22. struct Point { int x; int y; }; struct Point p1; Please Enter number of Elements: 5 Fibonacci Series with the help of Recursion: 0 1 1 2 3 Fibonacci Series without Using Recursion: 0 1 1 2 3 34. What is the difference between Struct and Union in C? Usage: Accessing Members: Memory Efficiency: Memory Allocation: Struct Union Each member in a struct has its own memory location, and the total memory occupied by a struct is the sum of the sizes of its members. Useful when different types of data need to be stored simultaneously, allowing access to each member independently. Allocates memory for each member, which can lead to higher memory usage when storing multiple types of data. Members independently using the dot (.) operator. All members share the same memory location. The size of a union is determined by the largest member within it. Ideal when only one type of data needs to be stored at a time, conserving memory by sharing the same memory location for different members. Saves memory by sharing memory space; however, accessing the correct member is crucial to avoid data misinterpretation. Only one member can be accessed at a time, using the dot (.) operator like structs. are accessed Example (Struct):
  • 23. Example (Union): 35. What are Static Memory Allocation and Dynamic Memory Allocation in C? Static memory allocation- Static memory allocation is the type of memory allocation that occurs during compilation. Allocating static memory reduces operating time. Because memory is allocated from the stack, it is quicker than dynamic memory allocation. Compared to dynamic memory allocation, this form of memory allocation is less effective. Within the array, it is mostly favored. Run Code >> Run Code >> Dynamic memory allocation- Dynamic memory allocation is the process of allocating memory during runtime or execution. Because dynamic memory allocation uses the heap for memory allocation, it is slower than static memory allocation. When compared to static memory p1.x = 1; p1.y = 2; union Data { int i; float f; char c; }; union Data d; d.i = 10; printf("%d", d.i); // Output: 10 d.f = 3.14; printf("%f", d.f); // Output: 3.140000
  • 24. Run Code >> typedef in C is used to create custom data type aliases. It allows programmers to define names for existing data types, making the code more readable and adaptable. Custom types created with typedef can simplify complex declarations and enhance code clarity. You can track every memory allocation you make, plan to the point where you wish to destroy (in a good sense) that memory, and then remove it there to prevent memory leaks. Using the C++ smart pointer in C to connect it to GNU compilers is an additional method. An alias name for the current complex type definition is provided by typedef. You may easily make an alias for any type with typedef. Typedef will let you write shorter code, whether you're allocation, this form of memory allocation is more efficient. Most people in the linked list favor it. Depending on the size of the data type, assigning a variable requires space in either our heap or RAM. Nevertheless, if a programmer uses heap memory and forgets to delta it, eventually all of the RAM's memory will be used up and there won't be any more memory, which could result in a memory leak. C Interview Questions and Answers for Experienced 36. What is a Memory Leak? How to avoid it? 37. What is typedef? int main() { char * ptr = malloc(sizeof(int)); /* Do some work */ /*Not freeing the allocated memory*/ return 0; } typedef <existing-type> <new-type-identifiers>; HTML to PDF declaring a sophisticated function pointer, structure, or simple integer.
  • 25. 38. Write a C program to check whether a number is prime or not. // C program to check if a // number is prime #include #include // Driver code int main() { int num; int check = 1; printf("Enter a number: n"); scanf("%d", &num); // Iterating from 2 to sqrt(num) for (int i = 2; i <= sqrt(num); i++) { // If the given number is divisible by // any number between 2 and n/2 then // the given number is not a prime number if (num % i == 0) { check = 0; break; } } if (num <= 1) { check = 0; } if (check == 1) { printf("%d is a prime number", num); } else { printf("%d is not a prime number", num); } return 0; }
  • 26. Run Code >> Source Code The programmer creates the source code. Object Code A translator such as a compiler can produce object code. Low-level programming is incomprehensible to humans. Compared to source code, object code has more statements and cannot be changed. Object code is system-specific and modifiable. High-level, easily understood by humans code. Compared to object code, source code is easier to modify and has fewer statements. Source code is not system-specific and is subject to change over time. A function that uses pass-by-reference can change a variable without copying it. Since the provided parameter and variable share the same memory address, any modifications made to the argument will also affect the variables. Explanation This C program checks whether a given number is prime or not. It takes an input number, iterates from 2 to the square root of the input, and checks for divisibility. If the number is divisible by any value in this range, it's not prime. If it's less than or equal to 1, it's not prime either. The result is displayed accordingly. 40. What is Pass-by-Reference in functions? 39. How is Source Code different from Object Code? Example // C program to change a variable // using pass by reference #include // * used to dereference the variable void change(int* num)
  • 27. Output Explanation Run Code >> In this code, the change function takes a pointer to an integer as a parameter and modifies the value stored at that memory location. The address of the num variable is passed to the change function using the & operator. As a result, the value of num inside the main function is changed to 34. Value of num before passing is: 12 { // value of num changed to 34 *num = 34; } // Driver code int main() { int num = 12; printf("Value of num before passing is: %dn", num); // Calling change function by passing address change(&num); printf("Value of num after changing with the help of " "function is: %d", num); return 0; } Value of num after changing with the help of function is: 34 41. What is an auto keyword?
  • 28. Run Code >> In the C programming language, each local variable in a function is referred to as an automatic variable. For every variable declared inside a function or block, the default storage class is Auto. Access to auto variables is restricted to the block or function in which they have been defined. With the aid of pointers, we may use them outside of their intended usage. Auto keywords by default have a garbage value. This code uses the printf function inside the if statement condition. The printf function returns the number of characters printed. Since the string "Hello - World" has a non-zero length, the condition evaluates to true and the empty block { } under if is executed, leading to the printing of "Hello - World". 42. Write a program to print “Hello-World” without using a semicolon. Output Explanation Hello - World // C program to print hello-world // without using semicolon #include // Driver code int main() { // This will print the hello-world // on the screen without giving any error if (printf(“Hello - World”)) { } return 0; }
  • 29. 43. Explain Modifiers in C In the C language, modifiers are keywords that are used to alter the meaning of fundamental data types. They outline how much memory should be set aside for the variable. There are five types of modifiers, which are 44. Write a program to print the factorial of a given number with the help of recursion. Run Code >> 1. long 2. short 3. signed 4. unsinged 5. long long // C program to find factorial // of a given number #include <stdio.h> // Function to find factorial of // a given number unsigned int factorial(unsigned int n) { if (n == 0) return 1; return n * factorial(n - 1); } // Driver code int main() { int num = 5; printf("Factorial of %d is %d", num, factorial(num)); return 0; }
  • 30. Output Explanation In C programming, both #include "..." and #include <...> are used to include header files, but they differ in their search paths and usage: #include "..." (Double Quotes): The C preprocessor searches the predefined list of system directories for the filename before checking user-specified directories (directories can be added to the predefined list by using the -I option). #include <...> (Angle Brackets): The preprocessor follows the search path given for the #include <filename> form after first searching in the same directory as the file containing the directive. Include programmer-defined header files using this way. Using double quotes ("...") is generally preferred for including project-specific headers, while angle brackets (<...>) are used for standard library or system headers to distinguish between user-defined and system-provided header files. This C program calculates the factorial of a given number using recursion. The factorial function recursively calculates the factorial: n! = n * (n-1)!. In the main function, the program calculates the factorial of 5. The program computes 5! Which is equal to 5 * 4 * 3 * 2 * 1 = 120, and prints the result. Factorial of 5 is 120 // C program to determine whether // the given number is Armstrong // or not #include // Driver code int main() 46. Write a program to check an Armstrong number. 45. What is the difference between #include "..." and #include <...>?
  • 31. Output Explanation Run Code >> This C program checks if a given number is an Armstrong number or not. It calculates the sum of cubes of its digits and compares it with the original number. If they are equal, it's an Armstrong number. 1^3 + 5^3 + 3^3 = 153, which matches the original number. { int n; printf("Enter Number n"); scanf("%d", &n); int var = n; int sum = 0; // Loop to calculate the order of // the given number while (n > 0) { int rem = n % 10; sum = (sum) + (rem * rem * rem); n = n / 10; } // If the order of the number will be // equal to the number then it is // Armstrong number. if (var == sum) { printf("%d is an Armstrong number n", var); } else { printf("%d is not an Armstrong number", var); } return 0; }
  • 32. 153 is an Armstrong number include <stdio.h> #include <stdlib.h> // Node structure representing a node in the linked list struct Node { int data; struct Node* next; }; // Function to merge two sorted linked lists struct Node* mergeSortedLists(struct Node* list1, struct Node* list2) { if (list1 == NULL) return list2; if (list2 == NULL) return list1; if (list1->data < list2->data) { list1->next = mergeSortedLists(list1->next, list2); return list1; } else { list2->next = mergeSortedLists(list1, list2->next); return list2; } } // Function to create a new node with given data struct Node* createNode(int data) { struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); newNode->data = data; newNode->next = NULL; return newNode; } // Function to print the merged linked list void printList(struct Node* node) { while (node != NULL) { printf("%d ", node->data); node = node->next; } 47. Merge two sorted Linked Lists in C
  • 33. Output Explanation Run Code >> In this program, two sorted linked lists (list1 and list2) are merged into a new sorted linked list (mergedList). The merged list is then printed. return 0; } First sorted linked list: 1 3 5 Second sorted linked list: 2 4 6 printf("n"); } // Driver code int main() { struct Node* list1 = createNode(1); list1->next = createNode(3); list1->next->next = createNode(5); struct Node* list2 = createNode(2); list2->next = createNode(4); list2->next->next = createNode(6); printf("First sorted linked list: "); printList(list1); printf("Second sorted linked list: "); printList(list2); struct Node* mergedList = mergeSortedLists(list1, list2); printf("Merged sorted linked list: "); printList(mergedList);
  • 34. Merged sorted linked list: 1 2 3 4 5 6 48. What is the use of an extern storage specifier? In the C language, the extern keyword is used to increase the visibility of C variables and functions. External can be shortened to extern. When a specific file wants to access a variable from any other file, it is used. Variables containing the extern keyword are simply declared, not defined, which increases duplication. There is no need to declare or create extern functions because they are visible by default throughout the program. 50. How is import in Java different from #include in C? 49. What is the difference between getc(), getchar(), getch() and getche() in C? 1. getc(): Reads a character from the specified file stream (e.g., stdin, file). Requires stdio.h header. Offers flexibility for reading from different input sources. 2. getchar(): Reads a character from the standard input stream (stdin). Requires stdio.h header. Commonly used for simple character input from the keyboard. 3. getch(): Reads a character from the keyboard without echoing it to the screen. Typically used in older MS-DOS and Windows environments. Requires conio.h header (non-standard and not portable). 4. getche(): Reads a character from the keyboard and echoes it to the screen. Similar to getch(), but it displays the input character. Requires conio.h header (non-standard and not portable). Note: getch() and getche() are not standard C functions and are not recommended for portable and modern C programming. Prefer using getc() or getchar() for standard and portable input operations.
  • 35. Not understanding the question correctly: Listen carefully and rephrase if needed. Beginner: Understanding core concepts like variables, operators, control flow, and functions. Intermediate: Pointers, arrays, structures, memory allocation, and recursion. Advanced: Algorithms, data structures (linked lists, trees), bit manipulation, and operating system concepts. C interview questions can range from basic syntax and data types to complex memory management and design patterns. They are typically categorized as: Import is a keyword, but #include is a statement processed by pre-processor software. #include increases in the size of the code. Related Interview Articles: C++ interview questions C# interview questions Java interview questions Javascript Interview Questions JQuery Interview Questions In conclusion, mastering these top 50 C language interview questions is pivotal for aspiring programmers. These insights into fundamental concepts, data structures, and algorithms equip candidates with the knowledge needed to succeed in technical interviews. Practice, understanding, and confidence in these areas will undoubtedly pave the way to a successful C programming career. You can also consider doing our C programming tutorial from ScholarHat to upskill your career. Conclusion FAQs Q1. What are the different levels of difficulty in C interview questions? Q2. What are some common mistakes candidates make in C interviews?
  • 36. Being unfamiliar with basic C concepts: Brush up on the fundamentals. Not explaining their thought process: Talk through your approach even if stuck. Poor code quality: Write clean, readable, and well-commented code. Lack of confidence: Practice and showcase your enthusiasm for C programming. Improving problem-solving skills for C interview questions involves regular practice and exposure to a variety of coding challenges. Utilize online platforms, coding competitions, and resources such as textbooks and tutorials to enhance your problem-solving abilities. To prepare for a C programming interview, it's essential to review core concepts such as data types, operators, arrays, pointers, and memory management. Additionally, practice solving coding problems and familiarize yourself with common algorithms and data structures implemented in C. In a C interview, you can expect a mix of theoretical questions to assess your understanding of concepts and practical coding problems to evaluate your problem-solving skills. Questions may range from basic syntax and language features to more complex algorithms and data manipulation tasks. Q3. How should I prepare for a C programming interview? Q4. What types of questions can I expect in a C interview? Q5. How can I improve my problem-solving skills for C interview questions? HTML to PDF