Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
6 views87 pages

Data Structures

The document is a collection of multiple-choice questions (MCQs) covering various topics in computer science, including algorithms, data structures, flowcharts, C programming language, control statements, functions, and structures. Each question is followed by the correct answer and an explanation. The content is designed to test knowledge and understanding of fundamental concepts in programming and computer science.

Uploaded by

kongariuma4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views87 pages

Data Structures

The document is a collection of multiple-choice questions (MCQs) covering various topics in computer science, including algorithms, data structures, flowcharts, C programming language, control statements, functions, and structures. Each question is followed by the correct answer and an explanation. The content is designed to test knowledge and understanding of fundamental concepts in programming and computer science.

Uploaded by

kongariuma4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 87

1. What is the time complexity of binary search in a sorted array?

A) O(n)
B) O(log n)
C) O(n log n)
D) O(1)

Answer: B) O(log n)
Explanation: Binary search divides the array into half each time, leading to a logarithmic
time complexity.

🧠 2. Which of the following data structures is used in Breadth-First Search


(BFS)?

A) Stack
B) Queue
C) Priority Queue
D) Hash Table

Answer: B) Queue
Explanation: BFS explores nodes level by level using a queue.

🧠 3. What is the worst-case time complexity of Quick Sort?

A) O(n log n)
B) O(n^2)
C) O(n)
D) O(log n)

Answer: B) O(n²)
Explanation: The worst-case occurs when the pivot selection leads to unbalanced partitions.

🧠 4. Which sorting algorithm is the best for nearly sorted arrays?

A) Merge Sort
B) Bubble Sort
C) Insertion Sort
D) Quick Sort

Answer: C) Insertion Sort


Explanation: Insertion sort is efficient for small or nearly sorted datasets.
🧠 5. What data structure is used for implementing recursion?

A) Queue
B) Stack
C) Linked List
D) Tree

Answer: B) Stack
Explanation: Function calls are stored in the call stack during recursion.

🧠 6. Which of the following algorithms uses a divide-and-conquer approach?

A) Bubble Sort
B) Insertion Sort
C) Merge Sort
D) Linear Search

Answer: C) Merge Sort


Explanation: Merge Sort divides the array and recursively sorts the parts.

🧠 7. In Dijkstra’s algorithm, which data structure is commonly used to find


the minimum distance?

A) Stack
B) Queue
C) Min Heap / Priority Queue
D) Hash Map

Answer: C) Min Heap / Priority Queue


Explanation: Dijkstra's algorithm needs efficient access to the minimum distance node.

🧠 8. Which traversal is used in Depth-First Search of a graph?

A) Level Order
B) Preorder
C) Inorder
D) Postorder

Answer: B) Preorder
Explanation: DFS uses preorder traversal using stack (either explicit or via recursion).
🧠 9. Which of the following problems can be solved using Dynamic
Programming?

A) Tower of Hanoi
B) Binary Search
C) Longest Common Subsequence
D) Depth First Search

Answer: C) Longest Common Subsequence


Explanation: DP is used where subproblems overlap and have optimal substructure, like
LCS.

🧠 10. What is the space complexity of merge sort?

A) O(1)
B) O(log n)
C) O(n)
D) O(n log n)

Answer: C) O(n)
Explanation: Merge sort uses additional memory for temporary arrays.

Flowchart in C – MCQs with Answers

1. What does a diamond symbol in a flowchart represent?

A) Start/End
B) Input/Output
C) Process
D) Decision

✅ Answer: D) Decision
Explanation: Diamond symbols are used for decision-making or conditional branching (like
if or switch in C).

2. Which symbol in a flowchart is used to denote input or output operations?

A) Circle
B) Parallelogram
C) Rectangle
D) Diamond
✅ Answer: B) Parallelogram
Explanation: A parallelogram represents either input (e.g., scanf) or output (e.g., printf) in
a program.

3. In a flowchart, what does a rectangle represent?

A) Loop
B) Process
C) Decision
D) Connector

✅ Answer: B) Process
Explanation: A rectangle is used to represent a processing step like a computation (a = b +
c).

4. Which of the following best describes the flowchart equivalent of an if


statement in C?

A) Oval
B) Rectangle
C) Diamond
D) Line Connector

✅ Answer: C) Diamond
Explanation: An if condition checks a decision, which is shown using a diamond shape.

5. What shape in a flowchart indicates the beginning or end of a program?

A) Rectangle
B) Parallelogram
C) Diamond
D) Oval

✅ Answer: D) Oval
Explanation: An oval denotes the Start or End (Terminator) of a flowchart.

6. In C, which control structure is most closely related to decision boxes in a


flowchart?

A) for loop
B) if-else statement
C) printf
D) scanf

✅ Answer: B) if-else statement


Explanation: Decision boxes reflect logic branching, which is done via if, else, or switch
in C.

7. A flowchart that contains a loop will include which type of arrow pattern?

A) Only downward arrows


B) Backward arrows
C) Diagonal arrows
D) No arrows

✅ Answer: B) Backward arrows


Explanation: Loops are represented by arrows going back to a previous step (usually from
the bottom of a loop to the decision box).

8. Which of the following is not a benefit of using flowcharts?

A) Easy to understand logic


B) Helps in debugging
C) Automatically generates code
D) Acts as a documentation tool

✅ Answer: C) Automatically generates code


Explanation: Flowcharts aid logic understanding, but don’t directly generate code.

9. In a C program, which element of a flowchart corresponds to a for loop?

A) Start
B) Input
C) Decision and Process
D) End

✅ Answer: C) Decision and Process


Explanation: A for loop involves a decision (condition check) and a process (repeated
execution).

10. What is the primary purpose of a flowchart in relation to C


programming?
A) To compile code
B) To represent program flow visually
C) To execute the logic
D) To debug hardware

✅ Answer: B) To represent program flow visually


Explanation: Flowcharts help in visualizing the logical sequence of operations before
coding.

C Programming Language – MCQs with Answers

1. Who is the founder of C language?

A) Bjarne Stroustrup
B) Dennis Ritchie
C) James Gosling
D) Ken Thompson

✅ Answer: B) Dennis Ritchie


Explanation: Dennis Ritchie developed C at Bell Labs in the early 1970s.

2. What is the correct syntax to declare a variable in C?

A) int x;
B) integer x;
C) x int;
D) declare int x;

✅ Answer: A) int x;
Explanation: In C, variables are declared as data_type variable_name;.

3. Which of the following is the correct format specifier for float in C?

A) %d
B) %f
C) %c
D) %lf

✅ Answer: B) %f
Explanation: %f is used to print float values in printf.

4. What is the output of: printf("%d", 10 + 5 * 2);


A) 20
B) 25
C) 30
D) 15

✅ Answer: A) 20
Explanation: According to precedence, multiplication happens first. So, 5 * 2 = 10; then
10 + 10 = 20.

5. Which header file is required for using printf and scanf?

A) conio.h
B) stdlib.h
C) stdio.h
D) string.h

✅ Answer: C) stdio.h
Explanation: printf and scanf are declared in stdio.h.

6. What is the size of int on a 32-bit system?

A) 8 bytes
B) 4 bytes
C) 2 bytes
D) 1 byte

✅ Answer: B) 4 bytes
Explanation: On a 32-bit system, int typically occupies 4 bytes.

7. Which keyword is used to define a constant in C?

A) const
B) define
C) constant
D) final

✅ Answer: A) const
Explanation: const defines a constant variable (e.g., const int x = 10;).

8. Which of the following is a loop structure in C?


A) if
B) for
C) switch
D) goto

✅ Answer: B) for
Explanation: for is a loop used for repeated execution.

9. Which operator is used to access the value at the address in C?

A) &
B) *
C) @
D) %

✅ **Answer: B) *
Explanation: * is the dereference operator used with pointers.

10. Which of the following is used to comment a single line in C?

A) // comment
B) /* comment */
C) # comment
D) <!-- comment -->

✅ Answer: A) // comment
Explanation: // is used for single-line comments in C99 and later.

Control Statements in C – MCQs with Answers

1. Which of the following is a selection (decision-making) control statement in


C?

A) for
B) while
C) if
D) do-while

✅ Answer: C) if
Explanation: The if statement allows branching based on a condition.

2. What is the output of the following code?


c
CopyEdit
int x = 5;
if (x == 5)
printf("Five");
else
printf("Not Five");

A) Five
B) Not Five
C) Error
D) No output

✅ Answer: A) Five
Explanation: The condition x == 5 is true, so "Five" is printed.

3. Which of the following loops is guaranteed to execute at least once?

A) for
B) while
C) do-while
D) None

✅ Answer: C) do-while
Explanation: do-while executes the loop body before checking the condition.

4. Which keyword is used to terminate a loop prematurely?

A) stop
B) return
C) exit
D) break

✅ Answer: D) break
Explanation: break is used to exit a loop or switch statement early.

5. What is the correct syntax of a for loop in C?

A) for (i = 0; i < 10; i++)


B) for (i < 10; i++)
C) for i = 0 to 10
D) foreach (i in range(10))
✅ Answer: A) for (i = 0; i < 10; i++)
Explanation: That is the correct format for a for loop in C.

6. Which of the following statements is used to skip the current iteration in a


loop?

A) break
B) exit
C) continue
D) return

✅ Answer: C) continue
Explanation: continue skips the rest of the current iteration and jumps to the loop
condition.

7. Which control structure is best for choosing between many options (e.g.,
days of the week)?

A) if-else ladder
B) switch
C) for loop
D) while loop

✅ Answer: B) switch
Explanation: switch is best for handling multiple constant values like menu options.

8. What will be the output?


c
CopyEdit
int i = 0;
while (i < 3) {
printf("%d ", i);
i++;
}

A) 0 1 2 3
B) 0 1 2
C) 1 2 3
D) Infinite loop

✅ Answer: B) 0 1 2
Explanation: The loop runs while i < 3, so it prints 0, 1, 2.
9. Which control statement causes the control to jump unconditionally?

A) continue
B) goto
C) break
D) return

✅ Answer: B) goto
Explanation: goto jumps to a labeled part of the code.

10. What is the purpose of the default keyword in a switch statement?

A) To stop the loop


B) To skip a case
C) To define fallback when no case matches
D) To initialize a variable

✅ Answer: C) To define fallback when no case matches


Explanation: default runs if none of the case values match.

Functions in C – MCQs with Answers

1. Which of the following is the correct way to declare a function in C?

A) function int myFunc()


B) int myFunc();
C) declare int myFunc();
D) int = myFunc();

✅ Answer: B) int myFunc();


Explanation: This is the correct way to declare a function that returns an int and takes no
arguments.

2. What is the default return type of a function in C if not specified (in older C
versions)?

A) void
B) int
C) float
D) double
✅ Answer: B) int
Explanation: In traditional C (before C99), if no return type is specified, it defaults to int.

3. How many times is a function executed in a C program?

A) Once
B) Depends on the number of function calls
C) Twice
D) Infinite times

✅ Answer: B) Depends on the number of function calls


Explanation: A function executes only when called.

4. What will the following function return?


c
CopyEdit
int sum(int a, int b) {
return a + b;
}

A) The difference of a and b


B) Nothing
C) The sum of a and b
D) Compilation error

✅ Answer: C) The sum of a and b


Explanation: The function returns a + b.

5. Which of the following is NOT a valid type of function in C?

A) Function with no arguments and no return value


B) Function with arguments and a return value
C) Function with no arguments and a return value
D) Function with no definition

✅ Answer: D) Function with no definition


Explanation: A function must be defined; otherwise, the program will not compile or link
correctly.

6. What is the keyword used to return a value from a function?


A) return
B) break
C) exit
D) continue

✅ Answer: A) return
Explanation: return is used to send a value back to the caller.

7. What is the scope of a variable declared inside a function?

A) Global
B) Local
C) External
D) Static

✅ Answer: B) Local
Explanation: Variables declared inside a function are local to that function.

8. Can a function call itself in C?

A) No
B) Only if static
C) Yes, it's called recursion
D) Only inside main()

✅ Answer: C) Yes, it's called recursion


Explanation: A function calling itself is a common practice called recursion.

9. What is the output of the following code?


c
CopyEdit
void hello() {
printf("Hello");
}

int main() {
hello();
return 0;
}

A) Hello
B) No output
C) Compilation error
D) main
✅ Answer: A) Hello
Explanation: The function hello() is called from main() and prints "Hello".

10. Which statement is true about function prototypes in C?

A) They are optional in all cases


B) They are used to define the function
C) They tell the compiler about the function's name, return type, and parameters
D) They allocate memory for functions

✅ Answer: C) They tell the compiler about the function's name, return type, and
parameters
Explanation: A prototype helps the compiler ensure proper function usage before its
definition.

Structures in C – MCQs with Answers

1. What is a structure in C?

A) A built-in data type


B) A loop structure
C) A user-defined data type
D) A type of array

✅ Answer: C) A user-defined data type


Explanation: A structure allows grouping variables of different data types under one name.

2. Which keyword is used to define a structure in C?

A) define
B) struct
C) union
D) class

✅ Answer: B) struct
Explanation: struct is the keyword used to define a structure.

3. Which of the following correctly defines a structure?

A) structure student { int roll; };


B) struct student { int roll; };
C) struct { int roll; } student;
D) struct student ( int roll; );

✅ Answer: B) struct student { int roll; };


Explanation: This is the correct syntax for defining a structure named student.

4. How do you access a structure member using a structure variable?

A) structure->member
B) structure.member
C) structure:member
D) structure#member

✅ Answer: B) structure.member
Explanation: The dot (.) operator is used to access members via a structure variable.

5. How do you access a structure member using a pointer to a structure?

A) ptr.member
B) ptr:member
C) ptr->member
D) ptr*member

✅ Answer: C) ptr->member
Explanation: The arrow (->) operator is used to access members through a structure pointer.

6. Can a structure in C contain another structure as a member?

A) No
B) Only in C++
C) Yes, it's called nested structure
D) Yes, but only pointers

✅ Answer: C) Yes, it's called nested structure


Explanation: Structures can contain other structures — this is called nesting.

7. What is the size of an empty structure in C?

A) 0
B) 1
C) Depends on the compiler
D) Cannot declare an empty structure

✅ Answer: D) Cannot declare an empty structure


Explanation: C does not allow structures with no members.

8. Which of the following allows creating variables during structure


declaration?

A) struct student;
B) struct student { int roll; } s1;
C) struct { int roll; } student;
D) student struct { int roll; };

✅ Answer: B) struct student { int roll; } s1;


Explanation: This declares a structure and creates a variable s1 of that structure.

9. What is the purpose of typedef with structures?

A) To define functions
B) To allocate memory
C) To rename structure types for simpler usage
D) To make structures global

✅ Answer: C) To rename structure types for simpler usage


Explanation: typedef allows giving a new name (alias) to a structure type.

10. What is the output of this code?


c
CopyEdit
struct Point {
int x, y;
};

int main() {
struct Point p = {10, 20};
printf("%d %d", p.x, p.y);
return 0;
}

A) 10 10
B) 20 10
C) 10 20
D) Error
✅ Answer: C) 10 20
Explanation: p.x = 10, p.y = 20; both values are printed.

Union in C – MCQs with Answers

1. What is a union in C?

A) A type of function
B) A user-defined data type
C) A type of array
D) A built-in variable type

✅ Answer: B) A user-defined data type


Explanation: union allows storing different data types in the same memory location.

2. Which keyword is used to define a union in C?

A) struct
B) union
C) enum
D) typedef

✅ Answer: B) union
Explanation: The union keyword is used to define a union type.

3. What is the difference between a struct and a union?

A) struct stores more data


B) union shares memory among members
C) struct can’t have arrays
D) union members are private

✅ Answer: B) union shares memory among members


Explanation: In a union, all members share the same memory; only one member can store a
value at a time.

4. How is memory allocated in a union?

A) Sum of sizes of all members


B) Memory equal to the largest member
C) 1 byte
D) Equal to number of members
✅ Answer: B) Memory equal to the largest member
Explanation: Union allocates memory equal to its largest member to ensure any one can be
stored.

5. Which of the following correctly defines a union?

A) union { int a; float b; } u1;


B) union u1 { int a, b; };
C) union u1 ( int a, float b );
D) union u1 int a; float b;

✅ Answer: A) union { int a; float b; } u1;


Explanation: This is correct syntax for defining and declaring a union variable u1.

6. If a union has an int (4 bytes) and a char (1 byte), how much memory will it
occupy?

A) 1 byte
B) 5 bytes
C) 4 bytes
D) 0 bytes

✅ Answer: C) 4 bytes
Explanation: Memory is allocated based on the size of the largest member (int in this case).

7. Can unions have pointers as members?

A) No
B) Yes
C) Only in C++
D) Only if static

✅ Answer: B) Yes
Explanation: Unions can have any valid C data type as members, including pointers.

8. What will this program output?


c
CopyEdit
#include <stdio.h>
union Data {
int i;
float f;
};

int main() {
union Data d;
d.i = 10;
d.f = 3.14;
printf("%d", d.i);
return 0;
}

A) 10
B) 3.14
C) Garbage value
D) Error

✅ Answer: C) Garbage value


Explanation: Assigning d.f overwrites d.i due to shared memory; so d.i gives
undefined/garbage output.

9. Can you use typedef with unions in C?

A) No
B) Yes
C) Only in structures
D) Only for arrays

✅ Answer: B) Yes
Explanation: typedef can be used to create aliases for union types just like with structs.

10. Which of the following is a limitation of unions in C?

A) Cannot store strings


B) Only one member can contain a value at any time
C) Cannot be passed to functions
D) Cannot contain other unions

✅ Answer: B) Only one member can contain a value at any time


Explanation: All members share the same memory; storing a new value overwrites the
previous.

File Handling in C – MCQs with Answers

1. Which header file is required for file operations in C?


A) stdlib.h
B) string.h
C) stdio.h
D) file.h

✅ Answer: C) stdio.h
Explanation: stdio.h includes standard file I/O functions like fopen(), fclose(), etc.

2. Which function is used to open a file in C?

A) fread()
B) fopen()
C) openfile()
D) create()

✅ Answer: B) fopen()
Explanation: fopen() is used to open a file and returns a FILE* pointer.

3. What does the mode "w" in fopen() do?

A) Opens a file for reading


B) Opens a file for writing (and erases contents)
C) Appends to the file
D) Reads and writes

✅ Answer: B) Opens a file for writing (and erases contents)


Explanation: "w" creates a new file or clears an existing one before writing.

4. What is the correct syntax to write a character to a file?

A) write(ch, fp);
B) putc(ch, fp);
C) fchar(ch, fp);
D) fputc(fp, ch);

✅ Answer: B) putc(ch, fp);


Explanation: putc() writes a character to the file pointed to by fp.

5. Which function is used to close a file?


A) endfile()
B) closefile()
C) fend()
D) fclose()

✅ Answer: D) fclose()
Explanation: fclose() closes a file and flushes any buffered output.

6. What does fscanf() do in C?

A) Scans files for viruses


B) Writes formatted data to a file
C) Reads formatted data from a file
D) Formats a file system

✅ Answer: C) Reads formatted data from a file


Explanation: fscanf() is used like scanf(), but reads from a file.

7. What type is returned by fopen()?

A) char*
B) int
C) FILE*
D) void*

✅ Answer: C) FILE*
Explanation: fopen() returns a pointer to a FILE object if successful; NULL otherwise.

8. Which file mode allows both reading and writing without truncating the
file?

A) "r"
B) "w"
C) "a"
D) "r+"

✅ Answer: D) "r+"
Explanation: "r+" opens an existing file for both reading and writing without deleting
content.
9. What does feof(fp) return when end of file is reached?

A) 1 (true)
B) -1
C) 0
D) NULL

✅ Answer: A) 1 (true)
Explanation: feof() returns non-zero when the end of the file has been reached.

10. Which function is used to read a string from a file?

A) fgets()
B) gets()
C) scanf()
D) fchar()

✅ Answer: A) fgets()
Explanation: fgets() reads a line or string from a file.

Pointers in C – MCQs with Answers

1. What is a pointer in C?

A) A variable that stores a data value


B) A variable that stores the address of another variable
C) A constant value
D) None of the above

✅ Answer: B) A variable that stores the address of another variable


Explanation: A pointer holds the memory address of another variable.

2. Which operator is used to get the address of a variable?

A) * (asterisk)
B) & (ampersand)
C) -> (arrow)
D) % (modulus)

✅ Answer: B) & (ampersand)


Explanation: The & operator returns the address of a variable.
3. Which operator is used to access the value at the address stored in a
pointer?

A) & (ampersand)
B) * (asterisk)
C) -> (arrow)
D) % (modulus)

✅ Answer: B) * (asterisk)
Explanation: The * operator is used to dereference a pointer.

4. What is the output of the following code?


c
CopyEdit
int a = 10;
int *p = &a;
printf("%d", *p);

A) Address of a
B) 10
C) Garbage value
D) Compilation error

✅ Answer: B) 10
Explanation: *p dereferences the pointer to give the value stored at a.

5. Which of the following declarations is correct for a pointer to an integer?

A) int p;
B) int *p;
C) int &p;
D) int p*;

✅ *Answer: B) int p;
Explanation: int *p; declares p as a pointer to an integer.

6. What happens if you increment a pointer?

A) The pointer moves to the next byte in memory


B) The pointer moves to the next element based on its data type size
C) Pointer value remains the same
D) Pointer becomes NULL
✅ Answer: B) The pointer moves to the next element based on its data type size
Explanation: Pointer arithmetic moves the pointer by the size of the data type it points to.

7. Which of the following is the correct way to declare a pointer to a pointer?

A) int **p;
B) int &*p;
C) int *&p;
D) int p**;

✅ **Answer: A) int p;
Explanation: int **p; declares a pointer to a pointer to an integer.

8. What does the following expression do?


c
CopyEdit
p = NULL;

A) Assigns zero to p
B) Assigns p an invalid address
C) Assigns a null pointer value to p
D) Dereferences p

✅ Answer: C) Assigns a null pointer value to p


Explanation: NULL means the pointer points to nothing.

9. Which operator is used to access members of a structure through a pointer?

A) . (dot)
B) -> (arrow)
C) & (ampersand)
D) * (asterisk)

✅ Answer: B) -> (arrow)


Explanation: The arrow operator accesses structure members via a pointer.

10. What is the output of the following code?


c
CopyEdit
int a = 5;
int *p = &a;
(*p)++;
printf("%d", a);

A) 5
B) 6
C) Garbage value
D) Compilation error

✅ Answer: B) 6
Explanation: (*p)++ increments the value pointed to by p, i.e., a.

Comprehensive C Programming MCQs with Answers

1. Which of the following is a valid identifier in C?

A) 1variable
B) _var123
C) var-1
D) int

Answer: B) _var123
Explanation: Identifiers cannot start with digits or contain special characters like -.
Keywords like int can't be identifiers.

2. What is the size of int in most 32-bit compilers?

A) 1 byte
B) 2 bytes
C) 4 bytes
D) 8 bytes

Answer: C) 4 bytes
Explanation: Usually, int occupies 4 bytes on 32-bit systems.

3. What will be the output of the following?


c
CopyEdit
printf("%d", sizeof(char));

A) 0
B) 1
C) 2
D) Compiler error
Answer: B) 1
Explanation: Size of char is always 1 byte.

4. Which of these is NOT a valid loop in C?

A) for
B) foreach
C) while
D) do-while

Answer: B) foreach
Explanation: C does not have a foreach loop.

5. What will be the output?


c
CopyEdit
int x = 5;
if(x = 0)
printf("True");
else
printf("False");

A) True
B) False
C) Compiler error
D) Garbage value

Answer: B) False
Explanation: x = 0 assigns 0 to x, which is false in condition.

6. What is recursion?

A) A loop inside another loop


B) A function calling itself
C) A function returning void
D) None of the above

Answer: B) A function calling itself


Explanation: Recursion is when a function calls itself.

7. How do you pass an array to a function in C?


A) By value
B) By reference (as a pointer)
C) By copying whole array
D) None of the above

Answer: B) By reference (as a pointer)


Explanation: Arrays decay to pointers when passed to functions.

8. Which operator is used to access members of a structure variable?

A) .
B) ->
C) *
D) &

Answer: A) .
Explanation: Dot operator accesses members of a structure variable.

9. What is the correct way to allocate memory dynamically in C?

A) malloc(size)
B) alloc(size)
C) new size
D) allocate(size)

Answer: A) malloc(size)
Explanation: malloc() dynamically allocates memory.

10. What does NULL represent in C?

A) An empty string
B) Zero integer
C) A null pointer
D) None of the above

Answer: C) A null pointer


Explanation: NULL means pointer points to nothing.

11. What does the keyword static mean inside a function?


A) Variable scope is global
B) Variable retains its value between function calls
C) Variable is constant
D) Variable is a pointer

Answer: B) Variable retains its value between function calls


Explanation: Static variables inside functions keep their value across calls.

12. Which file mode opens the file for appending in C?

A) "r"
B) "w"
C) "a"
D) "r+"

Answer: C) "a"
Explanation: "a" mode appends data to the end of the file.

13. What is the output of this code?


c
CopyEdit
int a = 10;
int *p = &a;
printf("%d", *p);

A) Address of a
B) 10
C) Garbage value
D) Error

Answer: B) 10
Explanation: *p dereferences pointer to get value 10.

14. Which of the following is NOT a valid storage class in C?

A) auto
B) register
C) static
D) dynamic

Answer: D) dynamic
Explanation: There is no dynamic storage class in C.
15. Which header file is required for using printf()?

A) stdlib.h
B) stdio.h
C) string.h
D) conio.h

Answer: B) stdio.h
Explanation: printf() is declared in stdio.h.

16. What is the default return type of a function if none is specified (in older
C)?

A) void
B) int
C) float
D) double

Answer: B) int
Explanation: Default return type is int in older C standards.

17. Which function is used to read a single character from a file?

A) getchar()
B) fgetc()
C) getc()
D) Both B and C

Answer: D) Both B and C


Explanation: Both fgetc() and getc() read a character from a file.

18. What is the result of this pointer arithmetic?


c
CopyEdit
int arr[5] = {1,2,3,4,5};
int *p = arr;
p++;

A) Points to arr[1]
B) Points to arr[0]
C) Points to garbage
D) Error

Answer: A) Points to arr[1]


Explanation: Incrementing pointer moves to next element based on type size.

19. What will happen if you use free() on a pointer not obtained via malloc()?

A) Program crashes
B) Memory leak
C) Undefined behavior
D) Nothing

Answer: C) Undefined behavior


Explanation: Freeing invalid pointers is undefined and may crash.

20. Which of the following is NOT true about arrays in C?

A) Size must be known at compile time (for static arrays)


B) Arrays can be passed to functions
C) Array name acts as a pointer to the first element
D) Array size can be changed at runtime

Answer: D) Array size can be changed at runtime


Explanation: Static arrays have fixed size; dynamic arrays require pointers and malloc.

Simple and Abstract Data Types in C – MCQs with Answers

1. Which of the following is NOT a simple data type in C?

A) int
B) float
C) struct
D) char

Answer: C) struct
Explanation: struct is an abstract (user-defined) data type, not a simple primitive type.

2. Which of these is the correct way to declare an integer variable?

A) int num;
B) float num;
C) char num;
D) struct num;

Answer: A) int num;


Explanation: int declares an integer variable.

3. What is the size of float data type on most systems?

A) 1 byte
B) 2 bytes
C) 4 bytes
D) 8 bytes

Answer: C) 4 bytes
Explanation: Typically, float occupies 4 bytes.

4. Which of the following is an example of an abstract data type?

A) int
B) float
C) union
D) char

Answer: C) union
Explanation: Unions are user-defined abstract data types.

5. What is the default value of uninitialized global variables in C?

A) Garbage value
B) 0
C) NULL
D) Depends on compiler

Answer: B) 0
Explanation: Global variables are zero-initialized by default.

6. Arrays in C are considered as:

A) Simple data types


B) Abstract data types
C) Both
D) None of the above

Answer: B) Abstract data types


Explanation: Arrays group multiple elements under one name, so they’re considered abstract.

7. Which data type is used to store a single character?

A) int
B) float
C) char
D) double

Answer: C) char
Explanation: char stores a single character.

8. What will be the output of this code?


c
CopyEdit
char c = 'A';
printf("%d", c);

A) A
B) 65
C) Garbage value
D) Error

Answer: B) 65
Explanation: %d prints ASCII value of 'A', which is 65.

9. Which is true about pointers in C?

A) They hold data values


B) They hold addresses of variables
C) They cannot be assigned NULL
D) They are abstract data types

Answer: B) They hold addresses of variables


Explanation: Pointers store memory addresses.

10. What does the following declaration represent?


c
CopyEdit
struct Point {
int x, y;
};

A) Simple data type


B) Abstract data type
C) Pointer type
D) Union type

Answer: B) Abstract data type


Explanation: Structures group multiple variables; they are user-defined abstract data types.

11. Which data type allows storing different data types in the same memory
location?

A) struct
B) union
C) enum
D) array

Answer: B) union
Explanation: Union members share the same memory space.

12. What kind of data type is enum in C?

A) Simple data type


B) Abstract data type
C) User-defined integral type
D) Pointer type

Answer: C) User-defined integral type


Explanation: enum defines named integral constants.

13. Which of these is NOT a primitive data type?

A) int
B) float
C) double
D) struct

Answer: D) struct
Explanation: struct is a composite (abstract) data type.
14. What is the size of a pointer variable in a 64-bit system?

A) 4 bytes
B) 8 bytes
C) 2 bytes
D) Depends on data type pointed to

Answer: B) 8 bytes
Explanation: Pointers are 8 bytes on 64-bit systems regardless of data type.

15. Arrays and pointers in C are related in that:

A) Array name is a constant pointer to its first element


B) Pointers cannot access arrays
C) Arrays are pointers themselves
D) None of the above

Answer: A) Array name is a constant pointer to its first element


Explanation: The name of an array represents the address of the first element.

Stacks in C – MCQs with Answers

1. What is a stack?

A) A linear data structure that follows FIFO


B) A linear data structure that follows LIFO
C) A nonlinear data structure
D) None of the above

Answer: B) A linear data structure that follows LIFO


Explanation: Stack follows Last-In-First-Out order.

2. Which operation removes an element from the top of the stack?

A) Push
B) Pop
C) Peek
D) Insert

Answer: B) Pop
Explanation: pop removes the top element.
3. What does the push operation do in a stack?

A) Removes an element from the stack


B) Adds an element at the bottom of the stack
C) Adds an element to the top of the stack
D) Checks if stack is empty

Answer: C) Adds an element to the top of the stack


Explanation: push inserts an element on top.

4. Which of the following can be used to implement a stack in C?

A) Array only
B) Linked list only
C) Both array and linked list
D) None of the above

Answer: C) Both array and linked list


Explanation: Stack can be implemented using arrays or linked lists.

5. What does the term 'stack overflow' mean?

A) Trying to pop from an empty stack


B) Trying to push to a full stack
C) Stack pointer is NULL
D) None of the above

Answer: B) Trying to push to a full stack


Explanation: Overflow happens when pushing to a full stack.

6. What happens when you pop an element from an empty stack?

A) Stack overflow
B) Stack underflow
C) Returns last element
D) Nothing

Answer: B) Stack underflow


Explanation: Underflow means popping from empty stack.
7. Which function is used to check the top element of a stack without
removing it?

A) push
B) pop
C) peek (or top)
D) isempty

Answer: C) peek (or top)


Explanation: peek returns top element without removing it.

8. What is the initial value of the stack pointer in an empty stack implemented
using an array?

A) -1
B) 0
C) 1
D) NULL

Answer: A) -1
Explanation: Usually, -1 indicates stack is empty in array implementation.

9. What is the time complexity of push and pop operations in a stack?

A) O(n)
B) O(log n)
C) O(1)
D) O(n^2)

Answer: C) O(1)
Explanation: Both operations are constant time.

10. Which of the following applications uses stack data structure?

A) Expression evaluation
B) Undo mechanism in editors
C) Function call management (recursion)
D) All of the above

Answer: D) All of the above


Explanation: Stacks are widely used in these applications.
11. What will be the output of the following C code snippet?
c
CopyEdit
#define MAX 5
int stack[MAX], top = -1;

void push(int val) {


if(top == MAX - 1) {
printf("Stack overflow\n");
return;
}
stack[++top] = val;
}

void printTop() {
if(top == -1)
printf("Stack empty\n");
else
printf("%d\n", stack[top]);
}

int main() {
push(10);
push(20);
printTop();
return 0;
}

A) 10
B) 20
C) Stack empty
D) Stack overflow

Answer: B) 20
Explanation: The last pushed element (20) is at the top.

12. Which of the following is NOT a valid stack operation?

A) enqueue
B) push
C) pop
D) peek

Answer: A) enqueue
Explanation: enqueue is used in queues, not stacks.

13. In a linked list implementation of stack, what is the time complexity of


push operation?
A) O(n)
B) O(1)
C) O(log n)
D) O(n^2)

Answer: B) O(1)
Explanation: Inserting at the head is O(1).

14. What will happen if you try to access stack[top+1] after pushing an
element?

A) Access next free space


B) Access invalid memory (if full)
C) Always safe
D) Error in compilation

Answer: B) Access invalid memory (if full)


Explanation: It may lead to overflow or invalid memory access.

15. Which standard library function can you use to check if the stack is
empty?

A) There is no standard stack library in C


B) isEmpty()
C) empty()
D) stack_empty()

Answer: A) There is no standard stack library in C


Explanation: C standard library does not have a stack; you implement it yourself.

Queues in C – MCQs with Answers

1. What kind of data structure is a queue?

A) Linear, FIFO
B) Linear, LIFO
C) Non-linear
D) Circular only

Answer: A) Linear, FIFO


Explanation: Queue follows First-In-First-Out order.
2. Which operation inserts an element into the queue?

A) push
B) enqueue
C) pop
D) dequeue

Answer: B) enqueue
Explanation: enqueue adds elements at the rear.

3. Which operation removes an element from the queue?

A) enqueue
B) push
C) pop
D) dequeue

Answer: D) dequeue
Explanation: dequeue removes elements from the front.

4. What happens when you try to enqueue an element in a full queue


implemented using an array?

A) Underflow
B) Overflow
C) Error
D) Nothing

Answer: B) Overflow
Explanation: Adding to a full queue causes overflow.

5. What happens when you try to dequeue an element from an empty queue?

A) Overflow
B) Underflow
C) Error
D) Returns 0

Answer: B) Underflow
Explanation: Removing from an empty queue causes underflow.
6. Which of the following is NOT a type of queue?

A) Circular queue
B) Priority queue
C) Double-ended queue (Deque)
D) Stack queue

Answer: D) Stack queue


Explanation: There is no such standard type as “stack queue.”

7. In a queue implemented with an array, what does the rear pointer


represent?

A) Position of front element


B) Position where the next element will be inserted
C) Position of last element removed
D) Position of last element inserted

Answer: B) Position where the next element will be inserted


Explanation: rear points to next insertion position.

8. What is the time complexity of enqueue and dequeue operations in a queue?

A) O(n)
B) O(log n)
C) O(1)
D) O(n^2)

Answer: C) O(1)
Explanation: Both enqueue and dequeue run in constant time.

9. Which queue implementation allows efficient use of array space by


wrapping around?

A) Simple queue
B) Circular queue
C) Priority queue
D) Deque

Answer: B) Circular queue


Explanation: Circular queue reuses free space by wrapping indices.
10. What is the main difference between a queue and a stack?

A) Queue is FIFO; stack is LIFO


B) Queue is LIFO; stack is FIFO
C) Both are FIFO
D) Both are LIFO

Answer: A) Queue is FIFO; stack is LIFO


Explanation: Queue removes elements in the order they were added.

11. In a linked list implementation of a queue, where is the new element


inserted?

A) At the front
B) At the rear
C) In the middle
D) It depends

Answer: B) At the rear


Explanation: New elements are enqueued at the rear.

12. Which of these is used to check if a queue is empty?

A) front == -1
B) front == rear
C) rear == -1
D) rear == front - 1

Answer: B) front == rear


Explanation: In many implementations, front == rear means empty.

13. What does the following code snippet do?


c
CopyEdit
int queue[5], front = 0, rear = 0;

void enqueue(int val) {


if((rear + 1) % 5 == front) {
printf("Queue full\n");
return;
}
queue[rear] = val;
rear = (rear + 1) % 5;
}
A) Adds val to the queue with circular wrap
B) Removes val from queue
C) Causes overflow always
D) Does nothing

Answer: A) Adds val to the queue with circular wrap


Explanation: Implements enqueue in a circular queue.

14. What happens when front == rear in a circular queue?

A) Queue is full
B) Queue is empty
C) Overflow occurs
D) Underflow occurs

Answer: B) Queue is empty


Explanation: This condition indicates the queue has no elements.

15. Which header file must be included for basic input/output functions like
printf used in queue implementations?

A) string.h
B) stdio.h
C) stdlib.h
D) math.h

Answer: B) stdio.h
Explanation: stdio.h contains declarations for input/output functions.

Linked Lists in C – MCQs with Answers

1. What is a linked list?

A) A collection of nodes stored at contiguous memory locations


B) A collection of nodes where each node contains data and a pointer to the next node
C) A linear array
D) None of the above

Answer: B) A collection of nodes where each node contains data and a pointer to the next
node
Explanation: Nodes can be scattered in memory, connected via pointers.
2. Which of the following is NOT a type of linked list?

A) Singly linked list


B) Doubly linked list
C) Circular linked list
D) Binary linked list

Answer: D) Binary linked list


Explanation: No standard data structure called binary linked list; binary trees exist though.

3. In a singly linked list, how do you traverse the list?

A) Using previous pointers


B) Using next pointers
C) Using both next and previous pointers
D) Random access

Answer: B) Using next pointers


Explanation: Singly linked lists have only one pointer per node pointing to the next node.

4. What does the head pointer in a linked list represent?

A) Pointer to the last node


B) Pointer to the first node
C) Pointer to a random node
D) NULL pointer

Answer: B) Pointer to the first node


Explanation: head points to the start of the list.

5. Which of the following is true about linked lists compared to arrays?

A) Linked lists have fixed size


B) Arrays use dynamic memory allocation
C) Linked lists use dynamic memory allocation and can grow or shrink at runtime
D) Arrays provide faster insertion and deletion at arbitrary positions

Answer: C) Linked lists use dynamic memory allocation and can grow or shrink at runtime
Explanation: Linked lists are dynamic and flexible.

6. What is the time complexity to access the nth element in a singly linked list?
A) O(1)
B) O(n)
C) O(log n)
D) O(n^2)

Answer: B) O(n)
Explanation: Need to traverse from head to nth node.

7. How do you insert a new node at the beginning of a singly linked list?

A) Update the new node's next pointer to current head, then update head to new node
B) Traverse to the end and add new node
C) Replace the head node data
D) None of the above

Answer: A) Update the new node's next pointer to current head, then update head to new
node
Explanation: This keeps the list connected and updates head.

8. What value does the next pointer of the last node in a singly linked list
hold?

A) Address of the head node


B) NULL
C) Address of the previous node
D) Garbage value

Answer: B) NULL
Explanation: Indicates end of the list.

9. Which function is commonly used in C to dynamically allocate memory for


new nodes?

A) alloc()
B) malloc()
C) calloc()
D) Both B and C

Answer: D) Both B and C


Explanation: malloc and calloc allocate memory dynamically.
10. What is the disadvantage of using singly linked lists?

A) Cannot traverse backwards


B) Cannot insert nodes
C) Cannot delete nodes
D) Requires contiguous memory

Answer: A) Cannot traverse backwards


Explanation: Only forward traversal is possible.

11. How can you implement a doubly linked list?

A) Each node has only one pointer to next node


B) Each node has two pointers: one to next and one to previous node
C) Nodes are stored in contiguous memory
D) Using arrays

Answer: B) Each node has two pointers: one to next and one to previous node
Explanation: Enables traversal in both directions.

12. What is the advantage of circular linked lists over linear linked lists?

A) No advantage
B) Can traverse the whole list from any node
C) Requires less memory
D) Easier to implement

Answer: B) Can traverse the whole list from any node


Explanation: Last node points to head, so no NULL termination.

13. What happens when you free the head node but forget to update the head
pointer?

A) Memory leak
B) Dangling pointer
C) Crash
D) No effect

Answer: B) Dangling pointer


Explanation: Head still points to freed memory.
14. Which of the following is true for linked list insertion at the end?

A) Time complexity is O(1) if tail pointer is maintained


B) Time complexity is always O(n)
C) Time complexity is O(log n)
D) Not possible in linked lists

Answer: A) Time complexity is O(1) if tail pointer is maintained


Explanation: Tail pointer helps insert at end in constant time.

15. Which is the correct way to declare a node structure for a singly linked
list?
c
CopyEdit
A) struct node { int data; struct node *next; };
B) struct node { int data; int *next; };
C) struct node { int data; struct node next; };
D) struct node { int data; void *next; };

Answer: A) struct node { int data; struct node *next; };


Explanation: Next must be a pointer to a node struct.

Trees in C – MCQs with Answers

1. What is a tree data structure?

A) A linear data structure


B) A hierarchical data structure consisting of nodes with parent-child relationships
C) A type of array
D) A stack implementation

Answer: B) A hierarchical data structure consisting of nodes with parent-child relationships


Explanation: Trees organize data hierarchically with nodes connected via edges.

2. What is the node at the top of a tree called?

A) Leaf node
B) Root node
C) Internal node
D) Child node

Answer: B) Root node


Explanation: The root node is the top-most node without a parent.
3. Which of the following is a leaf node?

A) A node with at least one child


B) A node with no children
C) A node with two children
D) Root node

Answer: B) A node with no children


Explanation: Leaf nodes have no children.

4. What is the maximum number of children for a binary tree node?

A) 1
B) 2
C) n
D) 3

Answer: B) 2
Explanation: Binary tree nodes have up to two children.

5. What is the height of a tree?

A) Number of leaf nodes


B) Number of edges on the longest path from root to a leaf
C) Number of nodes in the tree
D) Number of root nodes

Answer: B) Number of edges on the longest path from root to a leaf


Explanation: Height measures longest downward path.

6. Which traversal visits nodes in the order: left subtree, root, right subtree?

A) Preorder
B) Inorder
C) Postorder
D) Level-order

Answer: B) Inorder
Explanation: Inorder traversal follows left-root-right order.
7. Which traversal visits nodes in the order: root, left subtree, right subtree?

A) Preorder
B) Inorder
C) Postorder
D) Level-order

Answer: A) Preorder
Explanation: Preorder visits root first.

8. Which traversal visits nodes in the order: left subtree, right subtree, root?

A) Preorder
B) Inorder
C) Postorder
D) Level-order

Answer: C) Postorder
Explanation: Postorder visits root last.

9. Which traversal method uses a queue to visit nodes level by level?

A) Preorder
B) Inorder
C) Postorder
D) Level-order

Answer: D) Level-order
Explanation: Level-order traversal is breadth-first and uses a queue.

10. In C, how is a tree node typically defined?

A) struct node { int data; int *left; int *right; };


B) struct node { int data; struct node *left; struct node *right; };
C) struct node { int data; void *left; void *right; };
D) struct node { int data; struct node left; struct node right; };

Answer: B) struct node { int data; struct node *left; struct node
*right; };
Explanation: Left and right are pointers to child nodes.
11. What is the time complexity of searching an element in a balanced binary
search tree?

A) O(1)
B) O(log n)
C) O(n)
D) O(n log n)

Answer: B) O(log n)
Explanation: Balanced BST search is logarithmic.

12. Which of the following is NOT a type of binary tree?

A) Full binary tree


B) Complete binary tree
C) Linked binary tree
D) Perfect binary tree

Answer: C) Linked binary tree


Explanation: Linked binary tree is an implementation, not a type.

13. What is a Binary Search Tree (BST)?

A) A tree where left child > root > right child


B) A tree where left child < root < right child
C) A tree with no children
D) A tree with nodes connected randomly

Answer: B) A tree where left child < root < right child
Explanation: BST maintains order for efficient search.

14. Which traversal of a BST results in sorted order?

A) Preorder
B) Inorder
C) Postorder
D) Level-order

Answer: B) Inorder
Explanation: Inorder traversal of BST outputs sorted data.
15. What is the key difference between a full binary tree and a perfect binary
tree?

A) Full binary tree has all nodes with 0 or 2 children; perfect binary tree is full and all leaves
at the same level
B) Perfect binary tree can have nodes with one child
C) Full binary tree is always complete
D) No difference

Answer: A) Full binary tree has all nodes with 0 or 2 children; perfect binary tree is full and
all leaves at the same level
Explanation: Perfect binary trees are a special case of full binary trees.

Balanced Trees in C – MCQs with Answers

1. What is a balanced tree?

A) A tree where all nodes have two children


B) A tree where the height difference between left and right subtrees is minimized
C) A tree with no leaf nodes
D) A tree with only one node

Answer: B) A tree where the height difference between left and right subtrees is minimized
Explanation: Balanced trees keep height difference small for efficient operations.

2. Which of the following is a type of self-balancing binary search tree?

A) AVL tree
B) Linked list
C) Binary heap
D) B-tree

Answer: A) AVL tree


Explanation: AVL trees maintain balance by rotations after insert/delete.

3. What is the maximum allowed height difference (balance factor) between


left and right subtrees in an AVL tree?

A) 0
B) 1
C) 2
D) 3
Answer: B) 1
Explanation: AVL trees allow balance factor -1, 0, or +1.

4. What operation is used in AVL trees to restore balance after insertion or


deletion?

A) Searching
B) Rotations
C) Swapping nodes
D) Merging nodes

Answer: B) Rotations
Explanation: Single or double rotations fix unbalanced trees.

5. Which rotation type is used when a node is inserted into the left subtree of
the left child causing imbalance?

A) Right rotation
B) Left rotation
C) Left-Right rotation
D) Right-Left rotation

Answer: A) Right rotation


Explanation: Left-left imbalance fixed by right rotation.

6. Which rotation is used to fix a right-right imbalance?

A) Left rotation
B) Right rotation
C) Left-Right rotation
D) Right-Left rotation

Answer: A) Left rotation


Explanation: Right-right imbalance fixed by left rotation.

7. What is the time complexity of search, insertion, and deletion operations in


an AVL tree?

A) O(n)
B) O(log n)
C) O(1)
D) O(n log n)

Answer: B) O(log n)
Explanation: Height is balanced, so operations are logarithmic.

8. What is the balance factor of a node defined as in AVL trees?

A) Height of left subtree minus height of right subtree


B) Height of right subtree minus height of left subtree
C) Number of nodes in left subtree minus right subtree
D) Number of leaf nodes

Answer: A) Height of left subtree minus height of right subtree


Explanation: Balance factor = height(left) - height(right).

9. What happens if the balance factor of any node in an AVL tree becomes
less than -1 or greater than 1?

A) The tree becomes a linked list


B) The tree becomes unbalanced and requires rotations
C) Nothing, AVL allows this
D) Tree is deleted

Answer: B) The tree becomes unbalanced and requires rotations


Explanation: Rotations restore balance when factor exceeds ±1.

10. Which of the following is NOT a self-balancing binary search tree?

A) AVL tree
B) Red-black tree
C) B-tree
D) Binary heap

Answer: D) Binary heap


Explanation: Binary heaps are not BSTs and not necessarily balanced like AVL or red-black
trees.

11. What data structure is typically used to implement rotations in balanced


trees in C?
A) Arrays
B) Linked nodes with pointers
C) Stacks
D) Queues

Answer: B) Linked nodes with pointers


Explanation: Trees use pointers for dynamic node connections.

12. Which balanced tree structure is specifically designed for databases and
filesystems to handle large blocks of data?

A) AVL tree
B) Red-black tree
C) B-tree
D) Binary heap

Answer: C) B-tree
Explanation: B-trees are optimized for disk-based storage.

13. Which balanced tree uses colors to ensure balancing?

A) AVL tree
B) Red-black tree
C) B-tree
D) Trie

Answer: B) Red-black tree


Explanation: Red-black trees use red and black colors on nodes.

14. What does a double rotation in AVL trees consist of?

A) Two left rotations


B) Two right rotations
C) One left rotation followed by one right rotation or vice versa
D) Swapping nodes twice

Answer: C) One left rotation followed by one right rotation or vice versa
Explanation: Fixes left-right or right-left imbalances.

15. In C, how would you typically represent an AVL tree node?


c
CopyEdit
A) struct node { int data; struct node *left; struct node *right; int
height; };
B) struct node { int data; int *left; int *right; int height; };
C) struct node { int data; struct node left; struct node right; int height;
};
D) struct node { int data; void *left; void *right; };

Answer: A) struct node { int data; struct node *left; struct node *right; int height; };
Explanation: Height is stored with pointers to left and right nodes.

Graphs in C – MCQs with Answers

1. What is a graph?

A) A linear data structure


B) A collection of nodes (vertices) and edges connecting pairs of nodes
C) A type of array
D) A stack implementation

Answer: B) A collection of nodes (vertices) and edges connecting pairs of nodes


Explanation: Graphs model relationships between objects.

2. In graph terminology, what is a vertex?

A) An edge
B) A node
C) A weight
D) A cycle

Answer: B) A node
Explanation: Vertices are points or nodes in a graph.

3. What is the term for an edge that connects a vertex to itself?

A) Parallel edge
B) Self-loop
C) Directed edge
D) Weighted edge

Answer: B) Self-loop
Explanation: An edge that starts and ends at the same vertex.
4. Which data structure is commonly used to represent a graph in C?

A) Array and stack


B) Adjacency matrix and adjacency list
C) Queue and array
D) Linked list and stack

Answer: B) Adjacency matrix and adjacency list


Explanation: Both are standard graph representations.

5. What is the space complexity of an adjacency matrix for a graph with V


vertices?

A) O(V)
B) O(V^2)
C) O(E)
D) O(log V)

Answer: B) O(V^2)
Explanation: Adjacency matrix uses VxV space.

6. Which graph representation is more efficient for sparse graphs?

A) Adjacency matrix
B) Adjacency list
C) Edge list
D) None

Answer: B) Adjacency list


Explanation: Uses space proportional to edges, better for sparse graphs.

7. What does a directed graph mean?

A) Edges have no direction


B) Edges have direction from one vertex to another
C) Graph has no edges
D) All edges have equal weight

Answer: B) Edges have direction from one vertex to another


Explanation: Edges are ordered pairs in directed graphs.
8. What is the name of the traversal technique that uses a queue and explores
neighbors level by level?

A) Depth-First Search (DFS)


B) Breadth-First Search (BFS)
C) Dijkstra’s algorithm
D) Kruskal’s algorithm

Answer: B) Breadth-First Search (BFS)


Explanation: BFS uses a queue to explore neighbors.

9. Which traversal uses recursion or a stack to explore as far as possible along


a branch?

A) BFS
B) DFS
C) Dijkstra’s algorithm
D) Prim’s algorithm

Answer: B) DFS
Explanation: DFS uses recursion or stack to go deep before backtracking.

10. In C, how would you define a simple adjacency list node structure for a
graph?
c
CopyEdit
A) struct node { int vertex; struct node *next; };
B) struct node { int vertex; int weight; };
C) struct node { int vertex; struct node next; };
D) struct node { int vertex; void *next; };

Answer: A) struct node { int vertex; struct node *next; };


Explanation: Linked list node points to next adjacent vertex.

11. What is a connected graph?

A) A graph where there is a path between every pair of vertices


B) A graph with no edges
C) A graph with self-loops only
D) A graph with weighted edges

Answer: A) A graph where there is a path between every pair of vertices


Explanation: Connectivity means reachability among all vertices.
12. What is a cycle in a graph?

A) A path with no repeated vertices


B) A path that starts and ends at the same vertex
C) A disconnected component
D) An edge that connects two vertices

Answer: B) A path that starts and ends at the same vertex


Explanation: Cycle means looping back to the start.

13. Which algorithm is commonly used to find the shortest path in a weighted
graph?

A) BFS
B) DFS
C) Dijkstra’s algorithm
D) Kruskal’s algorithm

Answer: C) Dijkstra’s algorithm


Explanation: Dijkstra’s finds shortest paths with non-negative weights.

14. Which algorithm finds the Minimum Spanning Tree (MST) of a graph?

A) BFS
B) DFS
C) Dijkstra’s algorithm
D) Kruskal’s algorithm

Answer: D) Kruskal’s algorithm


Explanation: Kruskal’s finds MST by sorting edges.

15. What is the time complexity of DFS on a graph with V vertices and E
edges using adjacency list?

A) O(V^2)
B) O(V + E)
C) O(E^2)
D) O(log V)

Answer: B) O(V + E)
Explanation: DFS visits all vertices and edges once.
Classes and Class-like Data Structures in C – MCQs with Answers

1. Which C keyword is used to define a user-defined data structure similar to


a class?

A) class
B) object
C) struct
D) typedef

Answer: C) struct
Explanation: C uses struct to group variables, similar to classes in OOP.

2. Can a C struct contain functions directly?

A) Yes
B) No
C) Only in C99 standard
D) Only with pointers

Answer: B) No
Explanation: Functions cannot be members of a struct, but function pointers can be used.

3. How can you simulate a class method in C?

A) Using function pointers inside a struct


B) By defining functions outside the struct
C) Using macros
D) Both A and B

Answer: D) Both A and B


Explanation: You can define functions separately and pass struct pointers or embed function
pointers inside structs.

4. What is the purpose of typedef when used with structs?

A) To create a new type alias for easier usage


B) To define functions inside struct
C) To inherit from another struct
D) To declare variables
Answer: A) To create a new type alias for easier usage
Explanation: typedef lets you use a simpler name instead of struct name.

5. What is encapsulation in the context of C data structures?

A) Keeping data and functions together in one unit


B) Making data private and accessible only via functions
C) Both A and B are partially possible with structs and separate functions
D) Not possible in C

Answer: C) Both A and B are partially possible with structs and separate functions
Explanation: C doesn’t enforce encapsulation, but you can simulate it using static variables
and function interfaces.

6. Which of the following correctly declares a struct and a variable of that


struct type?
c
CopyEdit
A) struct Person { int age; }; struct Person p1;
B) struct Person { int age; } p1;
C) typedef struct Person { int age; } Person; Person p1;
D) All of the above

Answer: D) All of the above


Explanation: All syntaxes are correct ways to declare structs and variables.

7. How can you access the members of a struct using a pointer to that struct?

A) Using . operator
B) Using -> operator
C) Using * operator
D) Using & operator

Answer: B) Using -> operator


Explanation: -> is used to access members via pointer.

8. Which of the following is a way to simulate inheritance in C?

A) Using nested structs (struct inside struct)


B) Using pointers to base structs
C) Using macros for reuse
D) All of the above

Answer: D) All of the above


Explanation: C doesn’t support inheritance but these techniques simulate it.

9. What happens if you pass a struct to a function without a pointer?

A) The function modifies the original struct


B) The struct is passed by value, so the function gets a copy
C) The function receives a reference to the struct
D) Compilation error

Answer: B) The struct is passed by value, so the function gets a copy


Explanation: Structs are copied when passed by value.

10. What is the correct way to define a function pointer inside a struct?
c
CopyEdit
A) struct S { void (*func)(); };
B) struct S { void func(); };
C) struct S { (*func) void(); };
D) struct S { func void*; };

Answer: A) struct S { void (*func)(); };


Explanation: Function pointer syntax requires (*func).

Objects in C Data Structures – MCQs with Answers

1. How can you simulate an object in C?

A) Using classes
B) Using structs combined with related functions
C) Using pointers only
D) Using arrays

Answer: B) Using structs combined with related functions


Explanation: Objects in C can be simulated by grouping data (structs) and functions
operating on that data.

2. Which keyword is used to define a user-defined data type that can be


considered as an object in C?
A) class
B) object
C) struct
D) typedef

Answer: C) struct
Explanation: struct groups data fields representing an object.

3. How do you access a member of a struct when you have a pointer to the
struct?

A) Using . operator
B) Using -> operator
C) Using * operator
D) Using & operator

Answer: B) Using -> operator


Explanation: -> is used to access members via pointers.

4. Can functions be part of a struct in C?

A) Yes, directly as members


B) No, but you can include function pointers inside the struct
C) No, C does not allow functions in structs
D) Yes, but only static functions

Answer: B) No, but you can include function pointers inside the struct
Explanation: C structs can’t have actual functions, but can hold pointers to functions.

5. What is the purpose of including function pointers inside a struct in C?

A) To simulate methods (member functions) of an object


B) To store addresses of variables
C) To make the struct bigger
D) To initialize the struct

Answer: A) To simulate methods (member functions) of an object


Explanation: Function pointers inside structs mimic object methods.

6. Which of the following correctly defines a struct with a function pointer to


simulate an object method?
c
CopyEdit
A) struct Object { int data; void (*display)(struct Object*); };
B) struct Object { int data; void display(); };
C) struct Object { int data; void (*display)(); };
D) struct Object { int data; int *display; };

Answer: A) struct Object { int data; void (display)(struct Object); };


Explanation: Function pointer takes a pointer to the struct for access to its data.

7. How would you call a function pointer inside a struct given a pointer obj to
that struct?

A) obj.display(obj);
B) obj->display();
C) obj->display(obj);
D) (*obj).display();

Answer: C) obj->display(obj);
Explanation: Using pointer, call function pointer with obj as argument.

8. How is data encapsulation usually achieved in C when simulating objects?

A) Using static keyword for variables inside source files and exposing functions for access
B) Using private keywords
C) Using inheritance
D) Using arrays only

Answer: A) Using static keyword for variables inside source files and exposing functions
for access
Explanation: Encapsulation is simulated by restricting data access and providing functions.

9. When you pass a struct to a function in C, what is passed?

A) Reference to the original struct


B) Copy of the struct
C) Pointer to the struct automatically
D) Memory address

Answer: B) Copy of the struct


Explanation: Structs are passed by value unless a pointer is used.
10. Which of the following is true about objects in C compared to C++?

A) C has full OOP support with classes and objects


B) C simulates objects using structs and functions, lacks built-in OOP features
C) C supports inheritance and polymorphism natively
D) C uses templates for objects

Answer: B) C simulates objects using structs and functions, lacks built-in OOP features
Explanation: C is procedural, OOP features must be manually implemented.

Complexity of Algorithms in C – MCQs with Answers

1. What does the time complexity of an algorithm measure?

A) The amount of memory used


B) The time taken to execute as a function of input size
C) The number of lines of code
D) The size of the output

Answer: B) The time taken to execute as a function of input size


Explanation: Time complexity expresses how running time grows with input size.

2. Which notation is commonly used to represent the worst-case time


complexity of an algorithm?

A) Ω (Omega)
B) Θ (Theta)
C) O (Big-O)
D) λ (Lambda)

Answer: C) O (Big-O)
Explanation: Big-O represents upper bound worst-case complexity.

3. What is the time complexity of a linear search algorithm?

A) O(1)
B) O(log n)
C) O(n)
D) O(n^2)

Answer: C) O(n)
Explanation: Linear search scans elements one by one.
4. What is the time complexity of binary search on a sorted array?

A) O(n)
B) O(log n)
C) O(n log n)
D) O(1)

Answer: B) O(log n)
Explanation: Binary search divides the array by half each step.

5. What does space complexity measure?

A) The time required to run an algorithm


B) The amount of extra memory required as input size grows
C) The number of CPU cycles
D) The size of the input data

Answer: B) The amount of extra memory required as input size grows


Explanation: Space complexity measures additional memory usage.

6. What is the time complexity of the bubble sort algorithm in the worst case?

A) O(n)
B) O(n log n)
C) O(n^2)
D) O(log n)

Answer: C) O(n^2)
Explanation: Bubble sort compares pairs multiple times, leading to quadratic time.

7. Which of the following time complexities represents the fastest growth rate?

A) O(n)
B) O(log n)
C) O(n^2)
D) O(n log n)

Answer: B) O(log n)
Explanation: Logarithmic grows slowest as input increases.

8. What is the time complexity of accessing an element in an array by index?


A) O(1)
B) O(n)
C) O(log n)
D) O(n^2)

Answer: A) O(1)
Explanation: Direct indexing is constant time.

9. Which complexity class represents algorithms whose time grows


exponentially with input size?

A) O(log n)
B) O(n^2)
C) O(2^n)
D) O(n log n)

Answer: C) O(2^n)
Explanation: Exponential complexity grows very fast, e.g., recursive Fibonacci.

10. What is the time complexity of inserting an element at the beginning of a


linked list?

A) O(1)
B) O(n)
C) O(log n)
D) O(n^2)

Answer: A) O(1)
Explanation: Insertion at head requires changing a pointer only.

11. If an algorithm has time complexity O(n!), what does it imply?

A) The algorithm runs very efficiently


B) The algorithm runs factorial time, which is very slow for large inputs
C) The algorithm is logarithmic
D) The algorithm runs in linear time

Answer: B) The algorithm runs factorial time, which is very slow for large inputs
Explanation: Factorial time is impractical for large n.
12. Which of the following sorting algorithms has an average-case time
complexity of O(n log n)?

A) Bubble Sort
B) Merge Sort
C) Selection Sort
D) Insertion Sort

Answer: B) Merge Sort


Explanation: Merge sort divides and conquers, running in O(n log n).

13. Which of the following statements about Big-O notation is true?

A) It gives the exact time an algorithm will take


B) It describes the upper bound on time or space complexity
C) It is only used for space complexity
D) It measures the best-case scenario

Answer: B) It describes the upper bound on time or space complexity


Explanation: Big-O gives an upper bound on growth rates.

14. What is the space complexity of recursive Fibonacci implemented without


memoization?

A) O(1)
B) O(n)
C) O(log n)
D) O(n^2)

Answer: B) O(n)
Explanation: Maximum recursion depth is proportional to n.

15. In terms of algorithm complexity, what does amortized analysis mean?

A) Analyzing the worst-case of each operation individually


B) Analyzing average cost per operation over a sequence of operations
C) Ignoring the cost of expensive operations
D) Using recursive methods only

Answer: B) Analyzing average cost per operation over a sequence of operations


Explanation: Amortized analysis averages costly and cheap operations over time.
Divide and Conquer in C – MCQs with Answers

1. What is the main idea behind the divide and conquer technique?

A) Divide the problem into smaller subproblems, conquer them independently, and combine
their results
B) Solve the problem directly without recursion
C) Use only iterative methods
D) Solve the largest subproblem first

Answer: A) Divide the problem into smaller subproblems, conquer them independently, and
combine their results
Explanation: Divide and conquer breaks a problem down recursively.

2. Which of the following algorithms uses divide and conquer?

A) Linear Search
B) Merge Sort
C) Bubble Sort
D) Insertion Sort

Answer: B) Merge Sort


Explanation: Merge sort divides the array into halves and merges sorted halves.

3. In the divide and conquer approach, what is the typical base condition in
recursive algorithms?

A) When the problem size is zero or one


B) When the problem size is more than 10
C) When all elements are sorted
D) When the problem cannot be divided further

Answer: A) When the problem size is zero or one


Explanation: Base case stops recursion when subproblem is trivially small.

4. Which of the following is NOT a divide and conquer algorithm?

A) Quick Sort
B) Binary Search
C) Selection Sort
D) Merge Sort
Answer: C) Selection Sort
Explanation: Selection sort is iterative and does not divide the problem recursively.

5. What is the time complexity of merge sort using divide and conquer?

A) O(n)
B) O(n log n)
C) O(n^2)
D) O(log n)

Answer: B) O(n log n)


Explanation: Merge sort divides array log n times and merges n elements each time.

6. How does quicksort divide the problem?

A) Into two subarrays around a pivot element


B) Into equal halves without partitioning
C) Using a temporary array
D) By finding the maximum element

Answer: A) Into two subarrays around a pivot element


Explanation: Quicksort partitions the array around a pivot recursively.

7. What is the key step in divide and conquer that combines the solutions of
subproblems?

A) Recursion
B) Partitioning
C) Merging or combining sub-results
D) Iteration

Answer: C) Merging or combining sub-results


Explanation: Combining partial solutions completes the algorithm.

8. Which of the following problems is best solved using divide and conquer?

A) Searching an unsorted list


B) Sorting large datasets
C) Linear traversal
D) Summing array elements sequentially
Answer: B) Sorting large datasets
Explanation: Divide and conquer is efficient for sorting large inputs.

9. In recursive divide and conquer algorithms, which term describes the


complexity recurrence?

A) T(n) = T(n-1) + O(1)


B) T(n) = 2T(n/2) + O(n)
C) T(n) = T(n/3) + O(log n)
D) T(n) = O(n^2)

Answer: B) T(n) = 2T(n/2) + O(n)


Explanation: This recurrence is typical for merge sort.

10. What is the role of the "conquer" step in divide and conquer algorithms?

A) Splitting the problem into subproblems


B) Solving the smaller subproblems recursively
C) Combining the results of subproblems to form the solution
D) Finding the base case

Answer: B) Solving the smaller subproblems recursively


Explanation: "Conquer" solves subproblems after division.

Greedy Algorithms in C – MCQs with Answers

1. What is the main idea behind a greedy algorithm?

A) Explore all possible solutions exhaustively


B) Make the locally optimal choice at each step hoping for a global optimum
C) Divide the problem into smaller subproblems
D) Use dynamic programming to store intermediate results

Answer: B) Make the locally optimal choice at each step hoping for a global optimum
Explanation: Greedy algorithms choose the best option at each step without reconsideration.

2. Which of the following problems can be solved optimally using a greedy


algorithm?

A) 0/1 Knapsack Problem


B) Fractional Knapsack Problem
C) Traveling Salesman Problem
D) Matrix Chain Multiplication

Answer: B) Fractional Knapsack Problem


Explanation: Fractional knapsack can be solved optimally with a greedy approach.

3. What is a major limitation of greedy algorithms?

A) They always give the optimal solution


B) They may not give optimal solution for all problems
C) They require huge memory
D) They only work for sorting problems

Answer: B) They may not give optimal solution for all problems
Explanation: Greedy algorithms can fail for problems where global optimal requires
backtracking.

4. In the context of greedy algorithms, what does the "greedy choice


property" mean?

A) Choosing the best solution overall at the start


B) A globally optimal solution can be arrived at by choosing a local optimum at each step
C) Trying all solutions exhaustively
D) Using recursion to solve subproblems

Answer: B) A globally optimal solution can be arrived at by choosing a local optimum at


each step
Explanation: The greedy choice property guarantees optimality by local decisions.

5. What data structure is commonly used in greedy algorithms like Huffman


Coding?

A) Queue
B) Stack
C) Priority Queue (Min-Heap)
D) Array

Answer: C) Priority Queue (Min-Heap)


Explanation: Priority queues efficiently select minimum elements in greedy algorithms.
6. What is the time complexity of the greedy algorithm for the fractional
knapsack problem if sorting is required?

A) O(n)
B) O(n log n)
C) O(log n)
D) O(n^2)

Answer: B) O(n log n)


Explanation: Sorting items by value/weight ratio dominates complexity.

7. Which problem cannot be solved optimally by a greedy algorithm?

A) Fractional Knapsack
B) Minimum Spanning Tree
C) 0/1 Knapsack
D) Activity Selection

Answer: C) 0/1 Knapsack


Explanation: 0/1 Knapsack requires dynamic programming, not greedy.

8. In the Activity Selection problem, how does the greedy algorithm choose
activities?

A) Choose activity with the earliest start time


B) Choose activity with the shortest duration
C) Choose activity that finishes earliest
D) Choose activity with the longest duration

Answer: C) Choose activity that finishes earliest


Explanation: Selecting earliest finishing activity leads to maximum compatible activities.

9. What is the typical first step in a greedy algorithm?

A) Divide the problem into subproblems


B) Sort the input based on a key parameter
C) Use recursion
D) Initialize a stack

Answer: B) Sort the input based on a key parameter


Explanation: Sorting often helps in making greedy choices efficiently.
10. Which of the following is an example of a greedy algorithm?

A) Merge Sort
B) Binary Search
C) Dijkstra’s Shortest Path Algorithm
D) Dynamic Programming for Fibonacci

Answer: C) Dijkstra’s Shortest Path Algorithm


Explanation: Dijkstra’s algorithm picks the shortest known distance greedily at each step.

Dynamic Programming in C – MCQs with Answers

1. What is the main idea behind dynamic programming?

A) Solve problems by dividing them into independent subproblems


B) Solve problems by storing results of overlapping subproblems to avoid recomputation
C) Solve problems using brute force
D) Solve problems by making greedy choices

Answer: B) Solve problems by storing results of overlapping subproblems to avoid


recomputation
Explanation: Dynamic programming uses memoization or tabulation to store solutions.

2. Which problem is a classic example solved by dynamic programming?

A) Bubble Sort
B) Fibonacci Series
C) Binary Search
D) Quick Sort

Answer: B) Fibonacci Series


Explanation: Fibonacci calculation benefits from storing previously computed values.

3. What type of problems is dynamic programming best suited for?

A) Problems with no overlapping subproblems


B) Problems with overlapping subproblems and optimal substructure
C) Problems that require sorting
D) Problems solvable by divide and conquer only

Answer: B) Problems with overlapping subproblems and optimal substructure


Explanation: DP applies when subproblems repeat and optimal substructure exists.
4. What is memoization in dynamic programming?

A) Storing answers to subproblems to avoid recomputation


B) Sorting data before processing
C) Dividing the problem into smaller problems
D) Using a greedy approach

Answer: A) Storing answers to subproblems to avoid recomputation


Explanation: Memoization caches computed results for efficiency.

5. Which of the following algorithms is NOT typically solved using dynamic


programming?

A) Longest Common Subsequence (LCS)


B) Knapsack Problem
C) Merge Sort
D) Matrix Chain Multiplication

Answer: C) Merge Sort


Explanation: Merge sort uses divide and conquer, not dynamic programming.

✅ Searching in C – MCQs with Answers

6. What is the time complexity of linear search on an unsorted array?

A) O(1)
B) O(log n)
C) O(n)
D) O(n^2)

Answer: C) O(n)
Explanation: Linear search scans each element one by one.

7. What condition must be met to use binary search on an array?

A) The array must be sorted


B) The array must be unsorted
C) The array size must be prime
D) The array must contain only positive numbers

Answer: A) The array must be sorted


Explanation: Binary search divides search space in a sorted array.
8. What is the average-case time complexity of binary search?

A) O(1)
B) O(n)
C) O(log n)
D) O(n log n)

Answer: C) O(log n)
Explanation: Binary search halves the search space every iteration.

9. Which searching algorithm is efficient for small or nearly sorted datasets?

A) Binary Search
B) Linear Search
C) Jump Search
D) Interpolation Search

Answer: B) Linear Search


Explanation: Linear search performs well on small or nearly sorted arrays.

10. What is the worst-case time complexity of interpolation search on a


uniformly distributed sorted array?

A) O(log n)
B) O(n)
C) O(n log n)
D) O(1)

Answer: A) O(log n)
Explanation: Interpolation search performs well on uniformly distributed data with O(log log
n) average, but worst case is O(n).

Traversal Techniques in C – MCQs with Answers

1. Which of the following is NOT a tree traversal technique?

A) Inorder
B) Preorder
C) Postorder
D) Breadth-First Search (BFS)
Answer: D) Breadth-First Search (BFS)
Explanation: BFS is a graph traversal technique but also used for trees (level order), but
commonly traversal on trees is classified as inorder, preorder, and postorder for DFS.

2. What is the order of nodes visited in inorder traversal of a binary tree?

A) Root -> Left -> Right


B) Left -> Root -> Right
C) Left -> Right -> Root
D) Root -> Right -> Left

Answer: B) Left -> Root -> Right


Explanation: Inorder visits left subtree, then root, then right subtree.

3. Which traversal technique uses a queue data structure for implementation?

A) Preorder traversal
B) Inorder traversal
C) Postorder traversal
D) Level order traversal (BFS)

Answer: D) Level order traversal (BFS)


Explanation: Level order uses a queue to visit nodes level by level.

4. In preorder traversal, what is the sequence of node visits?

A) Left -> Root -> Right


B) Root -> Left -> Right
C) Left -> Right -> Root
D) Right -> Root -> Left

Answer: B) Root -> Left -> Right


Explanation: Preorder visits root first, then left subtree, then right subtree.

5. What data structure is typically used to implement depth-first traversals


like inorder, preorder, and postorder?

A) Queue
B) Stack
C) Array
D) Linked List
Answer: B) Stack
Explanation: DFS uses recursion (implicit stack) or explicit stack data structure.

6. What is the order of nodes visited in postorder traversal?

A) Left -> Root -> Right


B) Root -> Left -> Right
C) Left -> Right -> Root
D) Right -> Root -> Left

Answer: C) Left -> Right -> Root


Explanation: Postorder visits left subtree, right subtree, then root.

7. Which traversal method is used to get the nodes in non-decreasing order in


a binary search tree?

A) Preorder
B) Inorder
C) Postorder
D) Level order

Answer: B) Inorder
Explanation: Inorder traversal of BST visits nodes in sorted order.

8. Which traversal visits nodes level by level?

A) Preorder
B) Postorder
C) Inorder
D) Level order

Answer: D) Level order


Explanation: Level order visits all nodes at each level before moving to next.

9. Which traversal is useful for deleting nodes in a tree safely?

A) Preorder
B) Postorder
C) Inorder
D) Level order
Answer: B) Postorder
Explanation: Postorder visits children before parent, safe for deletion.

10. Which of the following traversal techniques can be implemented using


recursion?

A) Preorder
B) Inorder
C) Postorder
D) All of the above

Answer: D) All of the above


Explanation: All DFS traversals (pre, in, postorder) are naturally recursive.

Backtracking in C – MCQs with Answers

1. What is the main idea of backtracking?

A) Try all possible solutions one by one without pruning


B) Build solutions incrementally and abandon a path as soon as it is determined that it cannot
lead to a valid solution
C) Use dynamic programming to store results
D) Solve problems iteratively only

Answer: B) Build solutions incrementally and abandon a path as soon as it is determined that
it cannot lead to a valid solution
Explanation: Backtracking prunes the search space early to avoid unnecessary work.

2. Which problem is commonly solved using backtracking?

A) Bubble Sort
B) N-Queens Problem
C) Binary Search
D) Merge Sort

Answer: B) N-Queens Problem


Explanation: N-Queens is a classic backtracking problem.

3. Backtracking algorithms are typically implemented using:

A) Iteration with queues


B) Recursion
C) Dynamic programming
D) Hashing

Answer: B) Recursion
Explanation: Backtracking explores solution space via recursive calls.

4. Which of the following problems is NOT usually solved by backtracking?

A) Sudoku Solver
B) Hamiltonian Cycle
C) Quick Sort
D) Subset Sum

Answer: C) Quick Sort


Explanation: Quick sort uses divide and conquer, not backtracking.

5. What is the time complexity of the N-Queens backtracking algorithm in the


worst case?

A) O(n)
B) O(n!)
C) O(n^2)
D) O(log n)

Answer: B) O(n!)
Explanation: Backtracking explores permutations of queen placements.

6. What technique does backtracking use to avoid checking invalid solutions?

A) Memoization
B) Pruning
C) Sorting
D) Binary Search

Answer: B) Pruning
Explanation: Pruning cuts off branches that won’t lead to a solution.

7. In backtracking, what does the "state space tree" represent?

A) The call stack of the program


B) All possible states or partial solutions explored by the algorithm
C) The input array sorted
D) The final solution only

Answer: B) All possible states or partial solutions explored by the algorithm


Explanation: The state space tree is the conceptual search space.

8. Which of these problems can be solved using backtracking?

A) Tower of Hanoi
B) Linear Search
C) Binary Search
D) Bubble Sort

Answer: A) Tower of Hanoi


Explanation: Tower of Hanoi uses recursion and can be viewed as backtracking.

9. Backtracking is a form of which general algorithm design technique?

A) Greedy
B) Divide and Conquer
C) Brute Force with pruning
D) Dynamic Programming

Answer: C) Brute Force with pruning


Explanation: It explores all solutions but prunes invalid paths early.

10. What data structure is commonly used implicitly in backtracking?

A) Queue
B) Stack
C) Linked List
D) Heap

Answer: B) Stack
Explanation: Recursion uses the call stack to manage backtracking states.

Branch and Bound in C – MCQs with Answers

1. What is the main idea of the Branch and Bound technique?

A) Explore all possible solutions without pruning


B) Divide the problem into smaller subproblems and use bounds to prune suboptimal
solutions
C) Use dynamic programming to store subproblem results
D) Make the greedy choice at each step

Answer: B) Divide the problem into smaller subproblems and use bounds to prune
suboptimal solutions
Explanation: Branch and Bound explores a search tree but cuts off branches that cannot
improve the best solution.

2. Which of the following problems is commonly solved using Branch and


Bound?

A) Merge Sort
B) Traveling Salesman Problem (TSP)
C) Linear Search
D) Bubble Sort

Answer: B) Traveling Salesman Problem (TSP)


Explanation: TSP is a classic NP-hard problem solved efficiently with Branch and Bound.

3. How does Branch and Bound prune the search space?

A) By using a heuristic to guess the solution


B) By calculating upper and lower bounds to discard suboptimal branches
C) By sorting the input data first
D) By iterating through all solutions

Answer: B) By calculating upper and lower bounds to discard suboptimal branches


Explanation: Bounds help to ignore branches that cannot yield better solutions.

4. What data structure is commonly used to manage nodes in Branch and


Bound?

A) Stack
B) Queue
C) Priority Queue (Min-Heap or Max-Heap)
D) Linked List

Answer: C) Priority Queue (Min-Heap or Max-Heap)


Explanation: Priority queues allow efficient retrieval of the next most promising node.
5. What is the difference between Branch and Bound and Backtracking?

A) Branch and Bound uses bounding to prune search space; Backtracking prunes based on
feasibility
B) Backtracking uses bounds; Branch and Bound explores all solutions
C) Both are the same
D) Branch and Bound is iterative; Backtracking is recursive only

Answer: A) Branch and Bound uses bounding to prune search space; Backtracking prunes
based on feasibility
Explanation: Branch and Bound incorporates bounds to estimate solution quality.

6. What is the primary goal of bounding in Branch and Bound?

A) To increase the size of the search tree


B) To eliminate branches that cannot improve the current best solution
C) To sort the input data
D) To store intermediate solutions

Answer: B) To eliminate branches that cannot improve the current best solution
Explanation: Bounding helps reduce unnecessary exploration.

7. In the context of Branch and Bound, what is a "node"?

A) A solution to the problem


B) A subproblem or partial solution in the search tree
C) The input data element
D) The output of the algorithm

Answer: B) A subproblem or partial solution in the search tree


Explanation: Nodes represent partial solutions or subproblems.

8. Which of the following is true about the time complexity of Branch and
Bound?

A) Always polynomial time


B) Always exponential time
C) Worst-case exponential, but often faster than brute force due to pruning
D) Always linear time

Answer: C) Worst-case exponential, but often faster than brute force due to pruning
Explanation: Pruning reduces search, but worst case remains exponential.
9. What role does a "best solution so far" play in Branch and Bound?

A) It is ignored during the search


B) It helps update bounds to prune more branches
C) It is the final output before the algorithm starts
D) It is used to sort input data

Answer: B) It helps update bounds to prune more branches


Explanation: The current best solution improves bounding.

10. Which data structure is NOT typically used in Branch and Bound
algorithms?

A) Priority Queue
B) Stack
C) Queue
D) Hash Table

Answer: D) Hash Table


Explanation: Hash tables are not commonly used for managing nodes in Branch and Bound.

NP-Hard Problems in C – MCQs with Answers

1. What does NP-hard mean in computational complexity?

A) Problems that can be solved in polynomial time


B) Problems as hard as the hardest problems in NP, but not necessarily in NP
C) Problems that can be solved by a nondeterministic Turing machine in polynomial time
D) Problems that are easy to solve

Answer: B) Problems as hard as the hardest problems in NP, but not necessarily in NP
Explanation: NP-hard problems are at least as hard as NP-complete problems but might not
be in NP.

2. Which of the following problems is known to be NP-hard?

A) Sorting an array
B) Traveling Salesman Problem (TSP)
C) Binary Search
D) Matrix Multiplication
Answer: B) Traveling Salesman Problem (TSP)
Explanation: TSP is a classic NP-hard problem.

3. If an NP-hard problem has a polynomial-time solution, what implication


does it have?

A) P = NP
B) P ≠ NP
C) The problem becomes easier
D) The problem is unsolvable

Answer: A) P = NP
Explanation: Finding a polynomial solution for NP-hard problems would prove P=NP.

4. NP-hard problems are usually solved by:

A) Exact polynomial-time algorithms


B) Heuristics or approximation algorithms
C) Linear search
D) Binary search

Answer: B) Heuristics or approximation algorithms


Explanation: NP-hard problems often require heuristics due to no known efficient exact
solutions.

5. Which of these statements is true?

A) All NP-hard problems are also NP-complete


B) All NP-complete problems are NP-hard
C) NP-hard problems are easier than NP-complete problems
D) NP-hard problems can always be solved in polynomial time

Answer: B) All NP-complete problems are NP-hard


Explanation: NP-complete problems are a subset of NP-hard problems.

6. Which problem is NOT NP-hard?

A) 3-Satisfiability (3-SAT)
B) Linear Search
C) Knapsack Problem (0/1)
D) Graph Coloring
Answer: B) Linear Search
Explanation: Linear search is a simple O(n) problem, not NP-hard.

7. What does NP stand for?

A) Non-Polynomial time
B) Non-deterministic Polynomial time
C) Numerical Polynomial time
D) Non-Parallel time

Answer: B) Non-deterministic Polynomial time


Explanation: NP is the class of problems verifiable in polynomial time by a nondeterministic
machine.

8. Which of the following is a known approach to handle NP-hard problems in


practice?

A) Use dynamic programming always


B) Use greedy algorithms exclusively
C) Use approximation algorithms or backtracking with pruning
D) Ignore the problem

Answer: C) Use approximation algorithms or backtracking with pruning


Explanation: These methods provide feasible solutions within reasonable time.

9. What is the difference between NP-complete and NP-hard?

A) NP-complete problems are solvable in polynomial time; NP-hard are not


B) NP-complete problems belong to NP and are as hard as any NP problem; NP-hard may not
belong to NP
C) NP-hard problems are easier than NP-complete problems
D) NP-hard problems have known polynomial algorithms

Answer: B) NP-complete problems belong to NP and are as hard as any NP problem; NP-
hard may not belong to NP
Explanation: NP-hard is a broader class.

10. Which is a common characteristic of NP-hard problems?

A) They have simple brute force solutions only


B) No known polynomial time algorithm exists to solve them exactly
C) They always require exponential space
D) They are always unsolvable

Answer: B) No known polynomial time algorithm exists to solve them exactly


Explanation: NP-hard problems have no known efficient exact solutions.

NP-Complete Problems in C – MCQs with Answers

1. What defines an NP-complete problem?

A) A problem solvable in polynomial time


B) A problem in NP that is as hard as every other problem in NP
C) A problem that cannot be verified in polynomial time
D) A problem easier than NP-hard problems

Answer: B) A problem in NP that is as hard as every other problem in NP


Explanation: NP-complete problems are both in NP and NP-hard.

2. Which of the following is a classic NP-complete problem?

A) Binary Search
B) 3-Satisfiability (3-SAT)
C) Merge Sort
D) Breadth First Search

Answer: B) 3-Satisfiability (3-SAT)


Explanation: 3-SAT is a fundamental NP-complete problem.

3. If a polynomial-time algorithm is found for any NP-complete problem, what


happens?

A) P ≠ NP
B) P = NP
C) The problem remains NP-complete
D) NP problems become unsolvable

Answer: B) P = NP
Explanation: Solving one NP-complete problem in polynomial time solves all NP problems
in polynomial time.

4. What is true about verifying solutions for NP-complete problems?


A) Verification can be done in polynomial time
B) Verification is impossible
C) Verification takes exponential time
D) Verification is the same as solving

Answer: A) Verification can be done in polynomial time


Explanation: By definition, NP problems have polynomial-time verifiable solutions.

5. Which of the following is NOT NP-complete?

A) Hamiltonian Cycle
B) Traveling Salesman Problem (decision version)
C) Sorting an array
D) Subset Sum

Answer: C) Sorting an array


Explanation: Sorting is solvable in polynomial time, so not NP-complete.

6. Which approach is commonly used to solve NP-complete problems in


practice?

A) Polynomial-time exact algorithms


B) Approximation algorithms and heuristics
C) Linear search
D) Brute force only

Answer: B) Approximation algorithms and heuristics


Explanation: Since exact solutions are often expensive, approximations are practical.

7. The decision version of the Knapsack Problem is classified as:

A) P
B) NP-complete
C) NP-hard but not in NP
D) Not a computational problem

Answer: B) NP-complete
Explanation: The decision knapsack problem is NP-complete.

8. NP-complete problems can be reduced to each other in:


A) Exponential time
B) Polynomial time
C) Constant time
D) They cannot be reduced

Answer: B) Polynomial time


Explanation: NP-complete problems are polynomial-time reducible to each other.

9. What is the relationship between NP, P, and NP-complete problems?

A) P ⊆ NP and NP-complete ⊆ NP
B) NP-complete ⊆ P ⊆ NP
C) P = NP-complete
D) NP and P are unrelated

Answer: A) P ⊆ NP and NP-complete ⊆ NP


Explanation: P problems are a subset of NP, and NP-complete problems lie within NP.

10. Which problem is often used to prove that other problems are NP-
complete?

A) Binary Search
B) 3-Satisfiability (3-SAT)
C) Quick Sort
D) Fibonacci calculation

Answer: B) 3-Satisfiability (3-SAT)


Explanation: 3-SAT is a common starting point for NP-completeness reductions.

You might also like