Basics of C Programming
- What is C programming language?
- C is a high-level, general-purpose programming language that was developed by Dennis Ritchie at Bell Labs in 1972.
- What are the key features of the C language?
- Key features include simplicity, efficiency, portability, and flexibility. It also allows low-level memory access and supports structured programming.
- What is a compiler in C?
- A compiler is a program that translates C code into machine code that can be executed by a computer.
- What is the difference between a compiler and an interpreter?
- A compiler translates the entire code at once and creates an executable file, while an interpreter translates code line-by-line and executes it directly.
- What is a syntax error in C?
- A syntax error occurs when the code violates the grammatical rules of the C language.
- What is a variable in C?
- A variable is a storage location identified by a name that holds data which can be modified during program execution.
- What are the basic data types in C?
- Basic data types include
int
,char
,float
, anddouble
.
- Basic data types include
- What is a constant in C?
- A constant is a value that cannot be altered during the execution of the program.
- What is the purpose of the
main()
function in C?- The
main()
function is the entry point of any C program. Execution starts from themain()
function.
- The
- How do you declare a variable in C?
- Variables are declared by specifying the data type followed by the variable name, e.g.,
int a;
.
- Variables are declared by specifying the data type followed by the variable name, e.g.,
Control Structures
- What is an if statement?
- An
if
statement is a control structure used to execute a block of code if a specified condition is true.
- An
- What is an else statement?
- An
else
statement is used to execute a block of code if the correspondingif
condition is false.
- An
- What is a switch statement?
- A
switch
statement allows a variable to be tested against a list of values, each with its own code block.
- A
- What is a loop in C?
- A loop is a control structure that repeats a block of code while a condition is true.
- What is a for loop?
- A
for
loop is used to execute a block of code a specific number of times.
- A
- What is a while loop?
- A
while
loop executes a block of code as long as a specified condition is true.
- A
- What is a do-while loop?
- A
do-while
loop executes a block of code once before checking the condition, and then it repeats the loop as long as the condition is true.
- A
- What is a break statement?
- A
break
statement terminates the nearest enclosing loop orswitch
statement.
- A
- What is a continue statement?
- A
continue
statement skips the remaining code inside the current loop iteration and starts the next iteration.
- A
- How do you implement nested loops in C?
- Nested loops are implemented by placing one loop inside the body of another loop.
Functions
- What is a function in C?
- A function is a block of code that performs a specific task, can be called by its name, and can be reused.
- What is the syntax for defining a function?
- The syntax is:
return_type function_name(parameters) { // body }
.
- The syntax is:
- What is a return type in a function?
- The return type specifies the type of value that the function returns.
- What are function parameters?
- Function parameters are variables passed to the function to use in its operations.
- What is a function prototype?
- A function prototype declares a function’s name, return type, and parameters to the compiler before its actual definition.
- What is the difference between a function declaration and definition?
- A function declaration specifies the function’s name, return type, and parameters without the body, while the definition includes the actual body of the function.
- What is recursion in C?
- Recursion is a process where a function calls itself directly or indirectly.
- What are the advantages of using functions?
- Advantages include code reusability, modularity, easier debugging, and improved readability.
- How do you call a function in C?
- A function is called by using its name followed by parentheses containing any required arguments, e.g.,
function_name(arguments);
.
- A function is called by using its name followed by parentheses containing any required arguments, e.g.,
- What is a void function?
- A
void
function does not return any value.
- A
Arrays and Strings
- What is an array in C?
- An array is a collection of elements of the same type stored in contiguous memory locations.
- How do you declare an array?
- An array is declared by specifying the data type, the array name, and the size, e.g.,
int arr[10];
.
- An array is declared by specifying the data type, the array name, and the size, e.g.,
- What is the index of an array?
- The index is the position of an element in the array, starting from 0.
- How do you initialize an array?
- An array can be initialized at the time of declaration, e.g.,
int arr[3] = {1, 2, 3};
.
- An array can be initialized at the time of declaration, e.g.,
- What is a multidimensional array?
- A multidimensional array is an array of arrays, e.g., a two-dimensional array is like a matrix.
- How do you declare a two-dimensional array?
- A two-dimensional array is declared as
data_type array_name[rows][columns];
, e.g.,int matrix[3][4];
.
- A two-dimensional array is declared as
- What is a string in C?
- A string is an array of characters terminated by a null character
\0
.
- A string is an array of characters terminated by a null character
- How do you declare a string?
- A string is declared as
char str[size];
or initialized directly aschar str[] = "text";
.
- A string is declared as
- What functions are used for string manipulation in C?
- Common string functions include
strlen()
,strcpy()
,strcat()
,strcmp()
, andstrstr()
.
- Common string functions include
- What is the difference between
char str[]
andchar *str
?char str[]
declares an array of characters, whilechar *str
declares a pointer to a character.
Pointers
- What is a pointer in C?
- A pointer is a variable that stores the memory address of another variable.
- How do you declare a pointer?
- A pointer is declared by specifying the data type followed by an asterisk and the pointer name, e.g.,
int *ptr;
.
- A pointer is declared by specifying the data type followed by an asterisk and the pointer name, e.g.,
- What is the purpose of the
&
operator?- The
&
operator is used to get the address of a variable.
- The
- What is the purpose of the
*
operator?- The
*
operator is used to dereference a pointer, i.e., to access the value stored at the address held by the pointer.
- The
- What is a NULL pointer?
- A NULL pointer is a pointer that does not point to any valid memory location.
- How do you assign an address to a pointer?
- You assign an address to a pointer using the address-of operator, e.g.,
ptr = &variable;
.
- You assign an address to a pointer using the address-of operator, e.g.,
- What is pointer arithmetic?
- Pointer arithmetic involves operations like incrementing, decrementing, and scaling pointers to navigate through memory locations.
- What is the difference between
int *ptr
andint **ptr
?int *ptr
is a pointer to an integer, whileint **ptr
is a pointer to a pointer to an integer.
- What is a function pointer?
- A function pointer is a pointer that points to a function’s address and can be used to call the function.
- How do you pass a pointer to a function?
- You pass a pointer to a function by specifying the pointer type in the function’s parameter list, e.g.,
void function(int *ptr);
.
- You pass a pointer to a function by specifying the pointer type in the function’s parameter list, e.g.,
Structures and Unions
- What is a structure in C?
- A structure is a user-defined data type that groups related variables of different data types.
- How do you define a structure?
- A structure is defined using the
struct
keyword followed by the structure name and body, e.g.,struct Person { char name[50]; int age; };
.
- A structure is defined using the
- How do you declare a structure variable?
- A structure variable is declared by specifying the structure type followed by the variable name, e.g.,
struct Person person1;
.
- A structure variable is declared by specifying the structure type followed by the variable name, e.g.,
- How do you access structure members?
- Structure members are accessed using the dot operator, e.g.,
person1.age
.
- Structure members are accessed using the dot operator, e.g.,
- What is the purpose of the
typedef
keyword?- The
typedef
keyword is used to create an alias for a data type, including structures.
- The
- What is a union in C?
- A union is a user-defined data type that allows storing different data types in the same memory location.
- How do you define a union?
- A union is defined using the
union
keyword, similar to structures, e.g.,union Data { int i; float f; char str[20]; };
.
- A union is defined using the
- How do you declare a union variable?
- A union variable is declared by specifying the union type followed by the variable name, e.g.,
union Data data1;
.
- A union variable is declared by specifying the union type followed by the variable name, e.g.,
- What is the difference between a structure and a union?
- In a structure, each member has its own storage location, whereas in a union, all members share the same memory location.
- How do you access union members?
- Union members are accessed using the dot operator, e.g.,
data1.i
.
- Union members are accessed using the dot operator, e.g.,
Dynamic Memory Allocation
- What is dynamic memory allocation?
- Dynamic memory allocation is the process of allocating and freeing memory during the runtime using pointers.
- What functions are used for dynamic memory allocation in C?
- Functions include
malloc()
,calloc()
,realloc()
, andfree()
.
- Functions include
- What does the
malloc()
function do?- The
malloc()
function allocates a specified number of bytes and returns a pointer to the allocated memory.
- The
- How do you use the
malloc()
function?malloc()
is used as follows:ptr = (cast_type*) malloc(size);
.
- What is the
calloc()
function?- The
calloc()
function allocates memory for an array of elements, initializes all bytes to zero, and returns a pointer to the allocated memory.
- The
- How do you use the
calloc()
function?calloc()
is used as follows:ptr = (cast_type*) calloc(num_elements, element_size);
.
- What is the
realloc()
function?- The
realloc()
function changes the size of previously allocated memory block and returns a pointer to the reallocated memory.
- The
- How do you use the
realloc()
function?realloc()
is used as follows:ptr = (cast_type*) realloc(ptr, new_size);
.
- What is the
free()
function?- The
free()
function deallocates previously allocated memory to avoid memory leaks.
- The
- How do you use the
free()
function?free()
is used as follows:free(ptr);
.
File I/O
- What is file I/O in C?
- File I/O refers to the operations of reading from and writing to files.
- How do you open a file in C?
- You open a file using the
fopen()
function, which returns a file pointer.
- You open a file using the
- What are the different modes to open a file?
- Modes include “r” (read), “w” (write), “a” (append), “r+” (read/update), “w+” (write/update), and “a+” (append/update).
- What is the syntax for opening a file?
- The syntax is:
FILE *file_ptr = fopen("filename", "mode");
.
- The syntax is:
- How do you close a file?
- A file is closed using the
fclose()
function, e.g.,fclose(file_ptr);
.
- A file is closed using the
- What is the purpose of the
fprintf()
function?fprintf()
is used to write formatted output to a file.
- How do you use the
fprintf()
function?fprintf()
is used as follows:fprintf(file_ptr, "format", data);
.
- What is the
fscanf()
function?fscanf()
is used to read formatted input from a file.
- How do you use the
fscanf()
function?fscanf()
is used as follows:fscanf(file_ptr, "format", &data);
.
- What is the
fgets()
function?fgets()
is used to read a string from a file.
- How do you use the
fgets()
function?fgets()
is used as follows:fgets(buffer, size, file_ptr);
.
- What is the
fputs()
function?fputs()
is used to write a string to a file.
- How do you use the
fputs()
function?fputs()
is used as follows:fputs(string, file_ptr);
.
- What is the
fseek()
function?fseek()
is used to move the file pointer to a specific location within the file.
- How do you use the
fseek()
function?fseek()
is used as follows:fseek(file_ptr, offset, origin);
.
- What is the
ftell()
function?ftell()
returns the current position of the file pointer.
- How do you use the
ftell()
function?ftell()
is used as follows:long pos = ftell(file_ptr);
.
- What is the
rewind()
function?rewind()
sets the file pointer to the beginning of the file.
- How do you use the
rewind()
function?rewind()
is used as follows:rewind(file_ptr);
.
Preprocessor Directives
- What is a preprocessor directive in C?
- Preprocessor directives are commands that are executed by the preprocessor before the compilation of the code begins.
- What is the
#include
directive?- The
#include
directive is used to include the contents of a file or library in the program.
- The
- How do you include a standard library header file?
- Use angle brackets, e.g.,
#include <stdio.h>
.
- Use angle brackets, e.g.,
- How do you include a user-defined header file?
- Use double quotes, e.g.,
#include "myheader.h"
.
- Use double quotes, e.g.,
- What is the
#define
directive?- The
#define
directive is used to define macros or constants.
- The
- How do you define a macro?
- Use
#define
followed by the macro name and replacement text, e.g.,#define PI 3.14
.
- Use
- What is a macro with arguments?
- A macro with arguments is a macro that takes parameters, e.g.,
#define SQUARE(x) ((x) * (x))
.
- A macro with arguments is a macro that takes parameters, e.g.,
- What is the
#undef
directive?- The
#undef
directive is used to undefine a macro.
- The
- How do you use the
#undef
directive?- Use
#undef
followed by the macro name, e.g.,#undef PI
.
- Use
- What is the
#if
directive?- The
#if
directive is used to include code based on a condition.
- The
- What is the
#ifdef
directive? – The#ifdef
directive is used to check if a macro is defined.
Advanced Topics
- What is a pointer to a function in C? – A pointer to a function points to the address of a function and can be used to call the function.
- How do you declare a pointer to a function? – Syntax:
return_type (*pointer_name)(parameter_list);
e.g.,int (*func_ptr)(int, int);
. - What are command-line arguments? – Command-line arguments are parameters passed to the program at the time of execution.
- How do you access command-line arguments in C? – Using
int main(int argc, char *argv[])
, whereargc
is the argument count andargv
is the argument vector. - What is a static variable? – A static variable retains its value between function calls and has file scope if defined outside a function.
- How do you declare a static variable? – Use the
static
keyword, e.g.,static int count;
. - What is a register variable? – A register variable is stored in a CPU register for faster access.
- How do you declare a register variable? – Use the
register
keyword, e.g.,register int counter;
. - What is an external variable? – An external variable is declared outside of any function and is accessible to all functions within the file.
- How do you declare an external variable? – Use the
extern
keyword in another file to access it, e.g.,extern int number;
.
Error Handling
- What is error handling in C? – Error handling refers to the process of anticipating, detecting, and responding to errors in the program.
- What is a runtime error? – A runtime error occurs during the execution of the program, such as division by zero or accessing an invalid memory location.
- How do you handle errors in C? – Using error codes, return values, and the
errno
variable. - What is the
errno
variable? –errno
is a global variable set by system calls and library functions in case of an error to indicate what went wrong. - How do you use the
errno
variable? – Include<errno.h>
and check the value oferrno
after a function call. - What is the
perror()
function? –perror()
prints a descriptive error message tostderr
. - How do you use the
perror()
function? –perror()
is used as follows:perror("Error message");
. - What is the
strerror()
function? –strerror()
returns a pointer to the textual representation of the currenterrno
value. - How do you use the
strerror()
function? –strerror()
is used as follows:printf("%s", strerror(errno));
. - What is the
exit()
function? –exit()
terminates the program and can return an exit status to the operating system.
Miscellaneous
- What is a bitwise operator? – Bitwise operators perform operations on the binary representations of integers.
- What are the common bitwise operators in C? – Common operators include
&
(AND),|
(OR),^
(XOR),~
(NOT),<<
(left shift), and>>
(right shift). - How do you perform a bitwise AND operation? – Use the
&
operator, e.g.,result = a & b;
. - How do you perform a bitwise OR operation? – Use the
|
operator, e.g.,result = a | b;
. - How do you perform a bitwise XOR operation? – Use the
^
operator, e.g.,result = a ^ b;
. - How do you perform a bitwise NOT operation? – Use the
~
operator, e.g.,result = ~a;
. - What is a left shift operation? – A left shift operation shifts bits to the left and fills the rightmost bits with zeros.
- How do you perform a left shift operation? – Use the
<<
operator, e.g.,result = a << 1;
. - What is a right shift operation? – A right shift operation shifts bits to the right and fills the leftmost bits with zeros or the sign bit (in case of signed integers).
- How do you perform a right shift operation? – Use the
>>
operator, e.g.,result = a >> 1;
.
Advanced Data Structures
- What is a linked list? – A linked list is a data structure consisting of nodes, where each node contains data and a pointer to the next node.
- What are the types of linked lists? – Types include singly linked list, doubly linked list, and circular linked list.
- How do you create a node in a linked list? – A node is created using a
struct
that contains data and a pointer to the next node. - What is a stack? – A stack is a linear data structure that follows the Last In First Out (LIFO) principle.
- What are the basic operations of a stack? – Basic operations include push (insert), pop (delete), and peek (retrieve top element).
- What is a queue? – A queue is a linear data structure that follows the First In First Out (FIFO) principle.
- What are the basic operations of a queue? – Basic operations include enqueue (insert), dequeue (delete), and front (retrieve front element).
- What is a binary tree? – A binary tree is a hierarchical data structure where each node has at most two children, referred to as left and right.
- What is a binary search tree (BST)? – A BST is a binary tree in which the left child contains values less than the parent node, and the right child contains values greater than the parent node.
- What are the common tree traversal methods? – Common methods include in-order, pre-order, and post-order traversal.
Concurrency and Multithreading
- What is concurrency in C? – Concurrency refers to the ability to run multiple parts of a program simultaneously.
- What is a thread in C? – A thread is a lightweight process that can run concurrently with other threads within the same program.
- What library is commonly used for threading in C? – The POSIX Threads (pthreads) library.
- How do you create a thread using pthreads? – Use
pthread_create()
, e.g.,pthread_create(&thread_id, NULL, function, arg);
. - What is the
pthread_join()
function? –pthread_join()
waits for a thread to terminate. - What is a mutex? – A mutex is a synchronization primitive used to prevent multiple threads from accessing a shared resource simultaneously.
- How do you initialize a mutex? – Use
pthread_mutex_init()
, e.g.,pthread_mutex_init(&mutex, NULL);
. - What is a deadlock? – A deadlock is a situation where two or more threads are blocked forever, each waiting for the other to release a resource.
- How do you avoid deadlocks? – By using techniques like resource ordering, avoiding circular wait, and using timeout mechanisms.
- What is a condition variable in pthreads? – A condition variable is used to block a thread until a particular condition is met.
More Topics
- What is type casting in C? – Type casting is the conversion of one data type to another.
- How do you perform explicit type casting? – By using the cast operator, e.g.,
int x = (int) 3.14;
. - What is implicit type casting? – Implicit type casting is automatically performed by the compiler when compatible types are used.
- What is a macro? – A macro is a fragment of code defined using the
#define
directive that can be inserted wherever its name appears. - What is the difference between
#define
andconst
? –#define
is a preprocessor directive, whileconst
is a keyword to define constant variables with type checking. - What is an enumeration in C? – An enumeration is a user-defined data type consisting of named integer constants.
- How do you define an enumeration? – Using the
enum
keyword, e.g.,enum Days {Sunday, Monday, Tuesday};
. - What is the size of an
int
data type? – The size of anint
is platform-dependent, typically 2 or 4 bytes. - What is a segmentation fault? – A segmentation fault occurs when a program tries to access an invalid memory location.
- What is a buffer overflow? – A buffer overflow occurs when data exceeds the storage capacity of a buffer, leading to adjacent memory corruption.
Input/Output
- What is the
printf()
function? –printf()
is used to print formatted output to the standard output (stdout). - What is the
scanf()
function? –scanf()
is used to read formatted input from the standard input (stdin). - How do you print a single character using
printf()
? – Use%c
format specifier, e.g.,printf("%c", ch);
. - How do you print a string using
printf()
? – Use%s
format specifier, e.g.,printf("%s", str);
. - How do you read an integer using
scanf()
? – Use%d
format specifier, e.g.,scanf("%d", &num);
. - What is the
putchar()
function? –putchar()
writes a single character to stdout. - What is the
getchar()
function? –getchar()
reads a single character from stdin. - What is the
puts()
function? –puts()
writes a string to stdout and appends a newline character. - What is the
gets()
function? –gets()
reads a string from stdin until a newline character or EOF. - Why should
gets()
be avoided? –gets()
should be avoided due to the risk of buffer overflow.
Advanced Memory Management
- What is memory leak? – A memory leak occurs when allocated memory is not freed, causing the program to consume more memory over time.
- How do you avoid memory leaks? – By ensuring that every allocated memory is properly freed using
free()
. - What is the stack memory? – Stack memory is a region of memory used for static memory allocation, function calls, and local variables.
- What is heap memory? – Heap memory is a region of memory used for dynamic memory allocation.
- What is the difference between stack and heap memory? – Stack memory is limited, automatically managed, and faster, while heap memory is larger, manually managed, and slower.
- What is fragmentation? – Fragmentation is the inefficient use of memory that leads to wasted space and reduced performance.
- What is the difference between internal and external fragmentation? – Internal fragmentation occurs when allocated memory exceeds the requested memory, while external fragmentation occurs when free memory is scattered and non-contiguous.
- How do you minimize fragmentation? – By using memory allocation techniques like compaction, paging, and segmentation.
Algorithms and Data Structures
- What is an algorithm? – An algorithm is a step-by-step procedure for solving a problem or performing a task.
- What are the characteristics of a good algorithm? – Characteristics include correctness, efficiency, clarity, and maintainability.
- What is Big O notation? – Big O notation is used to describe the upper bound of the time complexity of an algorithm.
- What are common time complexities in Big O notation? – Common time complexities include O(1), O(n), O(log n), O(n log n), O(n^2).
- What is the difference between time complexity and space complexity? – Time complexity measures the time an algorithm takes to run, while space complexity measures the memory it uses.
- What is a recursive function? – A recursive function is a function that calls itself.
- What is base case in recursion? – The base case is the condition under which the recursive calls stop.
- What is a sorting algorithm? – A sorting algorithm arranges elements in a specific order (ascending or descending).
- What are common sorting algorithms? – Common sorting algorithms include bubble sort, selection sort, insertion sort, merge sort, and quick sort.
- What is binary search? – Binary search is a search algorithm that finds the position of a target value within a sorted array.
- How does binary search work? – Binary search repeatedly divides the search interval in half and compares the target value with the middle element until it finds the target or the interval is empty.
- What is a hash table? – A hash table is a data structure that maps keys to values using a hash function.
- What is a hash function? – A hash function converts a given key into an index in the hash table.
- What is collision in a hash table? – A collision occurs when two keys are hashed to the same index.
- How do you handle collisions in a hash table? – Collision handling techniques include chaining and open addressing.
- What is a graph? – A graph is a data structure consisting of vertices (nodes) connected by edges (links).
- What are the types of graphs? – Types include directed, undirected, weighted, and unweighted graphs.
- What is a depth-first search (DFS)? – DFS is a graph traversal algorithm that explores as far as possible along each branch before backtracking.
- What is a breadth-first search (BFS)? – BFS is a graph traversal algorithm that explores all nodes at the present depth before moving on to nodes at the next depth level.
- What is a tree? – A tree is a hierarchical data structure with a root node and child nodes, where each child node can have its own child nodes.
- What is a binary heap? – A binary heap is a complete binary tree where the value of each node is greater than or equal to (max-heap) or less than or equal to (min-heap) the values of its children.
- What is dynamic programming? – Dynamic programming is an optimization technique that solves complex problems by breaking them down into simpler subproblems and storing the results of subproblems to avoid redundant computations.