Basic Dynamic Programming Interview Questions and Answers

1. What is C language ?

C is a general-purpose, procedural programming language developed by Dennis Ritchie at Bell Labs in the early 1970s. It is widely used for system programming, developing operating systems, and embedded programming. C provides low-level memory access, a simple set of keywords, and a structured approach. It is known for its efficiency and portability, making it popular for software development. Many modern languages like C++, Java, and Python are influenced by C.

2. What are the key features of C ?

C language has several key features that make it powerful and flexible. It supports structured programming, which helps in writing clear and maintainable code. C allows direct memory manipulation using pointers, which is useful for system programming. It has a rich set of built-in operators and library functions. C is portable, meaning programs written in C can run on different platforms with minimal modifications. It provides dynamic memory allocation using functions like malloc() and free().

3. What is the difference between printf() and scanf()?

printf() and scanf() are standard input-output functions in C. printf() is used to display output on the screen, while scanf() is used to take user input. printf() uses format specifiers like %d, %s, and %f to print different data types. scanf() also uses format specifiers but requires the use of the & (address-of) operator with variables to store input. While printf() only writes output, scanf() modifies variables based on user input.

4. What are pointers in C?

A pointer is a variable that stores the memory address of another variable. It allows dynamic memory allocation, efficient array handling, and function arguments by reference. Pointers improve program performance by reducing memory access time. They are declared using the * (asterisk) symbol, e.g., int *ptr;. Common pointer operations include dereferencing (*ptr), address-of (&var), and pointer arithmetic. Pointers are widely used in data structures like linked lists and trees.

5. What is the difference between call by value and call by reference?

In call by value, a copy of the actual parameter is passed to the function, and modifications inside the function do not affect the original variable. In call by reference, the memory address of the actual parameter is passed, allowing the function to modify the original variable. Call by value ensures data security as changes remain local to the function. Call by reference is more efficient for large data structures as it avoids copying large amounts of data. Pointers are commonly used for call by reference in C.

6. What is a static variable in C?

A static variable in C retains its value across multiple function calls. It is declared using the static keyword. Unlike automatic (local) variables, which are reinitialized every time a function is called, static variables maintain their previous value. Static variables have a default value of zero if not initialized. They are stored in the data segment instead of the stack, reducing memory usage and improving performance. Static variables help in maintaining state information in recursive or iterative processes.

7. What is the difference between an array and a linked list in C?

An array is a fixed-size, contiguous memory block that stores elements of the same type, while a linked list is a dynamic data structure consisting of nodes linked using pointers. Arrays allow fast access using index-based addressing, whereas linked lists provide efficient insertion and deletion at any position. Arrays require predefined size, but linked lists can grow dynamically. Arrays use less memory overhead compared to linked lists, which require extra pointers for linking nodes. Linked lists are useful when frequent insertions and deletions are required.

8. What are the different storage classes in C?

C has four primary storage classes: auto, static, extern, and register. Auto (automatic) is the default storage class for local variables, stored in the stack. Static variables retain their values across function calls. Extern variables are declared in one file and used in another, allowing global access. Register storage class suggests storing variables in CPU registers for faster access. Each storage class defines variable scope, lifetime, and linkage behavior.

9. What is recursion in C?

Recursion is a programming technique where a function calls itself directly or indirectly. It is used to solve problems that can be broken down into smaller subproblems of the same type. Each recursive function must have a base condition to stop infinite calls. Recursion is commonly used in algorithms like factorial calculation, Fibonacci series, and tree traversals. However, recursion can lead to high memory usage due to function call stack growth.

10. What is the use of malloc() and free() in C?

malloc() is a function in C used to allocate memory dynamically during runtime. It returns a pointer to the allocated memory block. If memory allocation fails, malloc() returns NULL. free() is used to deallocate memory previously allocated by malloc(), preventing memory leaks. Dynamic memory allocation helps in managing variable-sized data structures like linked lists and trees. Using free() ensures efficient memory management in C programs.

11. What is a structure in C?

A structure in C is a user-defined data type that groups related variables of different data types into a single unit. It is defined using the struct keyword. Structures are used to represent complex data objects, such as a student record containing name, roll number, and marks. They help in organizing data efficiently. Structures can also contain pointers, arrays, and even other structures, allowing flexible data representation.

12. What is a union in C?

A union in C is similar to a structure but with one key difference: all members of a union share the same memory location. This means only one member can store a value at a time. Unions are used when memory efficiency is crucial, such as when working with embedded systems. They help in situations where multiple variables may exist but are not needed simultaneously. Unions are defined using the union keyword.

13. What is the difference between a while loop and a do-while loop?

While loop

The while loop checks the condition before executing the loop body, meaning it may not execute at all if the condition is false initially.

Example i = 1 while i <= 5: print(i) i += 1

 do-while loop

The do-while loop executes the loop body at least once before checking the condition, ensuring that the loop runs at least once regardless of the condition.

Example i = 1 while True: print(i) i += 1 if i > 5: break

14. What is the purpose of return statement?

The return statement in C serves multiple important purposes in a function. It controls the flow of execution and also helps in returning values to the calling function. Below are the detailed purposes and aspects of the return statement

Example

int checkEven(int num) { if (num % 2 != 0) { return 0; // Exits the function early if the number is odd } return 1; // Returns 1 if the number is even }

15. Explain the difference between pass by value and pass by reference in C?

Pass by value

In C, pass by value means passing a copy of the actual value to a function, so changes made inside the function do not affect the original variable.

Pass by reference

Pass by reference is achieved using pointers, allowing a function to modify the original value by passing its memory address. Since C does not support true pass-by-reference like C++, pointers are used instead.

16. What is the purpose of the volatile keyword in C?

  • Recursion in C is a programming technique where a function calls itself to solve a problem. It is often used to break down complex problems into smaller, manageable subproblems. In recursion, the function must have a base case, which is a condition that stops the function from calling itself indefinitely.
  • When the function is called, it performs some work and then calls itself with modified arguments, usually closer to the base case. This process continues until the base case is met, at which point the recursion terminates, and the function returns control to the previous function call.

17. How does pointer arithmetic work in C?

Pointer arithmetic refers to operations performed on pointers, such as addition, subtraction, and comparison, based on the data type they point to. Here's how it works:

  • Pointer Addition: When a pointer is incremented (ptr++), it moves to the next memory location based on the size of the data type it points to. For example, if ptr is a pointer to an int, ptr++ will increase its address by sizeof(int) bytes.
  • Pointer Subtraction: Similarly, when a pointer is decremented (ptr--), it moves back by the size of the data type it points to. For example, ptr-- moves the pointer by -sizeof(int) bytes.
  • Pointer Difference: If you subtract one pointer from another that points to elements of the same array, it returns the number of elements between the two pointers.

18. What is the difference between static and global variables in C?

Static Variable

These are declared inside a function or file, and their scope is limited to that function or file. However, their lifetime lasts for the duration of the program.
Static variables also have a lifetime that lasts for the duration of the program, but they retain their value between function calls, unlike local variables.

Global Variable

These are declared outside all functions, typically at the top of the program, and can be accessed by any function within the same file or other files (if declared as extern).
The lifetime of global variables extends from program start to program end, meaning they are available throughout the execution of the program.

19. What is recursion in C, and how does it work?

Recursion in C is a programming technique where a function calls itself to solve a problem. It is often used to break down complex problems into smaller, manageable subproblems. In recursion, the function must have a base case, which is a condition that stops the function from calling itself indefinitely. When the function is called, it performs some work and then calls itself with modified arguments, usually closer to the base case. This process continues until the base case is met, at which point the recursion terminates, and the function returns control to the previous function call.

20. What is a memory leak in C, and how can it be prevented?

In C programming, a memory leak occurs when the program allocates memory dynamically (using malloc(), calloc(), or realloc()), but fails to free it when it is no longer needed, leading to a loss of access to that memory.

  • A memory leak occurs when dynamically allocated memory is not freed before losing its reference, causing wastage of system memory.
  • It can be prevented by properly deallocating memory using free(), tracking allocated memory with pointers, and using tools like Valgrind to detect leaks in large programs.
  • 21. What is a dynamic memory allocation in C?

    Dynamic Memory Allocation (DMA) in C allows programs to request memory at runtime instead of using fixed-size memory at compile-time. It provides flexibility in managing memory efficiently. DMA is particularly useful when dealing with arrays, linked lists, trees, and other data structures.

    Functions Used for Dynamic Memory Allocation
    • malloc()
    • calloc()
    • realloc()
    • free()

    22. What is the difference between <b>fopen()</b> and <b>freopen()</b>?

    fopen()

    Purpose: The fopen() function is used to open a file in different modes such as read, write, or append.

    Syntax:

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

    freopen()

    Purpose: The freopen() function is used to reopen an already open file with a different mode or associate a new file with a stream (such as stdin, stdout, or stderr).

    Syntax:

    FILE *freopen(const char *filename, const char *mode, FILE *stream);

    23. What are the basic data types in C?

    In C, data types define the type of data a variable can store. They determine the memory size and the operations that can be performed on the variable. 

    The basic data types in C are:

    int: Integer numbers
    float: Floating-point numbers
    double: Double precision floating-point numbers
    char: Single character

    24. What is a ternary operator in C?

    The ternary operator is a conditional operator that allows a shorthand way to write an if-else statement.

    It is written as: condition ? expression1 : expression2;

    #include int main() { int num; // Input a number printf("Enter a number: "); scanf("%d", &num); // Using the ternary operator to check even or odd (num % 2 == 0) ? printf("%d is Even\n", num) : printf("%d is Odd\n", num); return 0; }

    25. For Loop in c?

    The for loop in C is used to execute a block of code repeatedly for a fixed number of times.

    Syntax of For Loop:
    for(initialization; condition; update) { // Code to be executed }
    Example Program:

    #include <stdio.h>

    int main() { int i; // For loop to print numbers from 1 to 5 for(i = 1; i <= 5; i++) { printf("%d\n", i); } return 0; }
    line

    Copyrights © 2024 letsupdateskills All rights reserved