C Interview Questions and Answers
-
What is C?
- Answer: C is a general-purpose, procedural programming language. It's known for its efficiency and is widely used for system programming, embedded systems, and high-performance computing.
-
What are the basic data types in C?
- Answer: `int`, `float`, `char`, `double`, `void` are the basic data types. `int` stores integers, `float` and `double` store floating-point numbers (with differing precision), `char` stores characters, and `void` represents the absence of a type.
-
Explain the difference between `int` and `float`?
- Answer: `int` stores whole numbers (integers), while `float` stores numbers with decimal points (floating-point numbers). `float` uses less memory than `double` but has lower precision.
-
What is a pointer in C?
- Answer: A pointer is a variable that holds the memory address of another variable. It's declared using the `*` operator (e.g., `int *ptr;`).
-
How do you declare and initialize a pointer?
- Answer: `int x = 10; int *ptr = &x;` declares an integer `x`, a pointer `ptr` to an integer, and then assigns the memory address of `x` to `ptr` using the address-of operator `&`.
-
What is the difference between `malloc()` and `calloc()`?
- Answer: Both allocate memory dynamically. `malloc()` allocates a single block of memory of specified size, uninitialized. `calloc()` allocates multiple blocks of memory, each of specified size, and initializes them to zero.
-
What is `free()` and why is it important?
- Answer: `free()` releases dynamically allocated memory. It's crucial to prevent memory leaks, which occur when allocated memory is not freed, leading to program instability or crashes.
-
Explain the concept of a structure in C.
- Answer: A structure is a user-defined data type that groups together variables of different data types under a single name. It's useful for organizing related data.
-
What is a union in C?
- Answer: A union is similar to a structure, but all members share the same memory location. Only one member can hold a value at a time. It's used to conserve memory when different data types need to occupy the same space.
-
What are functions in C?
- Answer: Functions are blocks of code that perform specific tasks. They promote modularity and code reusability.
-
Explain the difference between call by value and call by reference.
- Answer: Call by value passes a copy of the argument's value to the function. Changes within the function don't affect the original variable. Call by reference passes the memory address of the argument. Changes within the function affect the original variable.
-
What are preprocessor directives in C?
- Answer: Preprocessor directives are commands that are processed before the actual compilation. Examples include `#include`, `#define`, `#ifdef`, etc. They modify the source code before compilation.
-
What is the purpose of `#include`?
- Answer: `#include` inserts the contents of a header file into the source code. Header files contain function declarations, macro definitions, and other declarations needed by the program.
-
What is a header file? Give examples.
- Answer: A header file contains function declarations, macro definitions, and other declarations needed by the program. Examples include `stdio.h`, `stdlib.h`, `string.h`.
-
What is the difference between `static` and `global` variables?
- Answer: `static` variables have local scope (within the function or block where they're declared) but retain their value between function calls. `global` variables have global scope (accessible throughout the program).
-
What is an array in C?
- Answer: An array is a contiguous block of memory that stores elements of the same data type. Elements are accessed using their index (starting from 0).
-
What is a string in C?
- Answer: A string in C is a null-terminated sequence of characters (a character array ending with '\0').
-
How do you copy a string in C?
- Answer: Using `strcpy()` from `string.h` (beware of buffer overflows!), or manually copying character by character until the null terminator is encountered.
-
What is a two-dimensional array?
- Answer: A two-dimensional array is an array of arrays, representing a table or matrix of elements.
-
Explain the concept of recursion.
- Answer: Recursion is a programming technique where a function calls itself. It's used to solve problems that can be broken down into smaller, self-similar subproblems.
-
What is a linked list?
- Answer: A linked list is a linear data structure where elements are not stored contiguously in memory. Each element (node) points to the next element in the sequence.
-
What are the different types of linked lists?
- Answer: Singly linked list, doubly linked list, circular linked list.
-
What is a stack?
- Answer: A stack is a LIFO (Last-In, First-Out) data structure. Elements are added (pushed) and removed (popped) from the top.
-
What is a queue?
- Answer: A queue is a FIFO (First-In, First-Out) data structure. Elements are added (enqueued) at the rear and removed (dequeued) from the front.
-
What is a binary tree?
- Answer: A binary tree is a hierarchical data structure where each node has at most two children (left and right).
-
What is a binary search tree (BST)?
- Answer: A BST is a binary tree where the value of each node is greater than or equal to the values in its left subtree and less than the values in its right subtree. This allows for efficient searching.
-
What is a graph?
- Answer: A graph is a non-linear data structure consisting of nodes (vertices) and edges connecting them.
-
What are different types of graph traversal algorithms?
- Answer: Breadth-First Search (BFS) and Depth-First Search (DFS).
-
Explain the concept of sorting algorithms.
- Answer: Sorting algorithms arrange elements of a data structure (usually an array) in a specific order (ascending or descending).
-
Name some common sorting algorithms.
- Answer: Bubble sort, insertion sort, selection sort, merge sort, quicksort, heapsort.
-
What is the time complexity of quicksort?
- Answer: Average case: O(n log n), Worst case: O(n^2)
-
What is the time complexity of merge sort?
- Answer: O(n log n) in all cases.
-
What is a file in C?
- Answer: A file is a persistent storage area on a disk or other storage device.
-
How do you open a file in C?
- Answer: Using `fopen()` function.
-
How do you read from a file in C?
- Answer: Using functions like `fgetc()`, `fgets()`, `fscanf()`.
-
How do you write to a file in C?
- Answer: Using functions like `fputc()`, `fputs()`, `fprintf()`.
-
How do you close a file in C?
- Answer: Using `fclose()`.
-
What are command-line arguments in C?
- Answer: Arguments passed to a program when it's executed from the command line.
-
How do you access command-line arguments in C?
- Answer: Through the `main()` function's arguments: `int main(int argc, char *argv[])`.
-
What is a dynamic memory allocation?
- Answer: Allocating memory during runtime using functions like `malloc()`, `calloc()`, `realloc()`, etc.
-
What is a memory leak?
- Answer: A memory leak occurs when dynamically allocated memory is not freed using `free()`, leading to wasted memory.
-
What is a dangling pointer?
- Answer: A dangling pointer points to a memory location that has been freed or is no longer valid.
-
Explain the difference between `const int *ptr` and `int * const ptr`.
- Answer: `const int *ptr`: The value pointed to by `ptr` is constant. `int * const ptr`: The pointer `ptr` itself is constant (cannot be reassigned).
-
What is the role of a makefile?
- Answer: A makefile automates the compilation process, specifying dependencies between source files and target executables.
-
What is the difference between `gets()` and `fgets()`?
- Answer: `gets()` is unsafe and prone to buffer overflows; it's been removed from the standard library. `fgets()` is safer as it allows specifying a maximum number of characters to read.
-
What are enumerated types (`enum`) in C?
- Answer: Enumerated types define a set of named integer constants, improving code readability and maintainability.
-
What is type casting in C?
- Answer: Explicitly converting a variable from one data type to another. (e.g., `(int)3.14` converts the `float` 3.14 to an `int` 3).
-
What is the purpose of the `sizeof` operator?
- Answer: Returns the size (in bytes) of a data type or variable.
-
What is the difference between `printf()` and `sprintf()`?
- Answer: `printf()` prints formatted output to the console. `sprintf()` prints formatted output to a string.
-
What is the purpose of `void` pointers?
- Answer: `void` pointers can hold the address of any data type but cannot be dereferenced directly; they must be cast to a specific pointer type before use.
-
What is a bit field in C?
- Answer: A bit field allows packing multiple variables into a single integer, conserving memory.
-
Explain the concept of function overloading in C.
- Answer: C does not support function overloading. You cannot have multiple functions with the same name, even if they have different parameter types.
-
What is operator precedence in C?
- Answer: The order in which operators are evaluated in an expression. Operators with higher precedence are evaluated before those with lower precedence.
-
Explain the concept of operator associativity in C.
- Answer: The order in which operators of the same precedence are evaluated (left-to-right or right-to-left).
-
What are the different storage classes in C?
- Answer: `auto`, `register`, `static`, `extern`.
-
What is the difference between `break` and `continue` statements?
- Answer: `break` exits a loop entirely. `continue` skips the current iteration and proceeds to the next iteration.
-
What is a macro in C?
- Answer: A macro is a preprocessor directive that replaces a symbolic name with a piece of code. It's defined using `#define`.
-
What are the advantages and disadvantages of using macros?
- Answer: Advantages: Improved code readability, avoids function call overhead. Disadvantages: Can lead to unexpected behavior if not used carefully, no type checking.
-
How do you handle errors in C?
- Answer: Using error codes returned by functions (e.g., `fopen()`), checking return values, using `perror()` to print error messages.
-
What are the differences between C and C++?
- Answer: C is procedural, C++ is object-oriented. C++ supports features like classes, objects, inheritance, polymorphism, that are not present in C.
-
What is the role of the compiler in C programming?
- Answer: The compiler translates the C source code into assembly language and then into machine code (executable).
-
What is a linker in C programming?
- Answer: The linker combines object files (generated by the compiler) and libraries into a single executable file.
-
What are libraries in C programming?
- Answer: Collections of pre-compiled functions and data that can be linked to a program to add functionality.
-
How do you handle command-line arguments in C?
- Answer: The `main` function takes two arguments: `argc` (argument count) and `argv` (argument vector), an array of strings representing the command-line arguments.
-
Explain the concept of modular programming in C.
- Answer: Breaking down a large program into smaller, independent modules (functions) to improve code organization, reusability, and maintainability.
-
What is the difference between local and global variables?
- Answer: Local variables are declared within a function and are only accessible within that function. Global variables are declared outside any function and are accessible from anywhere in the program.
-
How to debug a C program?
- Answer: Using a debugger (like GDB), print statements, code inspection, and testing.
-
What is the difference between `while` and `do-while` loops?
- Answer: A `while` loop checks the condition *before* each iteration. A `do-while` loop executes the body at least once, then checks the condition.
-
What is the role of the `return` statement in a C function?
- Answer: It specifies the value to be returned by the function. If the function's return type is `void`, a `return` statement is optional.
-
What are the different ways to pass arguments to a C function?
- Answer: Pass by value (a copy is passed), pass by reference (the address is passed), pass by pointer.
-
What is the significance of the null character ('\0') in C strings?
- Answer: It marks the end of the string, allowing functions to know where the string ends.
-
How do you convert a character to its ASCII value in C?
- Answer: A character variable directly holds its ASCII value. You can assign it to an integer variable to see the numerical value.
-
Explain the concept of "Segmentation Fault" in C.
- Answer: A segmentation fault occurs when a program attempts to access a memory location it doesn't have permission to access, often due to dereferencing a null pointer or accessing memory beyond array bounds.
-
What are some common causes of runtime errors in C?
- Answer: Memory leaks, dangling pointers, buffer overflows, division by zero, accessing invalid memory locations.
-
How to prevent buffer overflows in C?
- Answer: Use functions like `fgets()` instead of `gets()`, always check array bounds before accessing elements, use safe string manipulation libraries.
-
How to use `switch` statement in C?
- Answer: The `switch` statement selects a block of code to execute based on the value of an integer expression. `case` labels identify the blocks of code.
-
Explain the concept of a “for” loop in C.
- Answer: A `for` loop is used to iterate a specific number of times. It has three parts: initialization, condition, and increment/decrement.
-
What is the difference between `==` and `=` in C?
- Answer: `==` is the equality operator (comparison). `=` is the assignment operator.
-
How to check if a file exists in C?
- Answer: Use `fopen()` to try opening the file in read mode. If it returns NULL, the file doesn't exist.
-
Explain the concept of a "header file" in C and its importance.
- Answer: Header files (.h) contain function declarations, macro definitions, and other declarations. They allow you to reuse code and define interfaces for different modules.
-
What is the significance of the `main` function in a C program?
- Answer: It's the entry point of the program; execution begins here.
Thank you for reading our blog post on 'C Interview Questions and Answers'.We hope you found it informative and useful.Stay tuned for more insightful content!