Jharkhand JSSC JTMACCE-2025
AI and Coding Question
Unit 1: Introduction to Artificial Intelligence (Coding/Implementation Focus) – 30 MCQs
1. Reflex Agent Implementation
Question:In implementing an intelligent agent for a simple environment (such as a vacuum cleaner world), consider the following Python code for a reflex agent:
def reflex_agent(location, status):
if status == 'Dirty':
return 'Suck'
elif location == 'A':
return 'Right'
else:
return 'Left'
print(reflex_agent('A', 'Dirty'))
What will be the output of the above code?
Options
a) Right
b) Left
c) Suck
d) None
Correct Answer
✅ c) Suck
Explanation (Detailed)
This code represents a Simple Reflex Agent, which makes decisions only based on the current percept (current location and cleanliness status) and does not use memory or past experience.
Step-by-Step Execution:
- The function is called as:
reflex_agent('A', 'Dirty') - The agent first checks:
if status == 'Dirty':- Since
status = 'Dirty', this condition is True.
- Since
- The function immediately returns:
'Suck' - The remaining conditions (
elif location == 'A'andelse) are not executed.
2 Question :-
To demonstrate the PEAS framework (Performance measure, Environment, Actuators, Sensors), consider a Taxi Agent environment.
The following Python function represents the performance measure, where lower distance traveled and lower fuel consumption are preferred.
def performance_measure(distance, fuel):
return - (distance + 2 * fuel)
What will be the return value of the function when:
distance = 5fuel = 2
Options
a) -9
b) -5
c) -4
d) 9
Correct Answer
✅ a) -9

3. Goal-Based Agent Debugging
Question
Debug the following code for a goal-based intelligent agent.
What fix is required to make it return “Goal Reached” when state == goal?
def goal_agent(state, goal):
if state = goal:
return 'Goal Reached'
else:
return 'Move'
Options
a) Change = to ==
b) Add else if
c) Remove return
d) None
Correct Answer
✅ a) Change = to ==
Explanation
=is an assignment operator (invalid in conditions)==is a comparison operator- Goal-based agents compare the current state with the goal
✔ Used in pathfinding and planning algorithms
4. Rule-Based AI vs Machine Learning
Question
To show the difference between Rule-Based AI and Machine Learning, consider this rule-based AI code.
What is the output?
def ai_rule(input):
if input > 10:
return 'High'
else:
return 'Low'
print(ai_rule(15))
Options
a) Low
b) High
c) Error
d) None
Correct Answer
✅ b) High
Explanation
- This is Rule-Based AI, not ML
- Decisions are made using fixed if–else rules
- ML would learn thresholds from data
✔ Demonstrates AI ≠ ML
5. Narrow AI in Healthcare
Question
To demonstrate Narrow AI in healthcare, consider this simple diagnostic agent.
What is the output for temp = 38?
def health_agent(temp):
if temp > 37:
return 'Fever'
return 'Normal'
print(health_agent(38))
Options
a) Normal
b) Fever
c) Error
d) None
Correct Answer
✅ b) Fever
Explanation
- Narrow AI performs one specific task
- Uses a fixed threshold
- Common in basic symptom checker apps
✔ Not capable of general medical reasoning
6. PEAS Implementation for Vacuum Agent
Question
Implement PEAS logic for a vacuum cleaner agent.
What action will be taken if location = 'B' and dirty = True?
def vacuum_peas(location, dirty):
if dirty:
return 'Suck'
if location == 'A':
return 'Right'
return 'Left'
print(vacuum_peas('B', True))
Options
a) Right
b) Left
c) Suck
d) None
Correct Answer
✅ c) Suck
Explanation
- Cleaning (
Suck) has highest priority - PEAS Actuators: Left, Right, Suck
- Reflects vacuum cleaner world
✔ Practical PEAS-based agent simulation
7. Debug Rational Agent
Question
Debug the following code to make the rational agent choose the maximum reward action.
def rational_agent(rewards):
return min(rewards)
Options
a) Change min to max
b) Add loop
c) Remove return
d) None
Correct Answer
✅ a) Change min to max
Explanation
- Rational agents always select the best (maximum reward) action
min()selects the worst option
✔ Used in decision-making and utility-based agents
8. AI vs Deep Learning (ReLU Example)
Question
To illustrate Deep Learning within AI, consider the ReLU activation function.
What is the output for x = -1?
def relu(x):
return max(0, x)
print(relu(-1))
Options
a) -1
b) 0
c) 1
d) Error
Correct Answer
✅ b) 0
Explanation
- ReLU =
max(0, x) - Removes negative values
- Adds non-linearity in neural networks
✔ Core Deep Learning concept
9. Autonomous Vehicle Sensor-Based Agent
Question
For an autonomous vehicle, implement a simple sensor-based agent.
What action is taken when obstacle = True?
def auto_agent(obstacle):
if obstacle:
return 'Stop'
return 'Go'
print(auto_agent(True))
Options
a) Go
b) Stop
c) Error
d) None
Correct Answer
✅ b) Stop
Explanation
- Reflex agent reacts to sensor input
- Immediate response without planning
✔ Used in obstacle avoidance systems
10. PEAS Environment – Sensors
Question
In the following PEAS environment code, what represents the sensor?
class PEAS:
def __init__(self):
self.sensors = 'Location, Status'
peas = PEAS()
print(peas.sensors)
Options
a) Location, Status
b) Action
c) Performance
d) None
Correct Answer
✅ a) Location, Status
Explanation
- Sensors collect environment information
- Essential for agent perception
✔ Core concept in agent design
11. Debug Model-Based Agent (Strong AI Aspiration)
Question
Debug the following code for a model-based intelligent agent.
Which fix is required to correctly update the internal belief?
def model_agent(belief, input):
belief = input
return belief
Options
a) No fix needed
b) Add if condition
c) Change = to ==
d) Add return input
Correct Answer
✅ a) No fix needed
Explanation
- Model-based agents update their internal belief state
- Assignment (
=) is correct here - The updated belief is returned properly
✔ Practical for advanced agent design and Strong AI concepts
12. Machine Learning as a Subset of AI
Question
To show ML as a subset of AI, consider a simple linear ML model.
What is the prediction for x = 2, slope = 3, intercept = 1?
def ml_model(x, slope, intercept):
return slope * x + intercept
print(ml_model(2, 3, 1))
Options
a) 6
b) 7
c) 5
d) None
Correct Answer
✅ b) 7
Explanation
3×2+1=7
✔ Demonstrates prediction using learned parameters
13. ChatGPT-Like Rule-Based Agent
Question
For a ChatGPT-like application, implement a simple rule-based chat agent.
What is the response for input "hello"?
def chat_agent(input):
if input == 'hello':
return 'Hi'
return 'Unknown'
print(chat_agent('hello'))
Options
a) Unknown
b) Hi
c) Error
d) None
Correct Answer
✅ b) Hi
Explanation
- Narrow AI
- Fixed rule-based response
- No learning involved
14. Agent–Environment Interaction
Question
Implement an environment for an agent.
What is the next state after action 'Right' from state 'A'?
def environment(state, action):
if action == 'Right' and state == 'A':
return 'B'
return state
print(environment('A', 'Right'))
Correct Answer
✅ b) B
Explanation
✔ Demonstrates state transition in agent-environment interaction
15. Debug PEAS Actuators
Question
Debug the PEAS actuator code.
Which fix ensures correct action output?
def peas_actuators(performance):
if performance < 0:
return 'Improve'
Correct Answer
✅ a) Add else return ‘Good’
Explanation
- PEAS loop must handle all performance cases
- Ensures proper feedback
16. Deep Learning Layer Example
Question
To differentiate Deep Learning from AI, compute the output of this neural layer.
def dl_layer(inputs, weights):
return sum(i*w for i,w in zip(inputs, weights))
print(dl_layer([1,2], [3,4]))
Correct Answer
✅ a) 11
Explanation
1×3+2×4=11
✔ Weighted sum = basic DL operation
17. Healthcare Alert Agent
Question
For a healthcare application, what is the action if heart_rate = 110?
def health_alert(heart_rate):
if heart_rate > 100:
return 'Alert'
return 'Normal'
print(health_alert(110))
Correct Answer
✅ b) Alert
Explanation
✔ Threshold-based medical alert system
18. Utility-Based Agent
Question
What does the utility-based agent return?
def utility_agent(options):
return max(options)
print(utility_agent([5,10]))
Correct Answer
✅ b) 10
Explanation
✔ Utility-based agents select maximum utility
19. Debug AI vs ML Fit Function
Question
Is any fix required in this ML fit function?
def ml_fit(data):
return sum(data) / len(data)
Correct Answer
✅ a) No fix
Explanation
✔ Mean calculation represents a simple ML model
20. Autonomous Sensor Agent
Question
For autonomous systems, what action is taken if distance = 5?
def auto_sensor(distance):
if distance < 10:
return 'Brake'
return 'Accelerate'
print(auto_sensor(5))
Correct Answer
✅ b) Brake
Explanation
✔ Reflex-based safety behavior
21. PEAS Performance Measure
Question
Compute the PEAS performance score.
def peas_performance(actions, goals):
return goals / actions
print(peas_performance(3, 2))
Correct Answer
✅ a) 0.666…
Explanation
✔ Performance metric in PEAS framework
22. Adaptive Agent (General AI Aspiration)
Question
What is the updated value?
def adaptive_agent(value, error):
if error:
value += 1
return value
print(adaptive_agent(5, True))
Correct Answer
✅ b) 6
Explanation
✔ Adaptive agent updates internal state
23. ChatGPT Simulation (Multi-Response Agent)
Question
What is the response for input 'bye'?
def chat_multi(input):
responses = {'hello': 'Hi', 'bye': 'Goodbye'}
return responses.get(input, 'Unknown')
print(chat_multi('bye'))
Correct Answer
✅ b) Goodbye
24. Debug Environment Update Code
Question
Is a fix required?
def env_update(state, action):
if action == 'Move':
state = 'New'
return state
Correct Answer
✅ a) No fix
Explanation
✔ Environment updates state correctly
25. Distinguish AI Agent from ML
Question
What is the output?
def ai_agent(input):
if input == 'danger':
return 'Avoid'
print(ai_agent('danger'))
Correct Answer
✅ a) Avoid
(Note: Without else, other inputs return None)
26. Simple DL Activation (Sigmoid)
Question
What is the sigmoid output for x = 0?
import math
def sigmoid(x):
return 1 / (1 + math.exp(-x))
print(sigmoid(0))
Correct Answer
✅ b) 0.5
Explanation
✔ Standard sigmoid function
27. Healthcare Monitoring Agent
Question
What is the output for value = 40?
def monitor_agent(value):
if value < 50:
return 'Low'
return 'OK'
print(monitor_agent(40))
Correct Answer
✅ b) Low
28. PEAS Environment – Actuators
Question
What are the actuators?
class PEAS:
actuators = ['Move', 'Act']
print(PEAS.actuators)
Correct Answer
✅ a) [‘Move’, ‘Act’]
29. Debug Goal Agent Code
Question
Is any fix required?
def goal_check(current, goal):
return current == goal
Correct Answer
✅ a) No fix
Explanation
✔ Correct equality check
30. Autonomous Decision Agent
Question
What is the action if speed = 70?
def speed_agent(speed):
if speed > 60:
return 'Slow Down'
return 'Maintain'
print(speed_agent(70))
Correct Answer
✅ b) Slow Down
Explanation
✔ Threshold-based autonomous decision making
Unit 2: Mathematics for Artificial Intelligence
Linear Algebra (Questions 1–16)
1. Vector Addition Using NumPy
Question
Implement vector addition in Python using NumPy. What is the output?
import numpy as np
v1 = np.array([1, 2])
v2 = np.array([3, 4])
print(v1 + v2)
Options
a) [4 6]
b) [1 2 3 4]
c) Error
d) 10
✅ Correct Answer
a) [4 6]
Explanation
- Vector addition is performed element-wise
- Used in feature vector combination in AI/ML
2. Debug Matrix Multiplication
Question
Fix the code to perform matrix multiplication correctly.
import numpy as np
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
print(A * B) # Element-wise, wrong for matmul
Options
a) Change * to @
b) Add np.dot(A, B)
c) Both a and b
d) None
✅ Correct Answer
c) Both a and b
Explanation
*→ element-wise multiplication@ornp.dot()→ matrix multiplication- Used in neural network layers
3. Eigenvalue Computation
Question
Find eigenvalues of the matrix [[1,0],[0,2]].
import numpy as np
M = np.array([[1,0],[0,2]])
eigvals = np.linalg.eigvals(M)
print(eigvals)
Options
a) [1. 2.]
b) [0. 0.]
c) Error
d) [3.]
✅ Correct Answer
a) [1. 2.]
Explanation
- Eigenvalues represent scaling along axes
- Used in PCA and covariance analysis
4. Eigenvector Finding
Question
What is the shape of eigenvectors for a 2×2 matrix?
import numpy as np
M = np.array([[1,2],[3,4]])
_, eigvecs = np.linalg.eig(M)
print(eigvecs.shape)
Options
a) (2,2)
b) (2,)
c) Error
d) (4,)
✅ Correct Answer
a) (2,2)
Explanation
- Each column is an eigenvector
- Used in dimensionality reduction
5. Debug SVD Code
Question
Is any fix required in this SVD code?
import numpy as np
M = np.array([[1,2],[3,4]])
U, S, V = np.linalg.svd(M, full_matrices=False)
print(S.shape)
✅ Correct Answer
a) No fix
Explanation
- Correct SVD implementation
- Used in PCA, compression, noise reduction
6. Matrix Inverse (Singular Matrix)
Question
What happens if the matrix is singular?
import numpy as np
M = np.array([[1,2],[2,4]])
try:
inv = np.linalg.inv(M)
except:
print('Singular')
✅ Correct Answer
a) Prints Singular
Explanation
- Singular matrices are non-invertible
- Important for linear regression stability
7. Vector Dot Product
Question
Compute dot product of [1,2] and [3,4].
import numpy as np
v1 = np.array([1,2])
v2 = np.array([3,4])
print(np.dot(v1, v2))
✅ Correct Answer
a) 11
Explanation
1×3+2×4=11
✔ Used in cosine similarity
8. Matrix Transpose
Question
What is the output shape after transpose?
import numpy as np
M = np.array([[1,2],[3,4],[5,6]])
print(M.T.shape)
✅ Correct Answer
a) (2,3)
Explanation
- Transpose swaps rows and columns
- Used in data preprocessing
9. Eigenvalues with Complex Numbers
Question
Does NumPy handle complex eigenvalues?
import numpy as np
M = np.array([[0,-1],[1,0]])
eig = np.linalg.eig(M)
print(eig[0])
✅ Correct Answer
a) No fix, handles complex
Explanation
- NumPy supports complex eigenvalues
- Used in rotations & transformations
10. Vector Norm
Question
Find the norm of [3,4].
import numpy as np
v = np.array([3,4])
print(np.linalg.norm(v))
✅ Correct Answer
a) 5
Explanation
32+42=5
✔ Used in distance metrics
11. SVD Low-Rank Approximation
Question
What is the output shape of low-rank approximation?
import numpy as np
M = np.array([[1,2],[3,4]])
U, S, V = np.linalg.svd(M)
approx = U[:,:1] @ np.diag(S[:1]) @ V[:1,:]
print(approx.shape)
✅ Correct Answer
a) (2,2)
Explanation
- Rank-1 approximation
- Used in compression & recommender systems
12. Vector Norm (L2 Norm)
Question
Compute L2 norm of [3,4].
import numpy as np
v = np.array([3,4])
print(np.linalg.norm(v))
✅ Correct Answer
a) 5.0
13. Matrix Determinant
Question
Find determinant of [[1,2],[3,4]].
import numpy as np
M = np.array([[1,2],[3,4]])
print(np.linalg.det(M))
✅ Correct Answer
a) -2.0
Explanation
(1×4)−(2×3)=−2
✔ Used to check invertibility
14. Debug Eigenvector Code
Question
Fix code to obtain eigenvalues and eigenvectors.
import numpy as np
M = np.array([[1,0],[0,1]])
eigvals = np.linalg.eigvals(M)
✅ Correct Answer
a) Change to np.linalg.eig
15. Matrix Rank
Question
Find the rank of [[1,2],[2,4]].
import numpy as np
M = np.array([[1,2],[2,4]])
print(np.linalg.matrix_rank(M))
✅ Correct Answer
a) 1
Explanation
- Rows are linearly dependent
- Used in SVD & feature reduction
16. Vector Projection
Question
Find projection of [1,0] onto [1,1].
import numpy as np
u = np.array([1,0])
v = np.array([1,1])
proj = np.dot(u, v) / np.dot(v, v) * v
print(proj)
✅ Correct Answer
a) [0.5 0.5]

Unit 2: Mathematics for Artificial Intelligence
Probability & Statistics (Questions 16–25)
16. Random Variable Sampling from Normal Distribution
Question
Generate random samples from a normal distribution. What is the mean of 100 samples?
import numpy as np
samples = np.random.normal(0, 1, 100)
print(np.mean(samples))
Options
a) Close to 0
b) Exactly 1
c) Error
d) None
✅ Correct Answer
a) Close to 0
Explanation
- Samples are drawn from N(0, 1)
- By the Law of Large Numbers, the sample mean approaches 0
- Used in Monte Carlo simulations
17. Bayes Theorem
Question
Compute P(A∣B) using Bayes theorem.
def bayes(p_b_a, p_a, p_b):
return (p_b_a * p_a) / p_b
print(bayes(0.8, 0.3, 0.4))
Options
a) 0.6
b) 0.32
c) Error
d) 0.24
✅ Correct Answer
a) 0.6

18. Poisson Distribution – PMF
Question
Find P(k=2,λ=3) using Poisson PMF.
from scipy.stats import poisson
print(poisson.pmf(2, 3))
Options
a) ~0.224
b) 1
c) Error
d) 0
✅ Correct Answer
a) ~0.224
Explanation
- Poisson models event counts
- Used in queueing systems & traffic modeling
19. Hypothesis Test (t-test)
Question
Is any fix required in this independent t-test code?
from scipy import stats
data1 = [1,2,3]
data2 = [4,5,6]
t, p = stats.ttest_ind(data1, data2)
print(p)
Options
a) No fix
b) Use Mann–Whitney U
c) Add equal_var
d) None
✅ Correct Answer
a) No fix
Explanation
- Correct two-sample t-test
- Used in A/B testing
20. Normal Distribution – CDF
Question
Compute CDF of standard normal at 0.
from scipy.stats import norm
print(norm.cdf(0))
Options
a) 0.5
b) 0
c) 1
d) Error
✅ Correct Answer
a) 0.5
Explanation
- Symmetry of standard normal distribution
- Widely used in probability estimation
21. Random Variable Variance
Question
Find variance of [1,2,3].
import numpy as np
data = np.array([1,2,3])
print(np.var(data))
Options
a) 0.666…
b) 2
c) Error
d) 1
✅ Correct Answer
a) 0.666…

✔ Measures spread of data
22. Bayes Update (Posterior)
Question
Compute posterior probability using Bayes update.
def bayes_update(prior, lik, ev):
return (lik * prior) / ev
print(bayes_update(0.5, 0.9, 0.6))
Options
a) 0.75
b) 0.45
c) Error
d) 0.3
✅ Correct Answer
a) 0.75

23. Poisson Distribution – CDF
Question
Compute Poisson CDF for k=2,λ=1.
from scipy.stats import poisson
print(poisson.cdf(2, 1))
Options
a) ~0.919
b) 1
c) Error
d) 0
✅ Correct Answer
a) ~0.919
Explanation
- CDF gives probability of ≤ k events
- Used in queueing theory
24. Hypothesis P-Value (Chi-Square)
Question
Compute p-value for chi-square test.
from scipy.stats import chi2
print(1 - chi2.cdf(5, 2))
Options
a) ~0.082
b) 1
c) Error
d) 0
✅ Correct Answer
a) ~0.082
Explanation
- P-value measures statistical significance
- Used in feature independence tests
25. Uniform Random Variable
Question
Is any fix required in this uniform random sampling code?
import numpy as np
samples = np.random.uniform(0, 1, 10)
print(np.mean(samples))
Options
a) No fix
b) Change to normal
c) Add seed
d) None
✅ Correct Answer
a) No fix
Explanation
- Correct uniform sampling
- Mean ≈ 0.5 for large samples
- Used in random initialization
Jharkhand JSSC JTMACCE-2025
📘 Calculus (Questions 26–30)
26. Derivative Approximation (Finite Difference)
Question
Approximate the derivative of f(x)=x2 at x=2 using finite differences with h=0.001.
def deriv(f, x, h):
return (f(x+h) - f(x)) / h
f = lambda x: x**2
print(deriv(f, 2, 0.001))
Options
a) ~4.001
b) 2
c) Error
d) 0
✅ Answer
a) ~4.001
Explanation
- True derivative of x2 is 2x
- At x=2: derivative = 4
- Finite difference gives a close approximation
- Widely used in numerical optimization and gradient estimation
27. Partial Derivative (w.r.t x)
Question
Compute the partial derivative with respect to x of
f(x,y)=x2+y2 at (1,1).
def partial_x(x, y, h):
f = lambda x: x**2 + y**2
return (f(x+h) - f(x)) / h
print(partial_x(1, 1, 0.001))
Options
a) ~2.001
b) 1
c) Error
d) 0
✅ Answer
a) ~2.001

28. Gradient Vector
Question
Find the gradient of vector function

at point (1,1).
import numpy as np
def grad(x, y):
return np.array([2*x, 3*y**2])
print(grad(1,1))
Options
a) [2 3]
b) [1 1]
c) Error
d) [0 0]
✅ Answer
a) [2 3]
Explanation
- Gradient gives direction of steepest increase
- Essential for gradient descent algorithms
29. Gradient Descent Update Step
Question
Perform one GD step for loss L=w2 with learning rate = 0.1 and w=2.
def gd_step(w, lr):
grad = 2*w
return w - lr * grad
print(gd_step(2, 0.1))
Options
a) 1.6
b) 2.4
c) Error
d) 0
✅ Answer
a) 1.6
Explanation
- Gradient = 2w=4
- Update: 2−0.1×4=1.6
- Core concept in machine learning training
30. Debug Gradient Descent Loop
Question
Is the following gradient descent loop correct?
w = 10
for _ in range(10):
w -= 0.1 * 2*w
print(w)
Options
a) No fix, converges to 0
b) Add break
c) Change -= to +=
d) None
✅ Answer
a) No fix, converges to 0
Explanation
- Correct GD formula applied
- Minimizes w2
- Converges toward global minimum w=0
📘 Calculus (Questions 31–35)
31. Partial Derivative (w.r.t y)
Question
Find ∂y∂(x⋅y) at x=2,y=3.
def partial_y(x, y, h):
f = lambda y: x * y
return (f(y+h) - f(y)) / h
print(partial_y(2, 3, 0.001))
Options
a) ~2.0
b) 3.0
c) Error
d) 6.0
✅ Answer
a) ~2.0
Explanation
- ∂y∂(xy)=x
- Used in loss function gradients
32. Stochastic Gradient Descent (SGD)
Question
Perform one SGD update step.
def sgd(w, sample_grad, lr):
return w - lr * sample_grad
print(sgd(1, 0.5, 0.1))
Options
a) 0.95
b) 1.05
c) Error
d) 0
✅ Answer
a) 0.95
Explanation
- Single-sample update
- Used for large-scale ML problems
33. Optimization Convergence Check
Question
Check if optimization has converged.
def converge(old, new, tol=0.01):
return abs(old - new) < tol
print(converge(1.0, 1.005))
Options
a) True
b) False
c) Error
d) None
✅ Answer
a) True
Explanation
- Difference < tolerance → convergence achieved
- Used in iterative algorithms
34. Debug Vector Gradient
Question
Is the vector gradient implementation correct?
import numpy as np
def vec_grad(params):
return np.array([2*params[0], 2*params[1]])
print(vec_grad([1,2]))
Options
a) No fix
b) Change to [params**2]
c) Add np.gradient
d) None
✅ Answer
a) No fix
Explanation
- Correct gradient of x2+y2
- Common in multi-parameter optimization
35. Adam Optimizer Step (Simplified)
Question
Perform a simplified Adam optimizer step.
def adam_step(w, grad, lr=0.01):
return w - lr * grad
print(adam_step(5, 2))
Options
a) 4.98
b) 5.02
c) Error
d) None
✅ Answer
a) 4.98
Explanation
- Simplified form (without momentum terms)
- Adam is widely used in deep learning
📘 Discrete Mathematics (Questions 36–40)
36. Graph Adjacency List
Question
Implement a graph using an adjacency list.
What are the neighbors of node 0?
graph = {0: [1,2], 1: [0], 2: [0]}
print(graph[0])
Options
a) [1,2]
b) [0]
c) Error
d) None
✅ Answer
a) [1,2]
Explanation
- Adjacency list stores neighbors of each vertex
- Node
0is connected to nodes1and2 - Widely used in graph and network algorithms
37. Breadth-First Search (BFS) Traversal
Question
Implement BFS traversal for a tree.
What is the visit order starting from root 0?
from collections import deque
def bfs(root, graph):
q = deque([root])
visited = []
while q:
node = q.popleft()
visited.append(node)
q.extend(graph[node])
return visited
graph = {0: [1,2], 1: [], 2: []}
print(bfs(0, graph))
Options
a) [0,1,2]
b) [0,2,1]
c) Error
d) [1,2,0]
✅ Answer
a) [0,1,2]
Explanation
- BFS explores level by level
- Uses a queue (FIFO)
- Practical in search problems, shortest path in unweighted graphs
38. Graph Cycle Detection
Question
Debug the following code for cycle detection in an undirected graph.
def has_cycle(graph):
# Simple check for self-loop
for node in graph:
if node in graph[node]:
return True
return False
Options
a) No fix for simple
b) Add DFS
c) Change to directed
d) None
✅ Answer
b) Add DFS
Explanation
- Checking only self-loops is insufficient
- Cycles in undirected graphs require:
- DFS with visited + parent tracking
- Essential in network reliability and graph validation
39. Network Shortest Path (Dijkstra’s Algorithm)
Question
Compute the shortest distance from node 0 to node 1.
import heapq
def short_path(graph, start):
dist = {n: float('inf') for n in graph}
dist[start] = 0
pq = [(0, start)]
while pq:
d, node = heapq.heappop(pq)
for nei, w in graph[node]:
new_d = d + w
if new_d < dist[nei]:
dist[nei] = new_d
heapq.heappush(pq, (new_d, nei))
return dist
graph = {0: [(1,5)], 1: []}
print(short_path(graph, 0)[1])
Options
a) 5
b) inf
c) Error
d) 0
✅ Answer
a) 5
Explanation
- Dijkstra’s algorithm computes minimum path cost
- Edge weight from 0 → 1 is 5
- Used in routing, GPS, network optimization
40. Tree Height Calculation
Question
Compute the height of a tree.
def tree_height(tree, node):
if not tree[node]:
return 0
return 1 + max(tree_height(tree, child) for child in tree[node])
tree = {0: [1,2], 1: [], 2: []}
print(tree_height(tree, 0))
Options
a) 1
b) 2
c) 0
d) Error
✅ Answer
a) 1
Explanation
- Tree height = longest path from root to leaf
- Root → leaf = 1 edge
- Important in decision trees, recursion depth, balancing
Jharkhand JSSC JTMACCE-2025
📘 Unit 3: Programming Fundamentals & Coding
Programming Languages Basics (Questions 1–15)
1. Data Types in Python
Question
What is the output of the following Python code?
x = 5
y = "Hello"
print(type(x), type(y))
Options
a) <class 'int'> <class 'str'>
b) int str
c) Error
d) 5 Hello
✅ Answer
a) <class 'int'> <class 'str'>
Explanation
type()returns the data type of a variablexis an integer,yis a string- Practical for debugging and type checking
2. Debug C++ Conditional Statement
Question
Fix the C++ code to print “Pass” if score > 50.
#include <iostream>
int main() {
int score = 60;
if (score > 50)
std::cout << "Pass";
else
std::cout << "Fail";
return 0;
}
Options
a) No fix needed
b) Add {} around cout
c) Change > to <
d) None
✅ Answer
a) No fix needed
Explanation
- Condition is correct
- Code prints “Pass”
- Practical in grading and decision logic
3. Python Loop to Sum 1 to 5
Question
What is the output?
sum = 0
for i in range(1,6):
sum += i
print(sum)
Options
a) 15
b) 6
c) Error
d) 5
✅ Answer
a) 15
Explanation
- Adds numbers from 1 to 5
- Formula: 1+2+3+4+5 = 15
- Practical in accumulation problems
4. Python Function to Return Square
Question
Debug the function.
def square(x):
return x * x
print(square(3))
Options
a) No fix
b) Change * to **
c) Add int(x)
d) None
✅ Answer
a) No fix
Explanation
x * xcorrectly computes square- Practical in mathematical functions
5. C++ Loop Output
Question
What is the output?
#include <iostream>
int main() {
for(int i=1; i<=3; i++) {
std::cout << i << " ";
}
return 0;
}
Options
a) 1 2 3
b) 1 2
c) Error
d) Infinite
✅ Answer
a) 1 2 3
Explanation
- Loop runs from 1 to 3
- Practical in iteration and counters
6. Python Module Import
Question
What is the output if mymod.py contains def greet(): return "Hi"?
import mymod
print(mymod.greet())
Options
a) Hi
b) Error
c) greet
d) None
✅ Answer
a) Hi
Explanation
- Functions are accessed via
module.function() - Practical in code reuse and modular programming
7. Debug C++ Data Type
Question
Fix the C++ code to print a float.
#include <iostream>
int main() {
float f = 3.14;
std::cout << f;
return 0;
}
Options
a) No fix
b) Change float to int
c) Add cast
d) None
✅ Answer
a) No fix
Explanation
- Float is correctly declared and printed
- Practical in numeric computations
8. Python Conditional Statement
Question
Output if age = 20?
age = 20
if age >= 18:
print("Adult")
else:
print("Minor")
Options
a) Adult
b) Minor
c) Error
d) None
✅ Answer
a) Adult
Explanation
- Age ≥ 18 → Adult
- Practical in eligibility checks
9. Implement C++ Function
Question
What is the output?
#include <iostream>
int add(int a, int b) {
return a + b;
}
int main() {
std::cout << add(2,3);
return 0;
}
Options
a) 5
b) Error
c) 23
d) None
✅ Answer
a) 5
Explanation
- Function returns sum
- Practical in modular programming
10. Debug Python Loop
Question
Fix the loop to print 0 to 4.
i = 0
while i < 5:
print(i)
i += 1
Options
a) No fix
b) Change < to >
c) Add break
d) None
✅ Answer
a) No fix
Explanation
- Loop correctly prints 0–4
- Practical in while-loop logic
11. Python Data Type Conversion
Question
What is the output?
print(int("123"))
Options
a) 123
b) “123”
c) Error
d) None
✅ Answer
a) 123
Explanation
- Converts string to integer
- Practical in user input handling
12. C++ Conditional Statement
Question
Output if x=5, y=10?
#include <iostream>
int main() {
int x=5, y=10;
if(x < y) std::cout << "Less";
else std::cout << "More";
return 0;
}
Options
a) Less
b) More
c) Error
d) None
✅ Answer
a) Less
Explanation
- 5 < 10 → “Less”
- Practical in comparisons
13. Python Loop with Break
Question
What is the output?
for i in range(5):
if i == 3:
break
print(i)
Options
a) 0 1 2
b) 0 1 2 3 4
c) Error
d) 3
✅ Answer
a) 0 1 2
Explanation
breakexits loop at i = 3- Practical in early termination
14. Debug C++ Include Statement
Question
Fix the code to use sqrt().
#include <iostream>
int main() {
std::cout << sqrt(4);
return 0;
}
Options
a) Add #include <cmath>
b) Change sqrt to pow
c) Remove main
d) None
✅ Answer
a) Add #include <cmath>
Explanation
- Math functions need
<cmath> - Practical in library usage
15. Python Function with Default Argument
Question
What is the output?
def func(x=10):
return x * 2
print(func(5))
Options
a) 10
b) 20
c) Error
d) None
✅ Answer
a) 10
Explanation
- Passed value
5overrides default - Default used only when no argument provided
- Practical in flexible APIs
📘 Unit 3: Programming Fundamentals & Coding
Programming + Object-Oriented Programming (Questions 16–25)
16. C++ Loop with continue
Question
What is the output of the following C++ code?
#include <iostream>
int main() {
for(int i=1; i<=3; i++) {
if(i==2) continue;
std::cout << i << " ";
}
return 0;
}
Options
a) 1 3
b) 1 2 3
c) Error
d) 2
✅ Answer
a) 1 3
Explanation
continueskips the current iteration- When
i == 2, printing is skipped - Output includes only 1 and 3
- Practical in selective processing
17. Python List Concatenation
Question
What is the output?
print([1,2] + [3])
Options
a) [1,2,3]
b) 6
c) Error
d) None
✅ Answer
a) [1,2,3]
Explanation
+concatenates lists- Does not perform arithmetic addition
- Practical in data aggregation
18. Debug Python Module Alias
Question
Fix the code to print the value of π.
import math as m
print(m.pi)
Options
a) No fix
b) Change to import math
c) Add from math import pi
d) None
✅ Answer
a) No fix
Explanation
- Alias
mcorrectly refers tomath m.piis valid- Practical in clean imports
19. C++ Nested Conditional
Question
What is the output if a=5, b=10, c=15?
#include <iostream>
int main() {
int a=5, b=10, c=15;
if(a < b) {
if(b < c) std::cout << "Increasing";
}
return 0;
}
Options
a) Increasing
b) Nothing
c) Error
d) None
✅ Answer
a) Increasing
Explanation
- Both conditions are true
- Nested
ifexecutes - Practical in multi-level decision logic
20. Python Module Function Call
Question
If mymod.py contains:
def greet():
return "Hi"
What is the output?
import mymod
print(mymod.greet())
Options
a) Hi
b) Error
c) greet
d) None
✅ Answer
a) Hi
Explanation
- Module functions are accessed via
module.function() - Practical in code reuse and modularity
🧩 Object-Oriented Programming (Questions 21–25)
21. Python Class Implementation
Question
What is the output?
class A:
def __init__(self):
self.x = 5
obj = A()
print(obj.x)
Options
a) 5
b) Error
c) None
d) A
✅ Answer
a) 5
Explanation
- Constructor initializes instance variable
x - Practical in data encapsulation
22. Debug C++ Class Code
Question
Fix the code to print 10.
#include <iostream>
class B {
public:
int y = 10;
};
int main() {
B obj;
std::cout << obj.y;
return 0;
}
Options
a) No fix
b) Add constructor
c) Change public to private
d) None
✅ Answer
a) No fix
Explanation
- Public members are directly accessible
- Practical in basic OOP design
23. Python Inheritance
Question
What is the output?
class Parent:
def method(self):
return "Parent"
class Child(Parent):
pass
c = Child()
print(c.method())
Options
a) Parent
b) Child
c) Error
d) None
✅ Answer
a) Parent
Explanation
- Child inherits methods from Parent
- Practical in code reuse
24. C++ Polymorphism
Question
What is the output?
#include <iostream>
class Base {
public:
virtual void show() { std::cout << "Base"; }
};
class Derived : public Base {
public:
void show() { std::cout << "Derived"; }
};
int main() {
Base* b = new Derived();
b->show();
return 0;
}
Options
a) Derived
b) Base
c) Error
d) None
✅ Answer
a) Derived
Explanation
virtualenables runtime polymorphism- Function resolved at runtime
- Practical in dynamic binding
25. Python Encapsulation (Private Members)
Question
Fix the code to access private variable __z.
class C:
def __init__(self):
self.__z = 20
obj = C()
print(obj.__z)
Options
a) Change to obj._C__z
b) Make variable public
c) Add getter method
d) All
✅ Answer
d) All
Explanation
- Python uses name mangling
- Access possible via mangled name, getter, or public variable
- Practical in data hiding
Unit 3: Programming Fundamentals & Coding
Object-Oriented Programming (Questions 26–40)
Formatted consistently with clear questions, options, correct answers, and practical explanations.
📘 Unit 3: Programming Fundamentals & Coding
Object-Oriented Programming (Questions 26–40)
26. Python Class Method
Question
What is the output of A.greet()?
class A:
@classmethod
def greet(cls):
return "Hi"
print(A.greet())
Options
a) Hi
b) Error
c) A
d) None
✅ Answer
a) Hi
Explanation
@classmethodworks on the class, not instanceclsrefers to classA- Practical in factory methods and shared behavior
27. C++ Inheritance
Question
What is the output?
#include <iostream>
class Base {
public:
int val = 100;
};
class Derived : public Base {};
int main() {
Derived d;
std::cout << d.val;
return 0;
}
Options
a) 100
b) Error
c) 0
d) None
✅ Answer
a) 100
Explanation
- Public members are inherited
- Practical in class reuse
28. Python Polymorphism (Method Overriding)
Question
What is the output?
class Animal:
def sound(self):
return "Sound"
class Dog(Animal):
def sound(self):
return "Bark"
d = Dog()
print(d.sound())
Options
a) Bark
b) Sound
c) Error
d) None
✅ Answer
a) Bark
Explanation
- Child overrides parent method
- Demonstrates runtime polymorphism
29. Debug C++ Constructor Code
Question
Fix the constructor call.
#include <iostream>
class D {
public:
D() { std::cout << "Created"; }
};
int main() {
D obj;
return 0;
}
Options
a) No fix
b) Add parameters
c) Remove ()
d) None
✅ Answer
a) No fix
Explanation
- Constructor automatically executes on object creation
- Practical in object initialization
30. Python Encapsulation with Getter
Question
What is the output?
class E:
def __init__(self):
self.__secret = "Hidden"
def get_secret(self):
return self.__secret
e = E()
print(e.get_secret())
Options
a) Hidden
b) Error
c) __secret
d) None
✅ Answer
a) Hidden
Explanation
- Getter provides controlled access
- Demonstrates encapsulation
31. C++ Polymorphism with Virtual Function
Question
What is the output?
#include <iostream>
class Base {
public:
virtual ~Base() {}
virtual void print() { std::cout << "Base"; }
};
class Derived : public Base {
void print() { std::cout << "Derived"; }
};
int main() {
Base* b = new Derived();
b->print();
delete b;
return 0;
}
Options
a) Derived
b) Base
c) Error
d) None
✅ Answer
a) Derived
Explanation
- Virtual functions enable dynamic binding
- Method resolved at runtime
32. Python Multiple Inheritance (MRO)
Question
What is the output?
class A:
def method(self):
return "A"
class B:
def method(self):
return "B"
class C(A, B):
pass
c = C()
print(c.method())
Options
a) A
b) B
c) Error
d) None
✅ Answer
a) A
Explanation
- Python follows Method Resolution Order (left-to-right)
- A is searched before B
33. Python Class Attribute
Question
Fix to print 42.
class F:
attr = 42
print(F.attr)
Options
a) No fix
b) Add self
c) Create instance
d) None
✅ Answer
a) No fix
Explanation
- Class attributes accessed via class name
- Practical in shared constants
34. C++ Encapsulation with Private Member
Question
What is the output?
#include <iostream>
class G {
private:
int priv = 50;
public:
int get_priv() { return priv; }
};
int main() {
G g;
std::cout << g.get_priv();
return 0;
}
Options
a) 50
b) Error (private)
c) None
d) 0
✅ Answer
a) 50
Explanation
- Private data accessed via public method
- Core concept of encapsulation
35. Python super() in Inheritance
Question
What is the output?
class Parent:
def method(self):
return "Parent"
class Child(Parent):
def method(self):
return super().method() + " Child"
c = Child()
print(c.method())
Options
a) Parent Child
b) Child
c) Error
d) None
✅ Answer
a) Parent Child
Explanation
super()calls parent implementation- Used to extend behavior
37. C++ Friend Function
Question
What does the friend function allow?
#include <iostream>
class H {
private:
int data = 60;
friend void print(H&);
};
void print(H& h) {
std::cout << h.data;
}
int main() {
H h;
print(h);
return 0;
}
Options
a) 60
b) Error
c) None
d) 0
✅ Answer
a) 60
Explanation
- Friend functions can access private members
- Useful for tight coupling
38. Python Abstract Class
Question
How is abstraction enforced?
from abc import ABC, abstractmethod
class I(ABC):
@abstractmethod
def must(self):
pass
class J(I):
def must(self):
return "Implemented"
j = J()
print(j.must())
Options
a) Implemented
b) Error if not implemented
c) ABC
d) None
✅ Answer
a) Implemented
Explanation
- Abstract methods must be implemented
- Enforces abstraction contract
39. Debug C++ Inheritance Visibility
Question
Fix needed to access protected member?
#include <iostream>
class Base {
protected:
int prot = 70;
};
class Derived : public Base {
public:
void show() { std::cout << prot; }
};
int main() {
Derived d;
d.show();
return 0;
}
Options
a) No fix
b) Change protected to public
c) Add friend
d) None
✅ Answer
a) No fix
Explanation
- Protected members are accessible in derived classes
- Practical in controlled inheritance
40. Python Duck Typing (Polymorphism)
Question
What is the output?
class K:
def quack(self):
return "Quack"
class L:
def quack(self):
return "Bark"
def make_quack(obj):
return obj.quack()
print(make_quack(L()))
Options
a) Bark
b) Quack
c) Error
d) None
✅ Answer
a) Bark
Explanation
- Duck typing depends on behavior, not class
- If it “quacks”, it works 🦆
- Core Python polymorphism concept
Jharkhand JSSC JTMACCE-2025
