Top 80+ C Interview Questions And Answers [2024]

Explore 80+ C interview questions, covering basics to advanced topics, essential for both freshers and experienced professionals to excel in interviews and secure roles in the programming field.

  • Testing Framework Interview QuestionsArrow
  • Testing Types Interview QuestionsArrow
  • General Interview QuestionsArrow
  • CI/CD Tools Interview QuestionsArrow
  • Programming Languages Interview QuestionsArrow
  • Development Framework Interview QuestionsArrow
  • Automation Tool Interview QuestionsArrow

OVERVIEW

The C programming language is a fundamental tool in software development, renowned for its efficiency and versatility. Developers need a solid understanding of C, ranging from basic concepts to advanced programming techniques.

This understanding will help fresher candidates or experienced developers to crack C interviews, as they often focus on assessing a candidate's knowledge of core principles and problem-solving skills. By familiarizing yourself with C interview questions, you can gain insights into what employers are looking for and improve your ability to tackle technical challenges effectively.

Note

Download C Interview Questions

Note : We have compiled all the C Interview Questions for your reference in a template format. Check it out now!

Fresher-Level C Interview Questions

Here are some essential C interview questions for freshers. These questions cover fundamental concepts across various C programming topics, helping you build a solid foundation in the language.

By preparing for these questions, you can enhance your understanding and showcase your skills effectively during interviews.

1. What Are the Primary Features of the C Programming Language?

This is one of the most commonly asked C interview questions. So, let’s understand the primary features of the C programming language:

  • Procedural Language: C is procedural, executing tasks step by step using predefined instructions and functions.
  • Fast and Efficient: C works directly with hardware, making it faster than dynamically typed languages.
  • Modularity: C allows code to be saved in libraries for reuse, promoting code reusability.
  • Statically Typed: Variable types are checked at compilation, helping catch errors early and optimizing memory allocation.
  • General-Purpose Language: C is used in various fields, including system programming and operating systems.
  • Rich Set of Built-in Operators: C provides a wide array of built-in operators for crafting complex and simple programs.
  • Middle-Level Language: C combines low-level and high-level language elements, balancing hardware manipulation and high-level abstractions.
  • Portability: C programs can run on various systems with minimal modifications, ideal for cross-platform applications.
  • Easy to Extend: C programs can be easily extended, allowing for the addition of new features and functions.

2. What Are Tokens in C?

Tokens are the fundamental units or elements used to build a C program, making it a crucial question to appear in C interview questions. These tokens hold significance for the compiler. An online C compiler dissects a program into these basic units, called tokens, and then continues through the various stages of compilation.

Types of Tokens in C:

  • Keywords
  • Identifiers
  • Constants
  • Special Characters
  • Strings
  • Operators

3. What Are Keywords?

Keywords are reserved words in C that have predefined meanings understood by the compiler. These words are fundamental to the syntax and cannot be used as identifiers within a program, making this question appear in C interview questions.

Below is a list of these reserved keywords in C:

auto break case char
const continue default do
double else enum extern
float for goto if
int long register return
short signed sizeof static
struct switch typedef union
unsigned void volatile while

4. What Do You Mean by the Scope of the Variable?

The scope of a variable in C refers to the specific block or region within the program where the variable is declared, defined, and accessible. Outside of this area, the variable cannot be accessed and is considered as if it were undeclared. This concept is fundamental in programming and often comes up in C interview questions.

5. What Is the Difference Between Local and Global Variables in C?

Local and global variables in C differ primarily in their scope and lifetime within a program. Below are the differences between local and global variables in C:

Aspect Local Variables Global Variables
Scope Limited to the block where they are declared. Accessible throughout the entire program.
Lifetime It exists only while the block is executing. It exists for the whole duration of program execution.
Storage Typically stored on the stack. Stored in the data segment of memory.
Default Initialization Not initialized by default (containing garbage values). Initialized to zero by default.
Declaration Location Inside functions or blocks. Outside of all functions.
Visibility Only visible within their scope. Visible to all functions (unless explicitly made static).
Memory Efficiency More memory-efficient as memory is allocated/deallocated as needed. They are less memory-efficient as they occupy memory for the entire program runtime.
Data Sharing It cannot be shared between functions unless passed as arguments. It can be shared between functions without passing as arguments.

6. What Is Typedef in C?

The typedef keyword in C is used to assign a new name to an existing data type, making it easier to work with complex types. This concept is often discussed in C interview questions, as it allows you to create an alias for already defined data types, enhancing code readability and maintainability.

Syntax:

typedef existing_data_type new_name;

7. What Are Pointers and Their Uses?

A pointer is a derived data type in C that holds the address of another variable or a specific memory location.

Syntax:

datatype *ptr;
  • datatype is the type of data the pointer will point to (e.g., int, char, float).
  • * is the dereferencing operator.
  • ptr is the name of the pointer variable.

Primary Uses of Pointers:

  • Data Structures: Pointers are crucial in implementing complex data structures like linked lists, trees, and graphs.
  • String Manipulation: String manipulation in C often involves pointer arithmetic.
  • Multi-dimensional Arrays: Pointers to pointers create and manipulate multi-dimensional arrays.
  • Efficient Data Access: Direct memory access through pointers can be more efficient than copying large amounts of data.
  • Memory-mapped Hardware: Pointers access specific memory addresses corresponding to hardware registers.
  • Dynamic Memory Allocation: Pointers are essential for allocating and managing memory at runtime, enabling flexible memory use.
  • Array Manipulation: Pointers can traverse arrays efficiently, as array names often decay to pointers.
  • Function Arguments: Passing pointers allows functions to modify variables in the calling function's scope, enabling pass-by-reference behavior in C.

This is the core concept of understanding C language, and it is often discussed in C interview questions.

8. What Is the Difference Between Type Casting and Type Conversion?

This is a frequent question discussed in C interview questions, and below are the differences between type casting and type conversion in C:

Aspect Type Casting Type Conversion
Definition Explicitly changing the data type of an expression. Implicitly changing the data type of a value.
Initiation Programmer-directed. Automatically performed by the compiler.
Syntax Uses cast operator: (type)expression. There is no specific syntax; it happens in expressions.
Precision May intentionally lose precision. Typically preserves precision when possible.
Compile-time vs. Runtime Evaluated at runtime. Often resolved at compile-time.
Flexibility It can be cast between unrelated types. Limited to compatible types.
Performance Impact It may have a slight runtime cost. Usually optimized by the compiler.
Readability It can clarify intentions. Implicitly, an understanding of the type of promotion rules may be required.
Common Use Cases Forcing specific types of interpretations. Arithmetic operations, assignments.
Example (float)intVariable. Assigning int to float.

9. What Is an Lvalue and Rvalue?

An Lvalue and Rvalue are fundamental concepts in C programming that distinguish between variables that can hold an address in memory and those that represent data values. Understanding the differences between Lvalues and Rvalues is crucial for effective memory management and operations in C; this question is frequently asked in C interview questions.

  • Lvalues: An Lvalue, short for "left value" or "locator value," refers to an object with an identifiable location in memory. The term originates from the fact that Lvalues can appear on the left side of an assignment operator.
  • Rvalues: An Rvalue, short for "right value," refers to a data value stored at some address in memory but doesn't have its identifiable memory location. Rvalues appear on the right side of an assignment operator.

10. What Is the Difference Between Pre-increment and Post-increment in C?

The difference between pre-increment and post-increment operators in C lies in the timing of the increment operation in relation to the value being used in an expression. Understanding these distinctions is essential for proper variable manipulation and control flow in your C programs, making it a common question to appear in C interview questions.

Below are the differences between pre-increment and post-increment operators in C:

Aspect Pre-increment (++x) Post-increment (x++)
Syntax ++variable variable++
Operation Order Increment first, then use the value. Use the current value, then increment.
Return Value Returns the incremented value. Returns the original value before incrementing.
Execution Time Generally, it's slightly faster. It may be slower due to the need to store the original value.
Standalone Statement Behaves the same as post-increment. Behaves the same as pre-increment.
Chaining Can be chained: ++(++x). Chaining not recommended: (x++)++ (undefined behavior).
Precedence Higher precedence than the dereference operator (*). Lower precedence than the dereference operator (*).

11. What Are Loops in C?

Loops in C are constructs that allow for the repeated execution of a block of code until a specified condition is met. They enable programmers to execute statements multiple times efficiently, avoiding code duplication and improving program structure. This topic is frequently discussed in C interview questions.

12. How Can You Create an Infinite Loop in C?

An infinite loop is a type of looping construct that never terminates, resulting in continuous execution of the loop. Also known as an indefinite or endless loop, it can either produce ongoing output or none at all.

To create an infinite loop in C, we can use any loop type. Here are examples of infinite loops using each type:

  • Using a for loop: The for loop has three parts: initialization, condition, and increment/decrement. In this infinite loop, all three parts are left empty (;;). This creates a loop that has no termination condition, thus running infinitely.
  • for (;;) {
        // Code to be executed indefinitely
    }
    
  • Using a while loop: The while loop continues to execute as long as its condition is true. In C, any non-zero value is considered true. Using 1 as the condition, we ensure the loop always evaluates to true, creating an infinite loop.
  • while (1) {
        // Code to be executed indefinitely
    }
    
  • Using a do-while loop: The do-while loop is similar to the while loop but always executes its code block at least once before checking the condition.
  • do {
        // Code to be executed indefinitely
    } while (1);
    
Note

Note : Run your tests with over 3000+ browsers and OS combinations. Try LambdaTest Now!

13. What Is the Difference Between Continue and Break Statements in C?

The continue and break statements in C control the flow of loops and are often compared in C interview questions. The table below highlights the key differences between these two statements:

Aspect Continue Break
Purpose It skips the rest of the current iteration and moves to the next iteration. It terminates the loop or switch statement entirely.
Execution flow Jumps to the next iteration of the innermost loop. Exits the innermost loop or switch statement.
Applicability Used only in loops (for, while, do-while). Used in loops and switch statements.
Remaining iterations Allows remaining iterations to occur. Prevents any further iterations.
Code after statement The code after 'continue' in the current iteration is skipped. Code after 'break' in the loop or switch is not executed.
Use case Skipping specific conditions within a loop. Exiting a loop prematurely when a condition is met.

14. What Are Goto Statements in C? Should We Use Them?

In C, the goto statement is a type of jump statement used to shift the execution flow between different blocks of code. It is an unconditional jump statement that can facilitate looping, but its primary use is to control program flow; this topic is frequently covered in C interview questions.

Syntax:


goto label_name;

// ... other code ...

label_name:
// Code to execute when goto is called

Although the “goto” statement can modify the execution order of instructions, it is often avoided because it can make the code less readable and harder to understand. Additionally, it can exit multiple loops at once instead of using multiple break conditions.

15. What Are the Functions and Their Types?

A large program can be divided into smaller, manageable units called functions in C. Each function consists of a group of programming statements enclosed in . Functions can be called multiple times, enhancing the reusability and modularity of the C program.

Essentially, a program is composed of a collection of functions. In other programming languages, functions are also called procedures or subroutines.

There are two main types of functions in C:

  • Library Function: These are pre-built functions that come with the compiler package. These "built-in functions" have specific purposes and can be used directly without needing to be defined by the programmer. This contrasts user-defined functions, which must be declared and defined before use. Examples of library functions include:
  • printf(), scanf(), malloc(), free(), etc.

    Here's an example using a library function:

    
    #include <string.h>
    #include <stdio.h>
    
    int main()
    {
        char str1[] = "Hello";
        char str2[] = "Developers";
        
        // Using the strcmp() library function to compare strings
        int result = strcmp(str1, str2);
        
        if (result == 0)
            printf("Strings are equal
    ");
        else if (result < 0)
            printf("str1 is less than str2
    ");
        else
            printf("str1 is greater than str2
    ");
        
        return 0;
    }
    

    Output:

    str1 is less than str2
  • User-Defined Functions: On the other hand, programmers create user-defined functions to perform specific tasks. These "custom functions" can be tailored to the program's needs and modified as required. When writing a function that isn't in any header file, you must declare and define it according to C syntax.
  • Here's an example of a user-defined function:

    
    #include <stdio.h>
    
    // User-defined function to check if a number is prime
    int isPrime(int n)
    {
        if (n <= 1) return 0;
        for (int i = 2; i * i <= n; i++)
            if (n % i == 0) return 0;
        return 1;
    }
    
    int main()
    {
        int num = 17;
        
        // Calling the user-defined function
        if (isPrime(num))
            printf("%d is prime
    ", num);
        else
            printf("%d is not prime
    ", num);
        
        return 0;
    }
    

    Output:

    17 is prime

16. What Is the Difference Between Macro and Functions?

In C, both macros and functions are used to perform specific tasks, but they differ significantly in their behavior, usage, and performance characteristics. Understanding these differences is essential, as this topic frequently arises in C interview questions.

Here are the primary differences between macro and functions:

Aspect Macro Function
Definition Preprocessor directive defined using #define. Block of code that performs a specific task.
Type checking No type checking was performed. The compiler performs type-checking.
Return value Does not return a value (simply expands). It can return a value.
Arguments Arguments are not type-checked. Arguments are type-checked.
Memory allocation No memory allocation for execution. Allocates memory on the stack or heap.
Speed Generally faster for small operations. It may be slower due to function call overhead.
Scope Global scope. It can have local or global scope.
Recursion It cannot be recursive. It can be recursive.
Flexibility Less flexible, cannot handle complex logic easily. More flexible and can handle complex operations.

17. What Are Macros? List Some Advantages of Macro Over Functions

In C, a macro is a segment of code that can be replaced by a specified value. It is defined using the #define preprocessor directive and does not require a semicolon (;) at the end. Macros are just names assigned to specific values or expressions and do not point to any memory location.

Each time the compiler comes across a macro, it substitutes the macro name with the defined value. Two macros are not allowed to have the same name.

Syntax:

#define MACRO_NAME(parameters) replacement_text

Some advantages of macros over functions include:

  • Macros are expanded inline, potentially avoiding function call overhead.
  • Macros can work with different data types without needing multiple function definitions.
  • Macros can generate code based on their arguments, which functions cannot do.
  • Macros can define constants without using memory storage.
  • Macros prevent multiple inclusions of header files.

18. What Is the Difference Between Malloc() and Calloc() in the C Programming Language?

In C programming, both malloc() and calloc() are used for dynamic memory allocation, but they have distinct differences in their functionality and behavior. This topic frequently comes up in C interview questions, making it essential to understand the nuances between the two.

Let us see their differences in detail below:

Aspect malloc() calloc()
Function prototype void* malloc(size_t size). void* calloc(size_t num, size_t size).
Number of arguments One Two
Memory initialization Does not initialize allocated memory. Initializes allocated memory to zero.
Return value Pointer to the allocated memory. Pointer to the allocated memory.
Usage Typically used when initialization is not needed. Preferred when zeroed memory is required.
Performance It is generally faster, as it doesn't initialize memory. Slightly slower due to memory initialization.
use case When you need a block of memory, quickly. When allocating arrays or structures that need zero initialization.

19. What Are Header Files and Their Uses?

In C interview questions, header files are frequently discussed due to their vital role in managing shared data across multiple files. They organize data required by different files or functions into a central location, containing definitions, structures, and other essential components.

This centralization simplifies program development and updates. Header files are included in programs using #include statements, earning them the nickname "include files."

Header files are generally defined as:

  • Structures for specific files and subroutines.
  • Typedef synonyms for data types.
  • System parameters or implementation characteristics.
  • Constants and macros used during preprocessing.

Uses of header files include:

  • Allowing multiple source files to utilize the same functions or variables.
  • Separating the interface from the implementation.
  • Ensuring consistent declarations across the project.
  • Hiding implementation details from users of a module.

20. What Is the Meaning of #include in a C Program?

The #include directive is used to include standard or user-defined header files in a C program, typically placed at the beginning of the code. This preprocessor directive is processed by the preprocessor, which inserts the contents of the specified header file—whether system-defined or user-defined—into the C program.

This process of including files is known as file inclusion, allowing the compiler to incorporate external header files into the source code.

21. How Is C# Different From C?

C is primarily known as a procedural language, while C# is more object-oriented. One of the most significant differences is that C# features automatic garbage collection managed by the Common Language Runtime (CLR), a capability absent in C.

Additionally, C# typically relies on the .NET framework for execution, whereas C can run on any platform. This topic is frequently discussed in C# interview questions.

22. What Do You Mean by Dangling Pointers, and How Are Dangling Pointers Different From Memory Leaks in C Programming?

Dangling pointers in C are pointers that reference memory locations that have been deallocated or are no longer valid. This situation often arises when memory is freed, but the pointer isn't updated to reflect this change.

Attempting to access or modify data through a dangling pointer can lead to undefined behavior or program crashes. These issues commonly occur when programmers fail to properly manage pointer lifecycles, particularly in dynamic memory allocation and deallocation scenarios.

Now, let's differentiate dangling pointers and memory leaks, a topic often explored in C interview questions:

Aspect Dangling Pointers Memory Leaks
Definition Pointers referencing deallocated memory. Allocated memory that's no longer accessible.
Cause Using pointers after freeing memory. Failing to free allocated memory.
Main issue Accessing invalid memory. Gradual loss of available memory.
Occurrence timing Immediate after deallocation. Accumulates over time.

23. What Is the Use of Static Variables in C?

Static variables retain their values between function calls, even when they're no longer in scope.

These variables maintain their data throughout the program's execution, allowing them to be reused without reinitialization.

By default, static variables are automatically initialized to 0 if a value is not explicitly assigned. This question has frequently appeared in C interview questions.

Here's an example to understand the behavior of a static variable:


#include <stdio.h>

void countCalls() {
    static int count = 0;  // Static variable initialized only once
    count++;
    printf("This function has been called %d time(s)\n", count);
}

int main() {
    for (int i = 0; i < 5; i++) {
        countCalls();
    }
    return 0;
}

Output:

This function has been called 1 time(s)
This function has been called 2 time(s)
This function has been called 3 time(s)
This function has been called 4 time(s)
This function has been called 5 time(s)

24. What Is the Difference Between Call by Value and Call by Reference?

Call by Value and Call by Reference are two different methods of passing arguments to a function. These methods affect how data is handled and modified within functions.

Below is the comparison table highlighting the differences:

Aspect Call by Value Call by Reference
Definition A copy of the actual argument is passed to the function. The memory address of the actual argument is passed to the function.
Memory usage Creates a new copy of the data, using more memory. It uses the original data's memory location, conserving memory.
Performance Slower for large data structures due to copying. Faster, especially for large data structures, as no copying is involved.
Function declaration Normal variable declaration in function parameters. Uses pointers or reference symbols in function parameters.
Data protection Original data is protected from changes within the function. The function can modify Original data, which may lead to unintended side effects.
Swapping variables Requires returning and reassigning values. It can be done directly within the function.
Null checking Not applicable. Requires checking for null pointers to avoid errors.
Use Used when you want to work with a copy of the data. Used when you want to modify the original data or avoid copying large structures.

25. How Would You Define a Memory Leak, and What Strategies Can Prevent Them?

A memory leak in C programming occurs when dynamically allocated memory is not properly released, causing unused memory to remain occupied, which can lead to system performance degradation. This issue is frequently discussed in C interview questions, as memory management is a critical skill for C programmers.

Common causes of memory leaks include failing to free allocated memory using malloc() or calloc(), mishandling pointers, and not deallocating memory in recursive functions.

Strategies to prevent memory leaks:

  • Always use the free() function to deallocate memory.
  • Implement consistent naming conventions for dynamically allocated variables for easier tracking.
  • Use tools like Valgrind to detect memory leaks.
  • Avoid circular references in dynamically allocated objects to prevent memory retention.

26. What Is a Structure?

A structure in C is a user-defined data type that enables developers to group variables of different data types under one name. Defined using the struct keyword, it allows for more organized management of related data.

Each variable within the structure is known as a member, and these members can hold various data types, making structures highly versatile. This concept frequently arises in C interview questions due to its importance in managing complex data in C programming.

27. What Is Union?

A union in C is a user-defined data type similar to a structure but with one key difference: it allows different variables to share the same memory space. Although a union can have multiple members, only one member can store a value at any given time.

The size of the union is determined by its largest member, making it efficient when memory conservation is needed. Unions are commonly discussed in C interview questions due to their unique memory management capabilities.

28. What Are Enumerations?

An enumeration (or enum) in C is a user-defined data type that consists of a set of named integral constants, making the code more readable and maintainable. Each constant in an enum is assigned a unique integer value, starting from 0 by default, unless explicitly set by the programmer.

Enums are commonly used for representing a group of related values, such as days of the week or error codes.

This question is frequently featured in C interview questions due to their importance in organizing constants effectively.

Syntax:


enum enum_name {
    constant1,
    constant2,
    constant3,
    ...
};

29. What Are Preprocessor Directives in C?

Preprocessor directives in C are instructions that are executed before the actual compilation of the program begins. These directives provide essential commands to the compiler, allowing for tasks like file inclusion, macro definitions, and conditional compilation.

They typically begin with the # symbol and are processed during the precompilation phase.

Common examples of preprocessor directives include #include, #define, and #ifdef. This topic often features in C interview questions due to its significance in controlling how the source code is processed before compilation.

Here's a list of common preprocessor directives in C:

Directive Description
#include Includes the contents of another file.
#define Defines a macro or constant.
#undef Undefines a previously defined macro.
#ifdef Check if a macro is defined.
#ifndef Checks if a macro is not defined.
#if Conditional compilation is based on a constant expression.
#else Alternative for #if
#elif Else if in a conditional compilation.
#endif Ends a conditional compilation block.
#error Generates a compiler error with a specified message.
#pragma Compiler-specific directives.
#line Changes the line number and file name used in compiler messages.
#warning Generates a compiler warning with a specified message.

30. What Is a Volatile Keyword?

The volatile keyword in C tells the compiler that the value of a variable may change unexpectedly and should not be optimized or cached in registers. When a variable is marked as volatile, the compiler ensures that every access reads or writes the actual value from memory, not from a cached version.

This is especially important when dealing with hardware registers or variables shared across multiple threads, as these can be modified outside of the program's control. This concept often appears in C interview questions due to its importance in embedded systems and multithreaded environments.

31. What Is an Auto Keyword?

In C programming, the auto keyword is a storage class that declares local variables with automatic duration. These variables are limited in scope to the function or block in which they are defined, and their memory is automatically allocated and deallocated when the function is entered and exited.

By default, local variables in C are automatically of auto type, so explicitly using the keyword is redundant. This topic is commonly addressed in C interview questions when discussing storage classes.

32. How to Convert a String to Numbers in C?

In C, strings can be converted to numbers using two common approaches: sscanf() or functions like atoi() and strtol().

  • sscanf(): This function extracts numbers from a string, similar to how scanf() works with standard input. It's flexible and can be used for multiple conversions at once.
  • atoi() or strtol(): atoi() converts a string to an integer, but strtol() offers more control by handling errors and specifying the base for conversion.

33. What Is the Difference Between Source Code and Object Code in C?

Source code and object code represent different stages in the process of creating an executable program in C. This is another frequent question that appears in C interview questions.

Below are the differences between these two types of code:

Aspect Source Code Object Code
Definition Human-readable code written by programmers. Machine-readable code generated by the compiler.
Language Written in high-level programming language (C). Consists of binary or machine code.
Readability Easily readable and understandable by humans. It is not directly readable by humans and requires special tools to interpret.
File extension Typically .c for C files. Usually .o or .obj.
Creation Written manually by programmers. It is generated automatically by the compiler.
Size Generally smaller in file size. Typically larger than the source code.
Compilation need It needs to be compiled to create object code. Result of the compilation process.
Optimization There is no inherent optimization. It may include compiler optimizations.

34. Why Is C Considered a Mid-level Programming Language?

C is considered a mid-level programming language because it incorporates both low-level and high-level language features. On one hand, it provides direct access to hardware and memory through pointers and bitwise operations, resembling assembly language.

On the other hand, C supports abstractions like functions and structures, which are typical of high-level languages, enabling easier application development.

This blend allows C to serve system-level programming while also being powerful enough for application development, a common topic in C interview questions.

35. What Is Common Language Runtime (CLR)?

The Common Language Runtime (CLR) is a fundamental component of the .NET Framework, often discussed in C# and C.NET interview questions. It serves as the runtime environment that executes code and streamlines the development process by providing various essential services.

The CLR manages the execution of .NET applications regardless of the programming language used, ensuring consistent behavior and performance.

Within the CLR framework, the Virtual Execution System (VES) is integrated as part of Microsoft's implementation of the Common Language Infrastructure (CLI). Code executed within the CLR environment is termed Managed Code, which benefits from features such as enhanced security, cross-language integration, and access to a robust set of class libraries.

Essentially, CLR facilitates a managed execution environment for .NET applications, simplifying development and improving application stability.

The C interview questions discussed above are vital for any fresher, as they establish a foundational understanding of key concepts and practices in C programming. Grasping these fundamentals is essential for developing a robust skill set and excelling in interviews.

As you advance, you will learn intermediate-level C interview questions that will further enhance your knowledge and expertise. This progression will enable you to handle more complex topics and scenarios, helping you elevate your skills in the programming field.

Intermediate-Level C Interview Questions

These C interview questions cover advanced topics and are ideal for candidates with some experience in C programming. They are designed to assess your ability to tackle complex scenarios and optimize code, helping you further enhance your skills in the field.

36. What Is Extern Storage Class in C?

The extern storage class in C signifies that a variable is defined outside the block where it is being used. Its value is assigned in one block but can be modified and accessed in others. Essentially, an extern variable acts as a global variable initialized with a valid value at its declaration point, making it accessible throughout the program.

A global variable can be made extern by prefixing the declaration or definition with the extern keyword within any function or block. This approach indicates that no new variable is being created; rather, the existing global variable is being referenced.

The primary purpose of using the extern variables is to facilitate access to variables across different files in a larger program, enhancing modularity and code organization.

37. What Are Near, Far, and Huge Pointers in C?

In the early days of C programming, particularly on 16-bit systems, memory addressing presented unique challenges. To address these limitations, three specialized pointer types were introduced: near, far, and huge pointers.

  • Near Pointers: It is designed to store 16-bit addresses within the current memory segment. Limited to accessing only the first 64 KB of data, they were the most efficient in terms of memory usage and execution speed. Near pointers occupied just 2 bytes of memory.
  • Syntax:

    int near* ptr;
  • Far Pointers: As programs grew more complex and required access to larger memory spaces, far pointers were introduced.
  • These pointers could reach beyond the current segment by storing the address in two 16-bit registers: one for the segment address and another for the offset within that segment.

    Far pointers occupied 4 bytes of memory, double the size of near pointers.

    Syntax:

    int far* ptr;
  • Huge Pointers: Like far pointers, they used two 16-bit registers and occupied 4 bytes. However, huge pointers allowed modification of both the segment and offset parts. This made huge pointers useful for working with large data structures or in situations requiring extensive memory manipulation.
  • Syntax:

    int huge* ptr;

38. What’s the Difference Between Getc(), Getchar(), Getch(), and Getche() Functions?

These functions are used in C programming to read characters from input, but they have distinct behaviors and use cases. Here’s a breakdown of each function:

getc()

  • Usage: Reads a character from a file stream (like stdin or any file).
  • Return Type: Returns the character read as an int, and EOF if the end of the file is reached or an error occurs.
  • Buffering: Buffered input, meaning it reads from a buffer for efficiency.
  • Example:

    FILE *fp = fopen("file.txt", "r"); int ch = getc(fp);

getchar()

  • Usage: Reads a character from standard input (stdin).
  • Return Type: Returns the character read as an int, and EOF on error or end of input.
  • Buffering: Buffered input.
  • Example:

    int ch = getchar();

getch()

  • Usage: Reads a character directly from the keyboard without echoing it to the console. Primarily used in DOS and Windows environments.
  • Return Type: Returns the character read as an int.
  • Buffering: Not buffered; it reads the character immediately.
  • Example:

    int ch = getch();

getche()

  • Usage: Similar to getch(), but it echoes the character to the console as it is read.
  • Return Type: Returns the character read as an int.
  • Buffering: Not buffered, reads and displays the character immediately.
  • Example:

    int ch = getche();

39. What Causes a Segmentation Fault in C and How Can It Be Prevented?

A segmentation fault occurs when a program attempts to access memory that it is not allowed to, leading to an access violation. This generally happens when the program tries to reach beyond the memory boundaries set by the operating system.

Causes of segmentation faults:

  • Dereferencing Null Pointers: Attempting to access or modify data through a pointer that is set to NULL.
  • Accessing Out-of-Bounds Memory: Trying to read or write to an array element outside of its allocated range.
  • Stack Overflow: This occurs when too much stack memory is used, often due to excessive recursion or allocating large local variables.
  • Using Uninitialized Pointers: Accessing pointers that have not been assigned a valid memory address can lead to undefined behavior.
  • Memory Corruption: Modifying memory that has been freed or corrupted can also result in segmentation faults.

How to prevent segmentation faults:

  • Always Initialize Pointers: Ensure all pointers are initialized before use, either to NULL or a valid memory address.
  • Check for NULL Pointers: Before dereferencing a pointer, check if it is NULL to avoid access violations.
  • if (ptr != NULL) { // Safe to dereference ptr }
  • Use Bounds-Checking Functions: Utilize functions that perform bounds checking, such as strncpy() instead of strcpy(), to prevent buffer overflows.
  • Avoid Out-of-Bounds Memory Access: Ensure that all array accesses are within the valid range, especially when dealing with dynamic arrays or pointers.
  • Monitor Stack Usage: Be cautious with recursive functions and large local variables to avoid stack overflow.
  • Utilize Memory Management Tools: Employ tools like Valgrind or AddressSanitizer to detect memory errors and leaks during the development process.

By following these best practices, you can significantly reduce the risk of encountering segmentation faults in your C programs, leading to more stable and reliable code.

Understanding these concepts is crucial for developers, as they frequently appear in C interview questions and reflect a candidate's ability to write safe and effective C code.

...

40. What’s the Difference Between Structs and Unions in C?

Structs and unions are user-defined data types in C, but they significantly differ in how they store and access data.

Below is the comparison table highlighting the differences between structs and unions:

AspectStructsUnions
Memory allocationAllocates memory for all members separately.Allocates memory only for the largest member.
SizeThe sum of sizes of all members plus any padding.Size of the largest member.
Member accessAll members can be accessed simultaneously.Only one member can be accessed at a time.
Memory usageEach member has its own memory space.All members share the same memory space.
Declarationstruct keywordunion keyword
use caseGrouping related data of different types.Saving memory when only one member is used at a time.

41. What Is Recursion in C?

Recursion in C is a technique where a function calls itself to solve a problem by breaking it down into smaller instances. Each call to the function handles a smaller part of the problem, and these solutions are combined to resolve the original issue.

While recursion can make code more concise and easier to understand, it uses a Last In, First Out (LIFO) stack structure, which can increase memory usage.

Properly defining a base case is crucial to prevent infinite loops and stack overflow. This concept frequently appears in C interview questions as it helps demonstrate a candidate's problem-solving skills.

42. What Is the Sleep() Function?

The sleep() function in C allows the current thread to suspend its execution for a specified duration. During this time, other processes on the CPU can continue to run normally, ensuring efficient multitasking. The function takes an integer argument representing the number of seconds to sleep.

Upon completion of the sleep duration, sleep() returns 0, signaling that the thread can resume its operations. This function is useful for implementing delays, pacing execution, or waiting for certain conditions to be met without consuming unnecessary CPU resources.

Understanding the sleep() function is essential for answering interview questions effectively, as it frequently appears in C interview questions. It reflects a candidate's grasp of thread management and execution flow.

43. What Is a Dynamic Data Structure in C?

A Dynamic Data Structure in C is a type of data structure that can adjust its size during runtime. While values in both static and dynamic data structures can be modified, dynamic data structures are specifically designed to allow both the data and the size of the structure to change easily during execution.

The main advantage of dynamic data structures is their ability to resize at runtime without affecting the operations associated with the structure before the size alteration. Understanding dynamic data structures is crucial, as they frequently appear in C interview questions, reflecting a candidate's ability to manage memory effectively.

44. What Are Linked Lists in C?

A linked list is a linear data structure consisting of a sequence of interconnected nodes. In a linked list, nodes are stored randomly in memory, with each node containing two components: data and an address. The final node in the list points to null. After arrays, linked lists are the second most frequently used data structure, where each link connects to another.

Understanding linked lists is essential, as they often appear in C interview questions, showcasing a candidate's knowledge of dynamic memory allocation and data organization.

45. What Are the Issues That Hamper the Efficiency of Sorting a File?

The issues that hamper the efficiency of sorting a file include the time a programmer spends coding a specific sorting algorithm, the machine time required to execute the program, and the amount of memory space the program needs. This question is often highlighted in C interview questions, where understanding the trade-offs of various sorting algorithms can be crucial for optimizing performance.

46. Is Using Exit() the Same As Using Return?

No, using the exit() function is not the same as using the return statement. The exit() function terminates your program entirely, while the return statement transfers control back to the calling function. Specifically, when used in the main() function, the return statement sends control back to the operating system, making it functionally similar to exit() in this context.

Understanding the distinction between these two methods is a common topic in C interview questions, where candidates are often evaluated on their grasp of program termination and control flow.

47. What Is the LRU Caching Scheme? What Data Structures Should Be Used?

The LRU (Least Recently Used) caching scheme manages the pages stored in a cache with a limited size. When the cache reaches its capacity and a new page is requested, the LRU scheme removes the page that was least recently used to make space for the new one.

To implement an LRU Cache, two data structures are commonly used: a queue (implemented as a doubly linked list) and a hash map. Questions about the LRU caching scheme frequently appear in C interview questions, as they reflect a candidate's ability to efficiently manage memory and optimize resource usage.

48. What Is a Heap Data Structure and What Are Its Applications?

A heap is a complete binary tree data structure that maintains the heap property, where each node's value is less than or equal to that of its children. This characteristic allows heaps to efficiently manage dynamic sets of elements.

Applications of Heap Data Structure:

  • Priority Queues: Heaps are commonly used in priority queue implementations, ensuring that elements are accessed based on their priority, such as the highest or lowest value.
  • Graph Algorithms: Heaps play a crucial role in graph algorithms, including Dijkstra’s and Prim’s algorithms, enabling efficient discovery of the shortest paths and construction of minimum spanning trees.

49. Can You Explain the Difference Between a Graph and a Tree Data Structure?

Graphs and trees are fundamental data structures in computer science, each serving distinct purposes in representing relationships and hierarchies. Understanding their differences is essential for efficient data management and algorithm design, often appearing in C interview questions.

Below are the differences between graph and tree data structures:

CharacteristicGraphTree
DefinitionA collection of nodes (vertices) connected by edges.A hierarchical structure with a root node and child nodes.
DirectionIt can be directed or undirected.Always directed (from parent to child).
CyclesIt can contain cycles.It cannot contain cycles.
Root nodeIt may not have a specific root.It has a single root node.
Number of edgesIt can have n(n-1)/2 edges max, where n is the number of nodes.It always has n-1 edges, where n is the number of nodes.
TraversalVarious methods (DFS, BFS, etc.).Specific methods (in-order, pre-order, post-order, level-order).
SubtreesIt's not a relevant concept.It can be divided into subtrees.
ImplementationAdjacency matrix, adjacency list.Array, linked representation.
Application examplesSocial networks, maps, computer networks.File systems, organization charts, and DOM in HTML.

The intermediate-level C interview questions listed above are designed to help both beginners and those with some experience prepare effectively for interviews.

As you advance in your career, you will encounter more challenging questions that are particularly relevant for experienced developers, helping you deepen your understanding and expertise in various C programming concepts.

Note

Download C Interview Questions

Note : We have compiled all C Interview Question for you in a template format. Feel free to comment on it. Check it out now!

Experienced-Level C Interview Questions

Here are some of the most frequently asked coding problems in C interview questions. These challenges span a wide range of topics, from basic operations to more complex tasks, helping you develop strong problem-solving skills.

Additionally, by exploring advanced C interview questions, you will gain a deeper understanding of complex programming concepts and optimization strategies, equipping you to tackle intricate coding scenarios and write efficient, high-performance C applications effectively.

50. How Would You Write a C Program to Check if a Number Is Prime?

To write a C program that checks if a number is prime, you need to implement a function that determines whether the number has any divisors other than 1 and itself. This typically involves iterating from 2 to the square root of the number and checking for divisibility.

#include <stdio.h>
#include <math.h>

int main() {
    int num, i;
    int isPrime = 1;  // Assume the number is prime

    printf("Enter a number: ");
    scanf("%d", &num);

    if (num <= 1) {
        isPrime = 0;
    } else {
      
        for (i = 2; i <= sqrt(num); i++) {
          
            if (num % i == 0) {
                isPrime = 0;
                break;
            }
        }
    }

    if (isPrime) {
        printf("%d is a Prime Number
", num);
    } else {
        printf("%d is not a Prime Number
", num);
    }

    return 0;
}

51. How Would You Swap Two Numbers Without Using a Third Variable in C?

Swapping two numbers without using a third variable in C can be achieved through arithmetic operations or bitwise XOR. This technique not only saves memory but also demonstrates a deeper understanding of variable manipulation in programming.

// C program to swap two numbers using the addition and subtraction method
#include <stdio.h>

int main() {
    int A, B;

    printf("Enter first number: ");
    scanf("%d", &A);
    printf("Enter second number: ");
    scanf("%d", &B);

    A = A + B;
    B = A - B;
    A = A - B;

    printf("After swapping:
");
    printf("First number: %d
", A);
    printf("Second number: %d
", B);

    return 0;
}

52. Can You Write a Program to Print “Hello World” Without Using a Semicolon?

Printing "Hello World" without using a semicolon in C can be accomplished by utilizing alternative control flow statements. This challenge highlights creative problem-solving skills and a deeper understanding of C syntax.

 // C program to print "Hello World" Using 'for' loop 
#include <stdio.h>

int main() {
    for (int i = 0; i < 1; printf("Hello World
")) {
    }
    return 0;
}

53. Write a C Program to Check if a String Is a Palindrome

This program checks whether a given string is a palindrome, meaning it reads the same forwards and backward. By reversing the string and comparing it to the original, the program determines if the input is a palindrome and provides appropriate feedback.

//checks if a given string is a palindrome using a stack data structure.
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define MAX_SIZE 100

typedef struct {
    char elements[MAX_SIZE];
    int index;
} CharStack;

void push(CharStack *stack, char character) {
    stack->elements[++stack->index] = character;
}

char pop(CharStack *stack) {
    return stack->elements[stack->index--];
}

int isPalindrome(const char *str) {
    int length = strlen(str);
    CharStack charStack;
    charStack.index = -1;

        for (int i = 0; i < length; i++) {
        if (isalnum(str[i])) {
            push(&charStack, tolower(str[i]));
        }
    }

       for (int i = 0; i < length; i++) {
        if (isalnum(str[i])) {
            if (tolower(str[i]) != pop(&charStack)) {
                return 0;             }
        }
    }

    return 1; 
}

int main() {
    char input[100];

    printf("Enter a string: ");
    fgets(input, sizeof(input), stdin);
    input[strcspn(input, "
")] = '';

    if (isPalindrome(input)) {
        printf(""%s" is a palindrome.
", input);
    } else {
        printf(""%s" is not a palindrome.
", input);
    }

    return 0;
}

54. Write a Program to Find the Largest Number Among Three Numbers

This program identifies the largest number among three given integers by comparing their values using conditional statements. It efficiently evaluates the inputs and displays the largest number as the output.

#include <stdio.h>

int main() {
    double num1, num2, num3, largest;

    printf("Enter three numbers: ");
    scanf("%lf %lf %lf", &num1, &num2, &num3);

    largest = num1;
    if (num2 > largest) {
        largest = num2;
    }
    if (num3 > largest) {
        largest = num3;
    }

    printf("The largest number is: %.2f
", largest);

    return 0;
}

55. Write a Program to Check Whether a Number Is Prime or Not

This program determines whether a given integer is a prime number by checking for factors other than 1 and itself. It efficiently evaluates divisibility and provides output indicating the primality of the input number.

#include <stdio.h>
#include <stdbool.h>
#include <math.h>

bool isPrime(int n) {
    if (n <= 1) return false;
    if (n <= 3) return true;
    
    if (n % 2 == 0 || n % 3 == 0) return false;
    
    for (int i = 5; i * i <= n; i += 6) {
        if (n % i == 0 || n % (i + 2) == 0) return false;
    }
    
    return true;
}

int main() {
    int num;
    printf("Enter a number: ");
    scanf("%d", &num);
    
    if (isPrime(num)) {
        printf("%d is a prime number.
", num);
    } else {
        printf("%d is not a prime number.
", num);
    }
    
    return 0;
}

56. Write a Program to Calculate the Factorial of a Number

This program calculates the factorial of a given non-negative integer by using either an iterative or recursive approach. It demonstrates the mathematical concept of factorial, which is the product of all positive integers up to the specified number.

#include <stdio.h>

unsigned long long factorial(int n) {
    if (n == 0 || n == 1) {
        return 1;
    }
    return n * factorial(n - 1);
}

int main() {
    int num;
    printf("Enter a non-negative integer: ");
    scanf("%d", &num);
    
    if (num < 0) {
        printf("Factorial is not defined for negative numbers.
");
    } else {
        printf("Factorial of %d is %llu
", num, factorial(num));
    }
    
    return 0;
}

57. Write a Program to Check if a Year Is a Leap Year or Not

This program determines whether a specified year is a leap year based on the rules of the Gregorian calendar. A leap year occurs every four years, except for years divisible by 100, unless they are also divisible by 400.

#include <stdio.h>

int main() {
    int year;
    int isLeapYear = 0;
    
    printf("Enter a year: ");
    scanf("%d", &year);

    if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
        isLeapYear = 1;
    }

    if (isLeapYear) {
        printf("%d is a leap year.
", year);
    } else {
        printf("%d is not a leap year.
", year);
    }

    return 0;
}

58. Write a Program to Reverse a Number

This program reverses a given integer by extracting its digits and rearranging them in the opposite order. It effectively demonstrates the use of loops and arithmetic operations to manipulate numbers in C.

// C program to reverse a number using a while loop.
#include <stdio.h>

int main() {
    int originalNumber, reverse = 0, digit;


    printf("Enter an integer: ");
    scanf("%d", &originalNumber);

    while (originalNumber != 0) {
        digit = originalNumber % 10;             
        reverse = reverse * 10 + digit;          
        originalNumber /= 10;                  
    }

    printf("Reversed number is: %d
", reverse);

    return 0;
}

59. Write a Program to Check if a Number Is Palindrome

To write a C program that checks if a number is a palindrome, you'll need to reverse the digits of the number and compare the reversed number with the original. If both numbers are the same, the number is a palindrome; otherwise, it is not.

// C program to check if a number is palindrome using a while loop.
#include <stdio.h>

int main() {
    int num, originalNum, reversedNum = 0, remainder;



    printf("Enter an integer: ");
    scanf("%d", &num);

    originalNum = num;

    while (num != 0) {
        remainder = num % 10;
        reversedNum = reversedNum * 10 + remainder;
        num /= 10;
    }

    if (originalNum == reversedNum) {
        printf("%d is a palindrome.
", originalNum);
    } else {
        printf("%d is not a palindrome.
", originalNum);
    }

    return 0;
}

60. Write a Program to Find the Area of a Circle

This program calculates the area of a circle based on a user-provided radius using the formula Area=π×radius2\text{Area} = \pi \times \text{radius}^2Area=π×radius2. It showcases the application of mathematical constants and basic input/output operations in C.

#include <stdio.h>
#include <math.h>

int main() {
    float radius, area;

    printf("Enter the radius of the circle: ");
    scanf("%f", &radius);

    area = M_PI * radius * radius;

    printf("The area of the circle is: %.2f
", area);

    return 0;
}

61. Write a Program to Check if a Number Is Even or Odd

This program checks whether a given number is even or odd by utilizing the modulus operator. It provides a simple demonstration of conditional statements and user input handling in C.

 // C program to check if the number is even or odd using a function
#include <stdio.h>

int isEven(int num) {
    return num % 2 == 0;
}

int main() {
    int number;

    printf("Enter an integer: ");
    scanf("%d", &number);

    if (isEven(number)) {
        printf("%d is even.
", number);
    } else {
        printf("%d is odd.
", number);
    }

    return 0;
}

62. Write a Program to Print the Fibonacci Series

This program generates and prints the Fibonacci series, where each number is the sum of the two preceding ones. It demonstrates the use of loops and conditional statements in C to handle sequence generation.

#include <stdio.h>

int main() {
    int n;

    printf("Enter the number of terms: ");
    scanf("%d", &n);

    int fib[n];
    fib[0] = 0;
    fib[1] = 1;

    printf("Fibonacci Series: %d %d ", fib[0], fib[1]);

    for (int i = 2; i < n; i++) {
        fib[i] = fib[i - 1] + fib[i - 2];
        printf("%d ", fib[i]);
    }

    return 0;
}

63. Write a Program to Calculate Compound Interest

This program calculates compound interest based on the principal amount, interest rate, and period. It showcases the use of mathematical formulas and user input in C to derive the final amount after compounding.

#include <stdio.h>
#include <math.h>

int main() {
    double principal, rate, amount;
    int timesCompounded, years;

    printf("Enter principal amount: ");
    scanf("%lf", &principal);
    printf("Enter annual interest rate (in percentage): ");
    scanf("%lf", &rate);
    printf("Enter number of times interest is compounded per year: ");
    scanf("%d", &timesCompounded);
    printf("Enter number of years: ");
    scanf("%d", &years);

    rate = rate / 100;

        amount = principal * pow(1 + rate / timesCompounded, timesCompounded * years);

    printf("Amount after %.2f years is: %.2f
", (double)years, amount);

    return 0;
}

64. Write a Program to Find the GCD (Greatest Common Divisor) of Two Numbers

This program finds the greatest common divisor (GCD) of two numbers using the Euclidean algorithm. It demonstrates the use of loops and conditional statements in C to efficiently compute the GCD.

#include <stdio.h>

int gcd(int a, int b) {
    if (b == 0)
        return a;
    return gcd(b, a % b);
}

int main() {
    int num1, num2;

    printf("Enter two integers: ");
    scanf("%d %d", &num1, &num2);

    printf("GCD of %d and %d is: %d
", num1, num2, gcd(num1, num2));

    return 0;
}

65. Write a Program to Find the LCM (Least Common Multiple) of Two Numbers

This program calculates the least common multiple (LCM) of two numbers based on their greatest common divisor (GCD). It showcases the relationship between GCD and LCM while using basic arithmetic operations in C.

#include <stdio.h>

int gcd(int a, int b) {
    while (b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

int main() {
    int num1, num2, lcm;

    printf("Enter two integers: ");
    scanf("%d %d", &num1, &num2);

    lcm = (num1 * num2) / gcd(num1, num2);

    printf("LCM of %d and %d is %d
", num1, num2, lcm);

    return 0;
}

66. Write a Program to Convert a Binary Number to a Decimal

This program converts a binary number to its decimal equivalent by processing each digit and calculating its value based on its position. It demonstrates the understanding of number systems and the ability to manipulate binary representations in C.

#include <stdio.h>
#include <string.h>
#include <math.h>

int binaryToDecimal(char *binary) {
    int decimal = 0, length = strlen(binary);

    for (int i = 0; i < length; i++) {
        if (binary[i] == '1') {
            decimal += pow(2, length - i - 1);
        }
    }

    return decimal;
}

int main() {
    char binary[32];

    printf("Enter a binary number: ");
    scanf("%s", binary);

    int decimal = binaryToDecimal(binary);

    printf("Decimal equivalent: %d
", decimal);

    return 0;
}

67. Write a Program to Create a Pyramid Pattern

This program generates a pyramid pattern using asterisks, showcasing nested loops to control the number of spaces and symbols on each line. It illustrates fundamental concepts of loops and formatting output in C.

#include <stdio.h>

int main() {
    int n;

    printf("Enter the number of rows: ");
    scanf("%d", &n);

    for (int i = 1; i <= n; i++) {
        for (int j = n; j > i; j--) {
            printf(" ");
        }

        for (int k = 1; k <= (2 * i - 1); k++) {
            printf("*");
        }
        printf("
");
    }

    return 0;
}

68. Write a Program to Reverse an Array

This program demonstrates how to reverse an array by swapping elements from the beginning and the end, moving towards the center. It effectively showcases the use of loops and indexing in C for array manipulation.

#include <stdio.h>

int main() {
    int arr[100];
    int n, start, end, temp;


    printf("Enter the number of elements: ");
    scanf("%d", &n);

    printf("Enter the elements of the array:
");
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    start = 0;
    end = n - 1;
    while (start < end) {
        temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }

    printf("Reversed array:
");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("
");

    return 0;
}

69. Write a Program to Find the Maximum and Minimum Elements in an Array

This program identifies the maximum and minimum elements within an array by iterating through the elements and comparing their values. It highlights the efficiency of linear search algorithms for data retrieval in C programming.

#include <stdio.h>

int main() {
    int arr[100];
    int n, max, min;

    printf("Enter the number of elements: ");
    scanf("%d", &n);

    printf("Enter the elements of the array:
");
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    max = arr[0];
    min = arr[0];

    for (int i = 1; i < n; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }

    for (int i = 1; i < n; i++) {
        if (arr[i] < min) {
            min = arr[i];
        }
    }

    printf("Maximum element: %d
", max);
    printf("Minimum element: %d
", min);

    return 0;
}

70. Write a Program to Implement Linear Search in an Array

This program demonstrates the implementation of a linear search algorithm, which sequentially checks each element in an array to find a specified value. It showcases the fundamental approach to searching in C programming, emphasizing its simplicity and directness.

#include <stdio.h>

int linearSearch(int arr[], int n, int target) {
    for (int i = 0; i < n; i++) {
        if (arr[i] == target) {
            return i; 
        }
    }
    return -1;
}

int main() {
    int arr[100];
    int n, target, result;

    printf("Enter the number of elements: ");
    scanf("%d", &n);

    printf("Enter the elements of the array:
");
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    printf("Enter the value to search for: ");
    scanf("%d", &target);

    result = linearSearch(arr, n, target);

    if (result != -1) {
        printf("Value %d found at index %d.
", target, result);
    } else {
        printf("Value %d not found in the array.
", target);
    }

    return 0;
}

71. Write a Program to Implement Binary Search in a Sorted Array

This program illustrates the binary search algorithm, an efficient method for finding a target value in a sorted array by repeatedly dividing the search interval in half. It highlights the advantages of binary search over linear search in terms of time complexity, making it a fundamental concept in C programming.

#include <stdio.h>

int binarySearch(int arr[], int n, int target) {
    int low = 0;
    int high = n - 1;
    int mid;

    while (low <= high) {
        mid = low + (high - low) / 2;

        if (arr[mid] == target) {
            return mid;
        } else if (arr[mid] < target) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }
    return -1; 
}

int main() {
    int arr[100];
    int n, target, result;

       printf("Enter the number of elements: ");
    scanf("%d", &n);

      printf("Enter the elements of the sorted array:
");
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

      printf("Enter the value to search for: ");
    scanf("%d", &target);

    result = binarySearch(arr, n, target);

    if (result != -1) {
        printf("Value %d found at index %d.
", target, result);
    } else {
        printf("Value %d not found in the array.
", target);
    }

    return 0;
}

72. Write a Program to Sort an Array Using Bubble Sort

This program demonstrates the bubble sort algorithm, a straightforward sorting technique that repeatedly steps through the array, compares adjacent elements, and swaps them if they are in the wrong order.

It emphasizes the simplicity of bubble sort, making it a common introductory example for understanding sorting algorithms in C programming.

#include <stdio.h>

void bubbleSort(int arr[], int n) {
    int temp;
    int swapped;
    
    for (int i = 0; i < n - 1; i++) {
        swapped = 0;

        for (int j = 0; j < n - i - 1; j++) {
                        if (arr[j] > arr[j + 1]) {
                                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
                swapped = 1;             }
        }
        
               if (swapped == 0) {
            break;
        }
    }
}

int main() {
    int arr[100];
    int n;


    printf("Enter the number of elements: ");
    scanf("%d", &n);

    printf("Enter the elements of the array:
");
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    bubbleSort(arr, n);

    printf("Sorted array:
");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("
");

    return 0;
}

73. Write a Program to Implement the Kadane’s Algorithm (Maximum Subarray Sum)

This program implements Kadane's Algorithm, a powerful technique used to find the maximum sum of a contiguous subarray within a one-dimensional array.

It efficiently computes the result in linear time, making it a popular choice for solving the maximum subarray problem in competitive programming and algorithm design.

#include <stdio.h>

int kadane(int arr[], int n) {
    int current_max = arr[0];
    int global_max = arr[0];

    for (int i = 1; i < n; i++) {
  
        current_max = (arr[i] > current_max + arr[i]) ? arr[i] : current_max + arr[i];

        if (current_max > global_max) {
            global_max = current_max;
        }
    }

    return global_max;
}

int main() {
    int arr[100];
    int n;


    printf("Enter the number of elements: ");
    scanf("%d", &n);

    printf("Enter the elements of the array:
");
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    int max_sum = kadane(arr, n);

    printf("Maximum subarray sum is: %d
", max_sum);

    return 0;
}

74.Write a Program to Rotate a Matrix by 90 Degrees Clockwise

This program demonstrates how to rotate a square matrix by 90 degrees clockwise, transforming the position of each element in the matrix. This operation is commonly used in image processing and computer graphics to manipulate and orient data efficiently.

#include <stdio.h>

void printMatrix(int matrix[][100], int n) {
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("
");
    }
}

void rotateMatrix(int matrix[][100], int n) {
    for (int i = 0; i < n; i++) {
        for (int j = i; j < n; j++) {
            int temp = matrix[i][j];
            matrix[i][j] = matrix[j][i];
            matrix[j][i] = temp;
        }
    }
    
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n / 2; j++) {
            int temp = matrix[i][j];
            matrix[i][j] = matrix[i][n - j - 1];
            matrix[i][n - j - 1] = temp;
        }
    }
}

int main() {
    int matrix[100][100];
    int n;

    printf("Enter the size of the matrix (n x n): ");
    scanf("%d", &n);

    printf("Enter the elements of the matrix:
");
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            scanf("%d", &matrix[i][j]);
        }
    }

    rotateMatrix(matrix, n);

    printf("Matrix after rotation:
");
    printMatrix(matrix, n);

    return 0;
}

75. Write a Program for Spiral Traversal of a Matrix

This program illustrates how to perform a spiral traversal of a matrix, visiting each element in a specific order, starting from the top-left corner and moving clockwise around the matrix. Spiral traversal is useful in various applications, such as data visualization and matrix manipulation.

#include <stdio.h>

void spiralTraversal(int matrix[][100], int rows, int cols) {
    int top = 0, bottom = rows - 1;
    int left = 0, right = cols - 1;
    
    while (top <= bottom && left <= right) {
        for (int i = left; i <= right; i++) {
            printf("%d ", matrix[top][i]);
        }
        top++;

        for (int i = top; i <= bottom; i++) {
            printf("%d ", matrix[i][right]);
        }
        right--;

        if (top <= bottom) {
            for (int i = right; i >= left; i--) {
                printf("%d ", matrix[bottom][i]);
            }
            bottom--;
        }

      
        if (left <= right) {
            for (int i = bottom; i >= top; i--) {
                printf("%d ", matrix[i][left]);
            }
            left++;
        }
    }
}

int main() {
    int matrix[100][100];
    int rows, cols;

    printf("Enter the number of rows and columns: ");
    scanf("%d %d", &rows, &cols);

    printf("Enter the elements of the matrix:
");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            scanf("%d", &matrix[i][j]);
        }
    }

    printf("Spiral traversal of the matrix:
");
    spiralTraversal(matrix, rows, cols);

    return 0;
}

76. Write a Program to Print All Permutations of a String in Lexicographical Order

This program generates all permutations of a given string and displays them in lexicographical order. Printing permutations is a common problem in combinatorial algorithms, showcasing the importance of recursion and backtracking in generating combinations of characters.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int compare(const void *a, const void *b) {
    return strcmp(*(const char **)a, *(const char **)b);
}

void generatePermutations(char *str, int start, int end, char **permutations, int *index) {
    if (start == end) {
        permutations[*index] = strdup(str);
        (*index)++;
    } else {
        for (int i = start; i <= end; i++) {
  
            char temp = str[start];
            str[start] = str[i];
            str[i] = temp;

      
            generatePermutations(str, start + 1, end, permutations, index);

            temp = str[start];
            str[start] = str[i];
            str[i] = temp;
        }
    }
}

int main() {
    char str[100];
    int n;

    printf("Enter the string: ");
    scanf("%s", str);

    n = strlen(str);
    

    char **permutations = (char **)malloc(sizeof(char *) * 1000000);
    int index = 0;

    generatePermutations(str, 0, n - 1, permutations, &index);

    qsort(permutations, index, sizeof(char *), compare);

    printf("Permutations in lexicographical order:
");
    for (int i = 0; i < index; i++) {
        printf("%s
", permutations[i]);
        free(permutations[i]); 
    }

    free(permutations);

    return 0;
}

77. Write a Program to Implement Merge Sort

This program implements the Merge Sort algorithm, a popular divide-and-conquer technique for sorting arrays. Merge Sort efficiently divides the array into smaller subarrays, sorts them, and then merges them back together, ensuring a time complexity of O(n log n).

#include <stdio.h>
#include <stdlib.h>

void merge(int arr[], int left, int mid, int right) {
    int n1 = mid - left + 1;
    int n2 = right - mid;

 
    int *L = (int *)malloc(n1 * sizeof(int));
    int *R = (int *)malloc(n2 * sizeof(int));

   
    for (int i = 0; i < n1; i++)
        L[i] = arr[left + i];
    for (int j = 0; j < n2; j++)
        R[j] = arr[mid + 1 + j];

  
    int i = 0; 
    int j = 0;
    int k = left;
    while (i < n1 && j < n2) {
        if (L[i] <= R[j]) {
            arr[k] = L[i];
            i++;
        } else {
            arr[k] = R[j];
            j++;
        }
        k++;
    }

    while (i < n1) {
        arr[k] = L[i];
        i++;
        k++;
    }

    while (j < n2) {
        arr[k] = R[j];
        j++;
        k++;
    }

    free(L);
    free(R);
}

void mergeSort(int arr[], int left, int right) {
    if (left < right) {
        int mid = left + (right - left) / 2;

        mergeSort(arr, left, mid);
        mergeSort(arr, mid + 1, right);

        merge(arr, left, mid, right);
    }
}

void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++)
        printf("%d ", arr[i]);
    printf("
");
}

int main() {
    int arr[100];
    int n;

    printf("Enter the number of elements: ");
    scanf("%d", &n);

    printf("Enter the elements of the array:
");
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    mergeSort(arr, 0, n - 1);

    printf("Sorted array:
");
    printArray(arr, n);

    return 0;
}

78. Write a Program to Implement Quick Sort

This program implements the Quick Sort algorithm, which is an efficient sorting technique based on the divide-and-conquer principle. Quick Sort selects a pivot element, partitions the array into elements less than and greater than the pivot, and recursively sorts the subarrays, achieving an average time complexity of O(n log n).

#include <stdio.h>

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int partition(int arr[], int low, int high) {
    int pivot = arr[high]; 
    int i = (low - 1); 

    for (int j = low; j < high; j++) {
        if (arr[j] <= pivot) {
            i++;
            swap(&arr[i], &arr[j]);
        }
    }
    swap(&arr[i + 1], &arr[high]);
    return (i + 1);
}

void quickSort(int arr[], int low, int high) {
    if (low < high) {
        int pi = partition(arr, low, high);

      
        quickSort(arr, low, pi - 1);
        quickSort(arr, pi + 1, high);
    }
}

void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++)
        printf("%d ", arr[i]);
    printf("
");
}

int main() {
    int arr[100];
    int n;

    printf("Enter the number of elements: ");
    scanf("%d", &n);

    printf("Enter the elements of the array:
");
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    quickSort(arr, 0, n - 1);

    printf("Sorted array:
");
    printArray(arr, n);

    return 0;
}

79. Write a Program to Reverse a Linked List Iteratively

This program reverses a linked list iteratively by manipulating the pointers of each node. By maintaining references to the previous and current nodes, it efficiently reverses the direction of the list in a single pass, achieving a time complexity of O(n).

#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* next;
};

struct Node* createNode(int data) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

void printList(struct Node* head) {
    struct Node* temp = head;
    while (temp != NULL) {
        printf("%d -> ", temp->data);
        temp = temp->next;
    }
    printf("NULL
");
}

void reverseList(struct Node** headRef) {
    struct Node* prev = NULL;
    struct Node* current = *headRef;
    struct Node* next = NULL;

    while (current != NULL) {
        next = current->next; 
        current->next = prev;  
        prev = current;       
        current = next;
    }

    *headRef = prev; 
}

int main() {
    struct Node* head = NULL;
    struct Node* second = NULL;
    struct Node* third = NULL;

    head = createNode(1);
    second = createNode(2);
    third = createNode(3);

    head->next = second;
    second->next = third;

    printf("Original list:
");
    printList(head);

    reverseList(&head);


    printf("Reversed list:
");
    printList(head);

  
    return 0;
}

80. Write a Program to Detect a Cycle in a Linked List

This program detects a cycle in a linked list using Floyd's Tortoise and Hare algorithm, which employs two pointers moving at different speeds. If the fast pointer meets the slow pointer, a cycle is present, allowing for efficient detection with O(n) time complexity and O(1) space complexity.

#include <stdio.h>
#include <stdlib.h>


struct Node {
    int data;
    struct Node* next;
};


struct Node* createNode(int data) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

int detectCycle(struct Node* head) {
    if (head == NULL) return 0;

    struct Node* slow = head;
    struct Node* fast = head;

    while (fast != NULL && fast->next != NULL) {
        slow = slow->next;            
        fast = fast->next->next;    

        if (slow == fast) {
            return 1;
        }
    }

    return 0;
}

void printList(struct Node* head) {
    struct Node* temp = head;
    while (temp != NULL) {
        printf("%d -> ", temp->data);
        temp = temp->next;
    }
    printf("NULL
");
}

int main() {
    struct Node* head = NULL;
    struct Node* second = NULL;
    struct Node* third = NULL;
    struct Node* fourth = NULL;

    head = createNode(1);
    second = createNode(2);
    third = createNode(3);
    fourth = createNode(4);


    head->next = second;
    second->next = third;
    third->next = fourth;
    fourth->next = second; // Create a cycle here (4 -> 2)


    if (detectCycle(head)) {
        printf("Cycle detected in the linked list.
");
    } else {
        printf("No cycle detected in the linked list.
");
    }

    return 0;
}

81. Write a Program to Implement a Stack Using Arrays

This program demonstrates how to implement a stack data structure using arrays, allowing for operations like push, pop, and peek. By maintaining an index to track the top element, the stack ensures Last In, First Out (LIFO) behavior for efficient data management.

#include <stdio.h>
#include <stdlib.h>
#include <limits.h> 

#define MAX 100 

typedef struct {
    int top;       
    int items[MAX];
} Stack;

void initStack(Stack* s) {
    s->top = -1;
}

int isFull(Stack* s) {
    return s->top == MAX - 1;
}

int isEmpty(Stack* s) {
    return s->top == -1;
}

void push(Stack* s, int value) {
    if (isFull(s)) {
        printf("Stack overflow. Cannot push %d.
", value);
        return;
    }
    s->items[++(s->top)] = value;
    printf("%d pushed to stack.
", value);
}

int pop(Stack* s) {
    if (isEmpty(s)) {
        printf("Stack underflow. Cannot pop.
");
        return INT_MIN;
    }
    return s->items[(s->top)--];
}

int peek(Stack* s) {
    if (isEmpty(s)) {
        printf("Stack is empty.
");
        return INT_MIN;
    }
    return s->items[s->top];
}

void display(Stack* s) {
    if (isEmpty(s)) {
        printf("Stack is empty.
");
        return;
    }
    printf("Stack elements are:
");
    for (int i = s->top; i >= 0; i--) {
        printf("%d
", s->items[i]);
    }
}

int main() {
    Stack stack; 
    initStack(&stack); 


    push(&stack, 10);
    push(&stack, 20);
    push(&stack, 30);

  
    display(&stack);

    printf("Top element is %d
", peek(&stack));

    printf("%d popped from stack.
", pop(&stack));
    printf("%d popped from stack.
", pop(&stack));

    display(&stack);

    return 0;
}

82. Write a Program to Implement a Queue Using Linked List

This program illustrates how to implement a queue data structure using a linked list, enabling efficient enqueue and dequeue operations. Maintaining pointers for both the front and rear of the queue ensures First In, First Out (FIFO) behavior for managing data.

#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* next;
};

typedef struct {
    struct Node* front; 
    struct Node* rear;  
} Queue;

struct Node* createNode(int data) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}


void initQueue(Queue* q) {
    q->front = q->rear = NULL;
}


int isEmpty(Queue* q) {
    return q->front == NULL;
}


void enqueue(Queue* q, int value) {
    struct Node* newNode = createNode(value);
    if (isEmpty(q)) {
        q->front = q->rear = newNode;
    } else {
        q->rear->next = newNode;
        q->rear = newNode;
    }
    printf("%d enqueued to queue.
", value);
}


int dequeue(Queue* q) {
    if (isEmpty(q)) {
        printf("Queue underflow. Cannot dequeue.
");
        return -1;
    }
    struct Node* temp = q->front;
    int value = temp->data;
    q->front = q->front->next;
    if (q->front == NULL) {
        q->rear = NULL; 
    }
    free(temp);
    return value;
}

int peek(Queue* q) {
    if (isEmpty(q)) {
        printf("Queue is empty.
");
        return -1;
    }
    return q->front->data;
}


void display(Queue* q) {
    if (isEmpty(q)) {
        printf("Queue is empty.
");
        return;
    }
    struct Node* temp = q->front;
    printf("Queue elements are:
");
    while (temp != NULL) {
        printf("%d -> ", temp->data);
        temp = temp->next;
    }
    printf("NULL
");
}

int main() {
    Queue queue;  
    initQueue(&queue); 

    enqueue(&queue, 10);
    enqueue(&queue, 20);
    enqueue(&queue, 30);

    display(&queue);

    printf("Front element is %d
", peek(&queue));

    printf("%d dequeued from queue.
", dequeue(&queue));
    printf("%d dequeued from queue.
", dequeue(&queue));

    display(&queue);

    return 0;
}
...

Conclusion

In conclusion, mastering the 80+ C interview questions and answers outlined in this guide will significantly enhance your understanding of the C programming language. These questions cover various topics, from fundamental concepts to advanced techniques, ensuring you're well-prepared for any interview scenario. By studying and practicing these questions, you'll build the confidence and expertise needed to excel in technical interviews and advance your programming career in 2024.

Note

Download C Interview Questions

Note : We have compiled all C Interview Question for you in a template format. Feel free to comment on it. Check it out now!

Frequently asked questions

  • General ...
Why is C known as a mother language?
C is often referred to as a mother language because:
  • It has significantly influenced many modern programming languages.
  • Can share the workload to map elements.
  • It's widely used as a basis for developing other languages (e.g., C++, Java, Python).
  • Many operating systems and compilers are written in C.
How to learn C?
To learn C effectively:
  • Start with basic concepts.
  • Learn about functions and arrays.
  • Study pointers and memory management.
  • Practice with small projects and coding exercises.
  • Read C programming books or follow online tutorials.
How do you call a function in C?
To call a function in C:
  • Use the function name.
  • Follow it with parentheses.
  • Include any required arguments inside the parentheses.
What is the difference between '++i' and 'i++' in C?
The difference lies in when the increment occurs:
  • "++i" (pre-increment): The variable is incremented before its value is used in the expression.
  • "i++" (post-increment): The variable's current value is used in the expression, then it's incremented.

Did you find this page helpful?

Helpful

NotHelpful

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud