0% found this document useful (0 votes)
23 views37 pages

Prog Lang Interview

The document provides a comprehensive list of frequently asked C programming interview questions, focusing on both basic and advanced concepts. It covers topics such as memory management, pointers, data types, and differences between C and C++ programming languages. Additionally, it includes explanations of key features, storage classes, and dynamic memory allocation in C.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views37 pages

Prog Lang Interview

The document provides a comprehensive list of frequently asked C programming interview questions, focusing on both basic and advanced concepts. It covers topics such as memory management, pointers, data types, and differences between C and C++ programming languages. Additionally, it includes explanations of key features, storage classes, and dynamic memory allocation in C.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

16/11/2024, 11:01 md2pdf - Markdown to PDF

Here is a comprehensive list of frequently asked C programming interview questions that are often
posed to entry-level candidates for software developer roles. The questions focus on theoretical
aspects of the C language, ensuring depth of knowledge without expecting much practical
application.
Frequently Asked C Programming Interview Questions
1. What is C language?
C is a general-purpose, procedural programming language developed by Dennis Ritchie in 1972 at
Bell Labs. It is widely used for system and application software, embedded systems, and low-level
programming tasks due to its efficiency and control over hardware.
2. Why is C called a mid-level programming language?
C is called a mid-level programming language because it combines features of both high-level and
low-level languages. It allows for system-level programming (like assembly) and also provides
abstractions that make it easier to write applications (like high-level languages)[1][2].
3. What are the key features of the C language?
Some key features of C include:
Simple and efficient: Easy to learn and fast execution.
Mid-level language: Combines low-level hardware control with high-level abstractions.
Portable: Code written in C can be run on different machines with minimal or no modifications.
Structured programming: Supports functions and blocks, which help in organizing code.
Rich library support: Provides numerous built-in functions[4].
4. What is the difference between a local variable and a global variable?
Local variable: Declared inside a function or block and accessible only within that function or
block.
Global variable: Declared outside all functions and accessible throughout the entire
program[1].
5. What is a pointer in C?
A pointer is a variable that stores the memory address of another variable. It allows direct access to
memory and manipulation of data stored at specific addresses.
6. What is the difference between malloc() and calloc()?
malloc(): Allocates a single block of memory without initializing it.
https://md2pdf.netlify.app 1/37
16/11/2024, 11:01 md2pdf - Markdown to PDF

calloc(): Allocates multiple blocks of memory and initializes all bits to zero[3].
7. What is the use of the static keyword in C?
The static keyword has three main uses:
For variables inside functions, it preserves their value between function calls.
For global variables, it restricts their scope to the file they are declared in.
For functions, it limits their visibility to the file they are declared in[3].
8. What are storage classes in C?
Storage classes define the scope (visibility) and lifetime of variables/functions within a C program.
The four storage classes are:
auto: Default for local variables.
register: Suggests storing variables in CPU registers.
static: Preserves variable value across function calls.
extern: Extends visibility across multiple files[4].
9. What are preprocessor directives in C?
Preprocessor directives are commands that give instructions to the compiler to preprocess the
information before actual compilation starts. Examples include #define , #include , #ifdef , etc.
10. What is typecasting in C?
Typecasting is the process of converting one data type into another. It can be done implicitly by the
compiler or explicitly by the programmer using casting operators like (int) , (float) , etc.[1].
11. What are arrays in C?
An array is a collection of elements of the same data type stored at contiguous memory locations.
Arrays allow you to store multiple values under a single name.
12. Explain recursion with an example in C.
Recursion occurs when a function calls itself directly or indirectly to solve a problem. Example:
int factorial(int n) {
if (n == 0)
return 1;
else
return n * factorial(n - 1);
}

https://md2pdf.netlify.app 2/37
16/11/2024, 11:01 md2pdf - Markdown to PDF

This function calculates the factorial of a number using recursion[3].


13. What is the difference between pass by value and pass by reference?
In pass by value, a copy of the actual parameter's value is passed to the function, so changes
made inside the function do not affect the original value.
In pass by reference, an address (or pointer) of the actual parameter is passed, allowing
modifications inside the function to affect the original variable.
14. What is a structure in C?
A structure is a user-defined data type that allows grouping variables of different types under one
name.
struct Person {
char name[50];
int age;
};

Structures help organize complex data more efficiently[3].


15. How does memory management work in C?
Memory management in C involves dynamically allocating and freeing memory using functions like
malloc() , calloc() , realloc() , and free() . Proper memory management ensures there are
no memory leaks or dangling pointers[3].
16. What are bitwise operators in C?
Bitwise operators perform operations on individual bits of data:
AND ( & ), OR ( | ), XOR ( ^ ), NOT ( ~ )
Left shift ( << ) and right shift ( >> ).
These operators are often used for low-level programming tasks like setting or clearing specific
bits.
17. What are header files in C?
Header files contain definitions of functions and macros that can be shared across multiple source
files using #include . Common header files include <stdio.h> , <stdlib.h> , <string.h> , etc.
18. Explain dynamic memory allocation in C with an example.
https://md2pdf.netlify.app 3/37
16/11/2024, 11:01 md2pdf - Markdown to PDF

Dynamic memory allocation allows you to allocate memory during runtime using functions like
malloc() or calloc() :

int *ptr = (int*) malloc(5 * sizeof(int)); // Allocates memory for an array of five in

Always remember to free dynamically allocated memory using free() .


19. What is a null pointer?
A null pointer points to nothing (i.e., address zero). It is often used as an indicator that a pointer
does not currently point to any valid object.
int *ptr = NULL;

20. What is an infinite loop? How can you create one in C?


An infinite loop runs indefinitely because its termination condition never becomes false:
while(1) {
// Infinite loop
}

Infinite loops are often used when waiting for external events like user input.

Here is a more advanced set of C programming interview questions, tailored for candidates with 2-
3 years of experience. These questions focus on deeper theoretical aspects, memory
management, and comparisons with other programming languages, as well as computer
architecture-related concepts.
Advanced C Programming Interview Questions
1. What is the difference between static and dynamic memory allocation in C?
Static Memory Allocation: Memory is allocated at compile-time. The size of variables is fixed,
and memory cannot be resized during program execution. It uses the stack.
Dynamic Memory Allocation: Memory is allocated at runtime using functions like malloc() ,
calloc() , or realloc() . It allows resizing of memory blocks and uses the heap[5][6].

2. What are the main issues associated with dynamic memory allocation?
https://md2pdf.netlify.app 4/37
16/11/2024, 11:01 md2pdf - Markdown to PDF

Memory Leaks: If dynamically allocated memory is not freed using free() , it can lead to
memory leaks.
Fragmentation: Internal and external fragmentation can occur if memory is not efficiently
managed. External fragmentation happens when there are small free blocks that cannot be
utilized[9].
Performance Overhead: Dynamic allocation involves more overhead than static allocation due
to the need to manage the heap[5].
3. Explain the difference between malloc() and calloc() in terms of
memory allocation.
malloc() : Allocates a single block of memory without initializing it. The content of the
allocated block remains uninitialized.
calloc() : Allocates multiple blocks of memory and initializes all bytes to zero[1][6].

4. What is a segmentation fault, and what causes it in C?


A segmentation fault occurs when a program tries to access a restricted area of memory (e.g.,
accessing an invalid pointer or dereferencing a null pointer). It typically happens due to:
Dereferencing null or uninitialized pointers.
Accessing memory beyond allocated bounds (buffer overflow).
Writing to read-only memory locations.
5. How does C handle function calls with respect to the stack?
When a function is called:
The function’s arguments are pushed onto the stack.
The return address is saved on the stack.
Local variables are allocated on the stack. When the function returns, the stack is unwound by
popping arguments, local variables, and return addresses off the stack.
6. What are function pointers in C, and how are they used?
A function pointer stores the address of a function that can be called indirectly through the pointer.
They are useful for implementing callback functions or passing functions as arguments.
Example:
void (*funcPtr)(int);
funcPtr = &someFunction;
(*funcPtr)(10); // Calls someFunction(10)

https://md2pdf.netlify.app 5/37
7. Explain how arrays are stored in memory in C.
16/11/2024, 11:01 md2pdf - Markdown to PDF

Arrays in C are stored in contiguous blocks of memory. The elements of an array are laid out
sequentially in increasing order of their index, with each element occupying space equal to its data
type.
8. What is the difference between arrays in C and arrays in higher-level
languages like Python or Java?
In C, arrays have a fixed size determined at compile-time or dynamically at runtime using
pointers. They do not support resizing after allocation.
In higher-level languages like Python or Java, arrays (or lists) can grow dynamically and offer
built-in methods for resizing and manipulation.
9. What is a volatile keyword in C? How does it affect optimization?
The volatile keyword tells the compiler that the value of a variable may change unexpectedly
(e.g., hardware registers). This prevents the compiler from optimizing code by caching variable
values, ensuring that every access fetches fresh data from memory.
10. How does C handle integer overflow?
C does not check for integer overflow by default. If an integer operation exceeds its maximum
value, it wraps around (modular arithmetic). For example, adding 1 to INT_MAX results in INT_MIN .
11. Explain how memory alignment works in C and why it’s important.
Memory alignment refers to arranging data in memory according to specific boundaries (e.g., 4-
byte boundaries for integers). Proper alignment ensures efficient access by the CPU, reducing
performance penalties associated with misaligned data access[9].
12. What is a union in C? How does it differ from a structure?
A union allows storing different data types in the same memory location but only one member can
hold a value at any time. A structure allocates separate memory for each member, allowing multiple
members to hold values simultaneously.
13. How do you prevent buffer overflows in C?
Buffer overflows can be prevented by:
Using bounds checking when accessing arrays.
Using safer alternatives like snprintf() instead of sprintf() .
Validating input lengths when reading from user input or files.
https://md2pdf.netlify.app 6/37
14. What is a double pointer (pointer to pointer) in C? Give an example use
16/11/2024, 11:01 md2pdf - Markdown to PDF

case.
A double pointer stores the address of another pointer. It’s commonly used for dynamic
multidimensional arrays or modifying pointers within functions.
Example:
void modifyPointer(int **ptr) {
*ptr = malloc(sizeof(int));
}

15. How does dynamic memory allocation differ between C and languages like
Java or Python?
In C:
Memory management is manual using malloc() , calloc() , and free() . In Java/Python:
Memory management is automatic via garbage collection, which periodically deallocates
unused objects without explicit programmer intervention[7].
16. What are near, far, and huge pointers? Why are they obsolete today?
These pointers were used in older architectures (like DOS) to manage segmented memory models:
Near pointers: Pointed within a single segment (64KB).
Far/huge pointers: Could point across segments. They are obsolete today because modern
systems use flat memory models where all addresses are linear[10].
17. Explain how virtual memory works at a high level and its relevance to C
programming.
Virtual memory allows programs to use more memory than physically available by swapping pages
between RAM and disk storage. In C programming, this affects how large data structures like arrays
behave when they exceed physical RAM limits.
18. What happens if you try to free already freed memory?
Freeing already freed memory results in undefined behavior, which may cause crashes or
corruption of heap structures managed by the operating system.
19. How does paging work in operating systems concerning dynamic memory
allocation?
https://md2pdf.netlify.app 7/37
16/11/2024, 11:01 md2pdf - Markdown to PDF

Paging divides virtual memory into fixed-size pages that map to physical frames in RAM. When
dynamically allocating large amounts of memory ( malloc() ), pages may be swapped between
disk and RAM as needed based on access patterns.
20. Why might you choose C over languages like Python for system-level
programming tasks?
C provides low-level control over hardware resources (e.g., direct access to memory via pointers),
which makes it ideal for system-level programming tasks like writing operating systems or
embedded software where performance and resource control are critical[7].

Here is a comprehensive list of 30 C++ interview questions, ranging from intermediate to advanced
levels, designed for candidates with a strong background in C++ and computer science
fundamentals. The questions focus on core C++ concepts, memory management, object-oriented
programming (OOP), and deeper computer architecture-related topics.
Intermediate to Advanced C++ Interview Questions
1. What is the difference between C and C++?
C is a procedural programming language, while C++ supports both procedural and object-oriented
paradigms. C++ introduces classes, objects, inheritance, polymorphism, encapsulation, and
abstraction. Additionally, C++ offers features like function overloading, operator overloading, and
templates that are not present in C.
2. Explain the concept of Object-Oriented Programming (OOP) in C++.
OOP in C++ is based on four key principles:
Encapsulation: Bundling data and methods that operate on that data.
Abstraction: Hiding implementation details and exposing only essential features.
Inheritance: Deriving new classes from existing ones to promote code reuse.
Polymorphism: Allowing functions or operators to behave differently based on the context
(e.g., function overloading and virtual functions).
3. What are access specifiers in C++?
Access specifiers define the access level of class members:
Public: Members are accessible from outside the class.
Private: Members are accessible only within the class.
Protected: Members are accessible within the class and derived classes.
https://md2pdf.netlify.app 8/37
4. What is the difference between a reference and a pointer in C++?
16/11/2024, 11:01 md2pdf - Markdown to PDF

Reference: Must be initialized when declared, cannot be null, and cannot be reassigned.
Pointer: Can be initialized later, can be null or point to different objects during its lifetime.
5. What is the purpose of the virtual keyword in C++?
The virtual keyword is used to enable runtime polymorphism by allowing derived classes to
override base class methods. When a method is declared as virtual in a base class, the derived
class can provide its own implementation.
6. What is a pure virtual function?
A pure virtual function is a function that has no implementation in the base class and must be
overridden by derived classes. It is declared using = 0 syntax:
class Base {
virtual void display() = 0; // Pure virtual function
};

7. What are templates in C++?


Templates allow writing generic code that works with any data type. There are two types of
templates:
Function templates: For creating generic functions.
Class templates: For creating generic classes.
8. Explain RAII (Resource Acquisition Is Initialization) in C++.
RAII ensures that resources like memory or file handles are acquired during object creation
(constructor) and released during object destruction (destructor). This guarantees that resources
are properly managed even if exceptions occur.
9. What are smart pointers in C++?
Smart pointers manage dynamic memory automatically by ensuring proper deallocation when the
pointer goes out of scope. Types include:
std::unique_ptr : Owns an object exclusively.

std::shared_ptr : Allows multiple owners of an object.

std::weak_ptr : Provides non-owning access to an object managed by std::shared_ptr .

10. What is operator overloading?


https://md2pdf.netlify.app 9/37
16/11/2024, 11:01 md2pdf - Markdown to PDF

Operator overloading allows customizing the behavior of operators for user-defined types (e.g.,
classes). For example, you can overload the + operator for a Complex number class:
Complex operator+(const Complex& c1, const Complex& c2);

11. What is multiple inheritance in C++, and when would you use it?
Multiple inheritance allows a derived class to inherit from more than one base class. It can be useful
when combining functionalities from different classes but should be used carefully to avoid
ambiguity issues (e.g., diamond problem).
12. What is the diamond problem in multiple inheritance? How does C++
resolve it?
The diamond problem occurs when two base classes inherit from the same ancestor class, and a
derived class inherits from both base classes. This leads to ambiguity about which ancestor's
members should be inherited. It is resolved using virtual inheritance, which ensures only one copy
of the common base class exists.
class A {};
class B : virtual public A {};
class C : virtual public A {};
class D : public B, public C {}; // D has only one copy of A

13. Explain deep copy vs shallow copy in C++.


Shallow copy: Copies only the object's pointer values; both objects share the same memory
address for dynamically allocated memory.
Deep copy: Copies both pointer values and the data they point to by allocating new memory
for each copy.
14. What is exception handling in C++? How does it differ from other
languages like Java?
Exception handling in C++ uses try , catch , and throw blocks to handle runtime errors. Unlike
Java, where all exceptions are objects derived from Throwable , exceptions in C++ can be of any
type (e.g., integers or custom objects).
15. What is the difference between new / delete and malloc() / free() ?
new / delete : Allocate and deallocate memory while also calling constructors/destructors.
malloc() / free() : Allocate and deallocate raw memory without invoking
constructors/destructors.
https://md2pdf.netlify.app 10/37
16. How does memory management work with dynamic arrays in C++?
16/11/2024, 11:01 md2pdf - Markdown to PDF

Dynamic arrays can be created using pointers with new[] . Memory must be explicitly deallocated
using delete[] . Failure to do so leads to memory leaks.
int* arr = new int[10]; // Allocate array
delete[] arr; // Deallocate array

17. What are namespaces in C++, and why are they important?
Namespaces prevent name collisions by grouping related entities under a unique name:
namespace MyNamespace {
int x;
}

To access members within a namespace:


MyNamespace::x;

18. What are static members in a class?


Static members belong to the class rather than any specific object instance:
Static variables retain their value across all instances.
Static functions can be called without creating an instance of the class.
19. Explain move semantics and rvalue references in C++. Why were they
introduced?
Move semantics allow transferring resources from one object to another without copying them,
improving performance for temporary objects (e.g., large containers). Rvalue references ( T&& )
enable move semantics by binding to temporary objects.
void setValue(std::vector<int>&& v); // Accepts rvalue references

20. What is STL (Standard Template Library)? What are its components?
STL provides generic data structures and algorithms:
Containers (e.g., vector, list)
Iterators (to traverse containers)
https://md2pdf.netlify.app 11/37
16/11/2024, 11:01 md2pdf - Markdown to PDF

Algorithms (e.g., sort, find)

Advanced Computer Science Fundamentals Questions


21. How does virtual function dispatch work internally (vtable)?
When a class contains virtual functions, a vtable (virtual table) is created at compile-time
containing pointers to virtual functions for that class. Each object contains a vpointer pointing to
this vtable. During runtime polymorphism, function calls are resolved through this vtable.
22. Explain how cache locality affects performance when using arrays vs
linked lists in modern CPUs.
Arrays exhibit better cache locality because elements are stored contiguously in memory, allowing
prefetching into cache lines efficiently. Linked lists have poor cache locality since nodes may be
scattered across memory.
23. How does dynamic dispatch differ from static dispatch? When does each
occur?
Static dispatch occurs at compile-time (e.g., function overloading).
Dynamic dispatch occurs at runtime via virtual functions or interfaces.
Dynamic dispatch involves additional overhead due to vtable lookups but enables polymorphic
behavior.
24. Describe how stack unwinding works during exception handling in C++.
Stack unwinding refers to cleaning up local variables as control moves up through nested function
calls when an exception is thrown but not caught locally. Destructors for local variables are called
during this process.
25. Explain how placement new works in C++. Why would you use it?
Placement new allows constructing an object at a specific memory location:
void* buffer = malloc(sizeof(MyClass));
MyClass* obj = new(buffer) MyClass(); // Construct at buffer location

This technique is useful for custom memory management scenarios where precise control over
memory allocation is required.

https://md2pdf.netlify.app 12/37
26. How does thread safety relate to static variables inside functions in
16/11/2024, 11:01 md2pdf - Markdown to PDF

multithreaded environments?
Static variables inside functions retain their value across invocations but can lead to race
conditions if accessed by multiple threads simultaneously without proper synchronization
mechanisms like mutexes or atomic operations.
27. Compare lock-based synchronization with lock-free programming
techniques like atomic operations or compare-and-swap (CAS).
Lock-based synchronization uses mutexes or semaphores but can lead to contention or deadlocks
if not used carefully. Lock-free programming uses atomic operations like CAS
( compare_exchange_strong ) to avoid locks but requires careful design to prevent race conditions
while ensuring correctness.
28. How does paging work at the OS level when dynamically allocating large
amounts of memory using new or malloc() ?
Paging divides physical memory into fixed-size pages mapped into virtual address space via page
tables maintained by the OS kernel. When dynamically allocating large blocks of memory, pages
may need to be swapped between disk storage and RAM depending on available physical memory.
29. How do modern compilers optimize tail recursion calls in recursive
functions?
Modern compilers optimize tail-recursive functions by reusing stack frames for successive
recursive calls instead of pushing new frames onto the stack—this optimization prevents stack
overflow for deep recursions.
30. Explain how CPU branch prediction affects performance when using
conditional statements inside loops (e.g., if-statements).
Branch prediction attempts to guess which way a branch will go before it’s known definitively at
runtime; if predicted correctly, execution proceeds smoothly; if predicted incorrectly (branch
misprediction), there’s performance penalty due to pipeline flushing and re-fetching instructions.

Here is a collection of 30 Python interview questions designed for someone with around one year
of experience. These questions cover core Python concepts, object-oriented programming (OOP),
and some intermediate-level topics that are frequently asked in interviews. The questions are
designed to test your understanding of Python's syntax, features, and OOP principles.
Frequently Asked Python Interview Questions
https://md2pdf.netlify.app 13/37
1. What are the key features of Python?
16/11/2024, 11:01 md2pdf - Markdown to PDF

Python is:
Interpreted: Code is executed line by line.
Dynamically typed: Variable types are determined at runtime.
High-level: It abstracts away most low-level details like memory management.
Object-oriented: Supports OOP principles like inheritance, encapsulation, and polymorphism.
Extensive libraries: Python has a vast standard library and third-party modules.
2. What is the difference between lists and tuples in Python?
Lists: Mutable, meaning their elements can be changed after creation. Defined using square
brackets [] .
Tuples: Immutable, meaning their elements cannot be changed once created. Defined using
parentheses () .
3. How do you handle exceptions in Python?
Exceptions in Python are handled using try , except , else , and finally blocks:
try:
# Code that may raise an exception
except SomeException:
# Handle the exception
else:
# Code that runs if no exception occurs
finally:
# Code that always runs (cleanup)

4. What is a dictionary in Python, and how do you access its elements?


A dictionary is an unordered collection of key-value pairs. Keys must be unique and immutable
(e.g., strings or numbers), while values can be of any type.
my_dict = {'name': 'John', 'age': 25}
print(my_dict['name']) # Accessing value by key

5. What is the difference between == and is operators in Python?


== : Compares the values of two objects for equality.
is : Compares the memory addresses (identity) of two objects.

6. Explain the concept of mutable vs immutable objects in Python.


https://md2pdf.netlify.app 14/37
16/11/2024, 11:01 md2pdf - Markdown to PDF

Mutable objects: Can be changed after creation (e.g., lists, dictionaries).


Immutable objects: Cannot be changed after creation (e.g., strings, tuples).
7. What are list comprehensions in Python?
List comprehensions provide a concise way to create lists based on existing iterables.
squares = [x**2 for x in range(10)]

8. What is a lambda function in Python?


A lambda function is an anonymous function defined with the keyword lambda . It can have any
number of arguments but only one expression.
add = lambda x, y: x + y
print(add(2, 3)) # Output: 5

9. What is the purpose of the self parameter in class methods?


The self parameter refers to the instance of the class and allows access to its attributes and
methods from within class methods.
10. Explain how inheritance works in Python.
Inheritance allows one class (child) to inherit attributes and methods from another class (parent).
This promotes code reuse.
class Parent:
def greet(self):
print("Hello from Parent")

class Child(Parent):
pass

c = Child()
c.greet() # Inherits greet() from Parent

11. What are decorators in Python?


Decorators are functions that modify the behavior of another function or method. They are often
used for logging, access control, or timing functions.
def decorator(func):
def wrapper():
https://md2pdf.netlify.app 15/37
16/11/2024, 11:01 md2pdf - Markdown to PDF
print("Before function call")
func()
print("After function call")
return wrapper

@decorator
def say_hello():
print("Hello!")

say_hello()

12. What is the difference between a class method and a static method?
Class method ( @classmethod ): Takes cls as its first argument and can modify class state.
Static method ( @staticmethod ): Does not take self or cls as arguments; it behaves like a
regular function but belongs to the class’s namespace.
13. How does garbage collection work in Python?
Python uses automatic garbage collection to free memory by removing objects that are no longer
referenced by any variable. It uses reference counting and cyclic garbage collection to manage
memory.
14. What is PEP8, and why is it important?
PEP8 is the style guide for writing clean and readable Python code. It covers naming conventions,
indentation rules, line length limits, etc., to ensure consistency across projects.
15. What are generators in Python? How do they differ from regular functions?
Generators allow you to iterate over data lazily (one item at a time) using the yield keyword
instead of returning all results at once.
def my_generator():
yield 1
yield 2

gen = my_generator()
print(next(gen)) # Output: 1
print(next(gen)) # Output: 2

16. Explain how multiple inheritance works in Python.


Multiple inheritance allows a class to inherit from more than one base class.

https://md2pdf.netlify.app 16/37
16/11/2024, 11:01 md2pdf - Markdown to PDF

class A:
def greet(self):
print("Hello from A")

class B:
def greet(self):
print("Hello from B")

class C(A, B):


pass

c = C()
c.greet() # Resolves using Method Resolution Order (MRO)

17. What are metaclasses in Python?


Metaclasses are classes that define how other classes behave. They allow you to customize class
creation by overriding methods like __new__ or __init__ .
18. How do you manage packages and dependencies in Python projects?
You can manage packages using tools like pip for installation and virtual environments ( venv ) for
isolating dependencies.
19. What is a context manager in Python? How do you implement one?
Context managers handle resource management tasks like opening/closing files or database
connections using the with statement.
with open('file.txt', 'r') as file:
data = file.read() # File automatically closed after block execution

You can create custom context managers using the __enter__() and __exit__() methods.
20. Explain duck typing in Python with an example.
Duck typing refers to dynamic typing where an object's behavior determines its suitability for use
rather than its type.
class Duck:
def quack(self):
print("Quack!")

class Dog:
def quack(self):
print("Woof!")

https://md2pdf.netlify.app 17/37
16/11/2024, 11:01 md2pdf - Markdown to PDF

def make_it_quack(animal):
animal.quack()

make_it_quack(Duck()) # Output: Quack!


make_it_quack(Dog()) # Output: Woof!

Intermediate-Level OOP & Application-Based Questions


21. How do you implement polymorphism in Python?
Polymorphism allows different classes to define methods with the same name but different
implementations.
class Cat:
def speak(self):
return "Meow"

class Dog:
def speak(self):
return "Woof"

animals = [Cat(), Dog()]


for animal in animals:
print(animal.speak()) # Output depends on object type

22. What is method overriding in Python? How does it differ from method
overloading?
Method overriding occurs when a child class provides its own implementation of a method
inherited from a parent class.
Unlike other languages like Java or C++, Python does not support traditional method
overloading based on argument types or counts; instead, default arguments or variable-length
arguments ( *args , **kwargs ) are used.
23. Explain how encapsulation works in Python with an example.
Encapsulation restricts access to certain attributes/methods by marking them as private using
underscores ( _ or __ ).
class MyClass:
def __init__(self):
self._protected_var = "Protected"
self.__private_var = "Private"

https://md2pdf.netlify.app 18/37
16/11/2024, 11:01 md2pdf - Markdown to PDF

obj = MyClass()
print(obj._protected_var) # Accessible but discouraged conventionally
# print(obj.__private_var) # Raises AttributeError due to name mangling

24. How do you implement abstract classes in Python?


Abstract classes cannot be instantiated directly and must define at least one abstract method
using the abc module.
from abc import ABC, abstractmethod

class Animal(ABC):
@abstractmethod
def sound(self):
pass

class Dog(Animal):
def sound(self):
return "Bark"

25. Explain how inheritance affects method resolution order (MRO) in multiple
inheritance scenarios.
Python uses C3 linearization (MRO) to determine the order in which base classes should be
searched when looking up methods or attributes during multiple inheritance.
You can view MRO using:
print(ClassName.__mro__)

More Practical Application-Based Questions


26. How would you optimize a slow-running script written in Python?
Some common optimization techniques include:
Using efficient data structures (e.g., sets instead of lists).
Profiling code with tools like cProfile .
Leveraging built-in libraries like NumPy for numerical computations.
Using caching via decorators like functools.lru_cache .

https://md2pdf.netlify.app 19/37
27. How do you handle memory management issues such as memory leaks in
16/11/2024, 11:01 md2pdf - Markdown to PDF

Python?
Memory management issues can be handled by:
Using weak references ( weakref ) for large objects that should not prevent garbage collection.
Avoiding circular references by explicitly breaking them or using weak references.
28. How would you implement a singleton pattern in Python?
A singleton ensures only one instance of a class exists throughout the program's lifetime.
class Singleton:
_instance = None

def __new__(cls):
if cls._instance is None:
cls._instance = super(Singleton, cls).__new__(cls)
return cls._instance

29. How would you handle large datasets efficiently with limited memory
resources in Python?
To handle large datasets efficiently:
Use generators instead of loading all data into memory at once.
Process data chunks iteratively (e.g., reading files line by line).
Example using generators:
def read_large_file(file_name):
with open(file_name) as file:
for line in file:
yield line.strip()

30. Explain how multithreading works in Python given the Global Interpreter
Lock (GIL). When would you use multiprocessing instead?
The GIL prevents multiple native threads from executing simultaneously within one process due to
thread safety concerns with CPython's memory management.
For CPU-bound tasks requiring parallel execution, it's better to use multiprocessing rather than
multithreading since each process gets its own interpreter instance without GIL restrictions.

https://md2pdf.netlify.app 20/37
16/11/2024, 11:01 md2pdf - Markdown to PDF

Here are 10 comparison-based problems that explore key differences and similarities between C,
C++, and Python. These problems cover various aspects of the languages, including memory
management, object-oriented programming, syntax, performance, and more. Each problem is
followed by a solution that explains how each language handles the particular concept.

1. Memory Management: Manual vs Automatic


Problem:
Compare how memory is managed in C, C++, and Python. Write a program to dynamically allocate
memory for an array of integers, store values in it, and then free the memory.
Solution:
C: In C, memory management is manual using malloc() and free() . You need to explicitly
allocate and deallocate memory.
#include <stdio.h>
#include <stdlib.h>

int main() {
int *arr = (int*) malloc(5 * sizeof(int)); // Allocate memory for 5 integers
for (int i = 0; i < 5; i++) {
arr[i] = i + 1;
}
free(arr); // Free allocated memory
return 0;
}

C++: In C++, you can use new and delete for dynamic memory allocation. Alternatively,
smart pointers can be used for automatic memory management.
#include <iostream>

int main() {
int *arr = new int[5]; // Allocate memory for 5 integers
for (int i = 0; i < 5; i++) {
arr[i] = i + 1;
}
delete[] arr; // Free allocated memory
return 0;
}

Python: Python uses automatic garbage collection, so you don’t need to manually allocate or
free memory. Lists are dynamically managed by the interpreter.

https://md2pdf.netlify.app 21/37
16/11/2024, 11:01 md2pdf - Markdown to PDF

arr = [i + 1 for i in range(5)] # Python list automatically manages memory

2. Object-Oriented Programming: Class Definitions


Problem:
Create a simple class called Person with attributes name and age , and a method greet() that
prints a greeting message. Compare how classes are defined in C++, Python, and how OOP is
handled differently in C.
Solution:
C++: C++ supports full object-oriented programming with classes, inheritance, polymorphism,
etc.
#include <iostream>
using namespace std;

class Person {
public:
string name;
int age;

Person(string n, int a) : name(n), age(a) {}

void greet() {
cout << "Hello, my name is " << name << " and I am " << age << " years old." <
}
};

int main() {
Person p("Alice", 30);
p.greet();
}

Python: Python has a simpler syntax for defining classes but supports OOP principles like
inheritance and polymorphism.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")

https://md2pdf.netlify.app 22/37
16/11/2024, 11:01 md2pdf - Markdown to PDF
p = Person("Alice", 30)
p.greet()

C: C does not have built-in support for OOP. However, you can simulate OOP using structs and
function pointers.
#include <stdio.h>
#include <string.h>

typedef struct {
char name[50];
int age;
} Person;

void greet(Person *p) {


printf("Hello, my name is %s and I am %d years old.\n", p->name, p->age);
}

int main() {
Person p;
strcpy(p.name, "Alice");
p.age = 30;

greet(&p);
}

3. Exception Handling
Problem:
Write code to handle division by zero in C, C++, and Python using exception handling mechanisms
available in each language.
Solution:
C: C does not have built-in exception handling like C++ or Python. Errors must be handled
manually using return codes or flags.
#include <stdio.h>

int divide(int a, int b) {


if (b == 0) {
printf("Error: Division by zero\n");
return -1;
}
return a / b;
}

https://md2pdf.netlify.app 23/37
16/11/2024, 11:01 md2pdf - Markdown to PDF
int main() {
int result = divide(10, 0);
}

C++: C++ provides exception handling using try , catch , and throw .
#include <iostream>
using namespace std;

int divide(int a, int b) {


if (b == 0) throw runtime_error("Division by zero");
return a / b;
}

int main() {
try {
cout << divide(10, 0) << endl;
} catch (const runtime_error& e) {
cout << e.what() << endl;
}
}

Python: Python has built-in exception handling using try , except .


def divide(a, b):
try:
return a / b
except ZeroDivisionError:
print("Error: Division by zero")

print(divide(10, 0))

4. Function Overloading
Problem:
Write overloaded functions to add two integers or two floats in C++, Python, and compare this with
how function overloading is handled in C.
Solution:
C++: Supports function overloading based on argument types or numbers.
#include <iostream>
using namespace std;

int add(int a, int b) { return a + b; }

https://md2pdf.netlify.app 24/37
16/11/2024, 11:01 md2pdf - Markdown to PDF
float add(float a, float b) { return a + b; }

int main() {
cout << add(2, 3) << endl; // Calls int version
cout << add(2.5f, 3.5f) << endl; // Calls float version
}

Python: Python does not support traditional function overloading. Instead, you can use default
arguments or variable-length arguments ( *args ).
def add(a, b):
return a + b

print(add(2, 3)) # Works with integers


print(add(2.5, 3.5)) # Works with floats

C: Function overloading is not supported in C. You would need to use different function names
or manually check types at runtime.
#include <stdio.h>

int add_int(int a, int b) { return a + b; }


float add_float(float a, float b) { return a + b; }

int main() {
printf("%d\n", add_int(2, 3));
printf("%f\n", add_float(2.5f, 3.5f));
}

5. File Handling
Problem:
Write code to open a file and read its contents in C, C++, and Python.
Solution:
C:
#include <stdio.h>

int main() {
FILE *file = fopen("test.txt", "r");

if (file == NULL) {
printf("Error opening file\n");
return -1;
https://md2pdf.netlify.app 25/37
16/11/2024, 11:01 md2pdf - Markdown to PDF
}

char line[100];

while (fgets(line, sizeof(line), file)) {


printf("%s", line);
}

fclose(file);
}

C++:
#include <iostream>
#include <fstream>
using namespace std;

int main() {
ifstream file("test.txt");

if (!file.is_open()) {
cout << "Error opening file" << endl;
return -1;
}

string line;

while (getline(file, line)) {


cout << line << endl;
}

file.close();
}

Python:
with open('test.txt', 'r') as file:
for line in file:
print(line.strip())

6. Multithreading
Problem:
Compare how multithreading is handled in C (POSIX threads), C++ (std::thread), and Python
( threading module). Write code to create two threads that print numbers from different ranges.
Solution:
https://md2pdf.netlify.app 26/37
16/11/2024, 11:01 md2pdf - Markdown to PDF

C (POSIX threads):
#include <pthread.h>
#include <stdio.h>

void* print_numbers(void* arg) {


int start = *(int*)arg;
for (int i = start; i < start + 5; i++) {
printf("%d ", i);
}
return NULL;
}

int main() {
pthread_t t1, t2;
int start1 = 1;
int start2 = 6;

pthread_create(&t1, NULL, print_numbers, &start1);


pthread_create(&t2, NULL, print_numbers, &start2);

pthread_join(t1,NULL);
pthread_join(t2,NULL);

return 0;
}

C++ ( std::thread ):
#include <iostream>
#include <thread>

void print_numbers(int start) {


for (int i = start; i < start + 5; ++i)
std::cout << i << " ";
}

int main() {
std::thread t1(print_numbers, 1);
std::thread t2(print_numbers, 6);

t1.join();
t2.join();
}

Python ( threading module):


import threading

https://md2pdf.netlify.app 27/37
16/11/2024, 11:01 md2pdf - Markdown to PDF
def print_numbers(start):
for i in range(start,start+5):
print(i,end=' ')

t1 = threading.Thread(target=print_numbers,args=(1,))
t2 = threading.Thread(target=print_numbers,args=(6,))
t1.start()
t2.start()
t1.join()
t2.join()

7. Template vs Dynamic Typing


Problem:
In languages like C++, templates allow generic programming at compile-time. In dynamically typed
languages like Python or statically typed languages like C/C++, how do you handle generic data
types?
Solution:
C++ Templates:
#include <iostream>
using namespace std;

template<typename T>
T add(T a,T b){
return a+b;
}

int main(){
cout<<add<int>(3 ,4)<<endl; // Works with integers.
cout<<add<float>(3.5 ,4.7)<<endl;// Works with floats.
}

Python Dynamic Typing (No templates):


def add(a,b):
return a+b

print(add(3 ,4)) # Works with integers.


print(add(3.5 ,4.7)) # Works with floats.

C Generic Programming (No templates):

https://md2pdf.netlify.app 28/37
16/11/2024, 11:01 md2pdf - Markdown to PDF

In C we typically use macros or void pointers to achieve generic programming but it's not as flexible
as templates in C++ or dynamic typing in Python.

8. Variable Scope
Problem:
Compare how variable scope works in functions across these three languages when variables are
declared inside functions vs global variables.
Solution:
In all three languages:
Variables declared inside functions are local to that function.
Global variables can be accessed from any part of the program unless shadowed by local
variables.
Example global variable usage:
C/C++ Global Variables Example
In both languages global variables can be declared outside any function scope.
#include<stdio.h>

//Global Variable
int x=10;

void func(){
x+=10;//Accessing global variable
printf("%d",x);
}

void main(){
func();
printf("%d",x);
}

9. Performance Comparison: Sorting Large Datasets


Problem:
Write a program to sort a large list of integers (e.g., 1 million integers) and compare the
performance of sorting in C, C++, and Python.
Solution:
C: In C, you can use the qsort() function from the standard library for sorting.
https://md2pdf.netlify.app 29/37
16/11/2024, 11:01 md2pdf - Markdown to PDF

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

int compare(const void *a, const void *b) {


return (*(int*)a - *(int*)b);
}

int main() {
int n = 1000000;
int *arr = (int*)malloc(n * sizeof(int));

// Fill array with random numbers


for (int i = 0; i < n; i++) {
arr[i] = rand();
}

clock_t start = clock();


qsort(arr, n, sizeof(int), compare);
clock_t end = clock();

printf("Time taken in C: %f seconds\n", (double)(end - start) / CLOCKS_PER_SEC);

free(arr);
}

C++: In C++, you can use the std::sort() function from the <algorithm> header.
#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>

int main() {
int n = 1000000;
std::vector<int> arr(n);

// Fill array with random numbers


for (int i = 0; i < n; i++) {
arr[i] = rand();
}

clock_t start = clock();


std::sort(arr.begin(), arr.end());
clock_t end = clock();

std::cout << "Time taken in C++: " << (double)(end - start) / CLOCKS_PER_SEC << "
}

https://md2pdf.netlify.app 30/37
16/11/2024, 11:01 md2pdf - Markdown to PDF

Python: In Python, you can use the built-in sorted() function or the sort() method for lists.
import random
import time

arr = [random.randint(0, 1000000) for _ in range(1000000)]

start = time.time()
arr.sort()
end = time.time()

print(f"Time taken in Python: {end - start} seconds")

10. Memory Management: Stack vs Heap


Problem:
Compare how stack and heap memory management works in C, C++, and Python. Write a program
that allocates memory on both the stack and heap and explain how each language handles it.
Solution:
C: In C, local variables are stored on the stack, while dynamic memory allocation (using
malloc ) is done on the heap.

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

int main() {
int stack_var = 10; // Allocated on stack
int *heap_var = (int *)malloc(sizeof(int)); // Allocated on heap
*heap_var = 20;

printf("Stack variable: %d\n", stack_var);


printf("Heap variable: %d\n", *heap_var);

free(heap_var); // Free heap memory


}

C++: Similar to C, local variables are stored on the stack while dynamic memory allocation
using new is done on the heap.
#include <iostream>

int main() {
int stack_var = 10; // Stack allocation
int *heap_var = new int(20); // Heap allocation

std::cout << "Stack variable: " << stack_var << std::endl;


https://md2pdf.netlify.app 31/37
16/11/2024, 11:01 md2pdf - Markdown to PDF
std::cout << "Heap variable: " << *heap_var << std::endl;

delete heap_var; // Free heap memory


}

Python: Python abstracts away memory management. Variables are automatically managed by
Python’s garbage collector. However, all objects in Python are allocated on the heap.
stack_var = 10 # This is technically stored on the heap
heap_var = [20] # Lists are dynamically allocated on the heap

print(f"Stack-like variable: {stack_var}")


print(f"Heap-like variable: {heap_var[0]}")

11. String Manipulation


Problem:
Write a program to reverse a string in C, C++, and Python. Compare how string manipulation differs
across these languages.
Solution:
C:
#include <stdio.h>
#include <string.h>

void reverse(char str[]) {


int n = strlen(str);
for (int i = 0; i < n / 2; i++) {
char temp = str[i];
str[i] = str[n - i - 1];
str[n - i - 1] = temp;
}
}

int main() {
char str[] = "Hello World";
reverse(str);
printf("%s\n", str);
}

C++:
#include <iostream>
#include <algorithm>
https://md2pdf.netlify.app 32/37
16/11/2024, 11:01 md2pdf - Markdown to PDF
using namespace std;

int main() {
string str = "Hello World";
reverse(str.begin(), str.end());
cout << str << endl;
}

Python:
str = "Hello World"
print(str[::-1]) # Slicing method to reverse string in Python

12. Input/Output Operations


Problem:
Write a program to take user input and print it back in C, C++, and Python. Compare how I/O
operations differ between these languages.
Solution:
C:
#include <stdio.h>

int main() {
char name[50];
printf("Enter your name: ");
fgets(name, sizeof(name), stdin);
printf("Hello, %s", name);
}

C++:
#include <iostream>
using namespace std;

int main() {
string name;
cout << "Enter your name: ";
getline(cin, name);
cout << "Hello, " << name << endl;
}

Python:
https://md2pdf.netlify.app 33/37
16/11/2024, 11:01 md2pdf - Markdown to PDF

name = input("Enter your name: ")


print(f"Hello, {name}")

13. Variable Arguments Functions


Problem:
Write a function that takes a variable number of arguments and sums them up in C, C++, and
Python. Compare how variadic functions are implemented across these languages.
Solution:
C (using stdarg ):
#include <stdio.h>
#include <stdarg.h>

int sum(int count, ...) {


va_list args;
va_start(args, count);

int total = 0;
for (int i = 0; i < count; i++) {
total += va_arg(args, int);
}

va_end(args);
return total;
}

int main() {
printf("%d\n", sum(3, 1, 2, 3));
}

C++ (using variadic templates):


#include <iostream>
using namespace std;

template<typename... Args>
int sum(Args... args) {
return (args + ...); // Fold expression (C++17)
}

int main() {
cout << sum(1, 2, 3) << endl;
}

https://md2pdf.netlify.app 34/37
16/11/2024, 11:01 md2pdf - Markdown to PDF

Python ( *args ):
def sum(*args):
return sum(args)

print(sum(1, 2, 3))

14. Recursion Example


Problem:
Write a recursive function to calculate the factorial of a number in C, C++, and Python. Compare
how recursion works across these languages.
Solution:
C:
#include <stdio.h>

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

int main() {
printf("%d\n", factorial(5));
}

C++:
#include <iostream>
using namespace std;

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

int main() {
cout << factorial(5) << endl;
}

Python:
https://md2pdf.netlify.app 35/37
16/11/2024, 11:01 md2pdf - Markdown to PDF

def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)

print(factorial(5))

15. Lambda Functions


Problem:
Write a lambda function to add two numbers in C++, Python and compare this with how
anonymous functions are handled in C.
Solution:
C++ Lambda Function:
#include<iostream>
using namespace std;

int main(){
auto add=[](int x,int y){return x+y;};
cout<<add(2 ,3)<<endl;
}

Python Lambda Function:


add=lambda x,y:x+y
print(add(2 ,3))

C Anonymous Functions:
C does not have built-in support for lambda or anonymous functions like Python or C++. You
would need to use function pointers or macros to achieve similar behavior.

Generic Comparison Questions


16. Compilation vs Interpretation
C/C++: Both are compiled languages. The code is converted into machine code before
execution.
Python: Interpreted language where code is executed line by line at runtime by an interpreter.
https://md2pdf.netlify.app 36/37
17. Memory Safety
16/11/2024, 11:01 md2pdf - Markdown to PDF

C/C++: Manual memory management using malloc/free or new/delete . This can lead to
issues like memory leaks or buffer overflows if not handled carefully.
Python: Automatic garbage collection manages memory safely without manual intervention.
18. Speed/Performance
Generally:
C/C++: Faster due to direct compilation into machine code and low-level control over
memory.
Python: Slower compared to C/C++ due to its interpreted nature and dynamic typing but
can be optimized using libraries like NumPy or through integration with C/C++ code.
19. Type Systems
C/C++: Statically typed languages where types must be declared explicitly.
Python: Dynamically typed language where types are inferred at runtime.
20. Standard Libraries
C/C++: Both have extensive standard libraries but require more manual work for common tasks
like file handling or networking.
Python: Comes with a rich standard library that simplifies many tasks such as file handling
( os , io ), networking ( socket , requests ), etc., making it more suitable for rapid
development.

https://md2pdf.netlify.app 37/37

You might also like