By Muhammad Abdullah AwaisPublished
Programming MCQs rarely ask you to write code. More often you read a short snippet and predict what it does, which tests both the language rules and your ability to trace without running it.
This guide revises the Programming area from data types to OOP, binding, exceptions and memory. Most sections end with a "what is the output?" question and a step-by-step trace. Try each one before reading the answer.
The weightage published for the NSCT syllabus gives Programming 10% (see our syllabus page, and confirm in the official student guide on nsct.hec.gov.pk). Tracing skill also carries over to Problem Solving, which is listed at 20%.
Data Types: Where Most Traps Start
| Concept | C++ | Java | Python 3 |
|---|---|---|---|
| Integer sizes | Implementation-defined minimums (char is always 1 byte) |
Fixed: byte 1, short 2, int 4, long 8 bytes |
Arbitrary-precision int |
| Integer overflow | Signed overflow is undefined behaviour; unsigned wraps | Wraps silently (Integer.MAX_VALUE + 1 is Integer.MIN_VALUE) |
No overflow for int |
7 / 2 |
3 |
3 |
3.5 (true division) |
-7 / 2 |
-3 (truncates toward zero) |
-3 |
-3.5; -7 // 2 is -4 |
-7 % 2 |
-1 |
-1 |
1 (sign follows divisor) |
char |
1 byte, integer type | 2-byte UTF-16 unit, numeric | No separate char type |
| Strings | std::string is mutable |
String is immutable |
str is immutable |
Practise these on the Data Types & Variables topic.
MCQ 1 (C++): integer division before assignment
int a = 7, b = 2;
double c = a / b;
cout << c << " " << a % b * 3 + 1;
Answer: 3 4
a / bis evaluated first, and both operands areint, so the result is integer3.- Only then is
3converted todouble, giving3.0.coutprints a whole-valueddoubleas3. %and*have the same precedence and associate left to right:a % bis1, then1 * 3is3, then+ 1gives4.
The trap option is 3.5, which needs a cast before dividing: (double)a / b.
Operators and Precedence
You do not need the full precedence table, only the rows most trace questions depend on:
- Unary operators (
!,++,--, unary-) bind tighter than arithmetic. *,/,%bind tighter than+and-.- Relational operators (
<,>=) bind tighter than equality (==,!=). &&binds tighter than||, and both short-circuit.- Assignment is right-associative:
a = b = 5assignsbfirst. - In Python,
**is right-associative:2 ** 3 ** 2is2 ** 9, which is512, not64.
MCQ 2 (Java): string concatenation order
System.out.println(1 + 2 + "3" + 4 + 5);
System.out.println('A' + 1);
Answer: 3345, then 66
+associates left to right.1 + 2is integer addition, giving3.3 + "3"involves aString, so it becomes concatenation:"33".- From here every
+is concatenation:"334", then"3345". - In the second line,
'A'is acharwith value 65.char + intis numeric addition, so the result is theint66. To printB, you would need(char)('A' + 1).
MCQ 3 (Java): increments and short-circuiting
int x = 5;
int y = x++ + ++x;
int a = 0;
boolean r = (a > 0) && (++a > 0);
System.out.println(x + " " + y + " " + a + " " + r);
Answer: 7 12 0 false
- Java evaluates operands left to right.
x++yields5, thenxbecomes6. ++xmakesxequal to7and yields7. Soy = 5 + 7 = 12.a > 0isfalse, so&&short-circuits and++anever runs.astays0.
A useful exam note: the same x++ + ++x line in C++ is undefined behaviour, because the two modifications of x are unsequenced. If an MCQ shows it in C++, "undefined behaviour" is the answer to look for. More drills are on the Operators & Expressions topic.
Control Flow
Loop and switch questions look easy but are often missed under time pressure. Two habits help: write the loop variable's values in a column (for i = 1; i <= 10; i += 3, that is 1, 4, 7, 10), and remember that switch in C, C++ and Java falls through until it meets a break.
MCQ 4 (Java): switch fall-through
int k = 2;
switch (k) {
case 1: System.out.print("one ");
case 2: System.out.print("two ");
case 3: System.out.print("three ");
default: System.out.print("other");
}
Answer: two three other
Execution jumps to case 2 and, with no break anywhere, runs every statement below it, including default.
Functions and Recursion
For recursion questions, write each call on its own line, then fill in return values from the bottom up. Know parameter passing too: C++ copies arguments by value unless the parameter is a reference (int& b), so changes reach the caller. The Functions / Methods topic drills both.
MCQ 5 (Python): recursion with a step of two
def f(n):
if n <= 1:
return 1
return n * f(n - 2)
print(f(7))
Answer: 105
f(7) = 7 * f(5)f(5) = 5 * f(3)f(3) = 3 * f(1)f(1) = 1(base case)
Unwinding: 3 * 1 = 3, 5 * 3 = 15, 7 * 15 = 105.
Arrays and Strings
Key facts to have ready:
- Java arrays have a
lengthfield,Stringhas alength()method, andArrayListhassize(). - Java array elements get default values:
0for numbers,falseforboolean,nullfor references. - In C and C++,
char s[] = "abc";occupies 4 bytes, because of the terminating'\0'. - In Java,
==on objects compares references; useequals()to compare string contents. - Python slicing never raises an
IndexErrorfor out-of-range bounds; indexing does.
MCQ 6 (Python): slicing and aliasing
s = "NSCTPREP"
print(s[2:5], s[::-1][0], s[-3:])
a = [1, 2, 3]
b = a
b.append(4)
c = a[:]
c.append(5)
print(len(a), len(b), len(c))
Answer: CTP P REP, then 4 4 5
- Indices: N=0, S=1, C=2, T=3, P=4, R=5, E=6, P=7.
s[2:5]takes indices 2, 3 and 4:CTP. s[::-1]reverses the string; its first character is the original last one,P.s[-3:]is the last three characters:REP.b = acopies the reference, not the list, sob.append(4)changes the one shared list.a[:]makes a new shallow copy, so appending tocleavesaalone.
The Four OOP Pillars
| Pillar | One-line meaning | Typical language feature |
|---|---|---|
| Encapsulation | Bundle data with the methods that use it, and hide internal state | private fields with getters/setters |
| Inheritance | A class reuses and extends another class | extends (Java), : public Base (C++), class B(A) (Python) |
| Polymorphism | One interface, many behaviours | Overriding with dynamic dispatch; overloading |
| Abstraction | Expose what an object does, not how | Abstract classes, interfaces, pure virtual functions |
A few details that appear in MCQs:
- Java supports single inheritance of classes but lets a class implement many interfaces. C++ and Python allow multiple inheritance of classes.
- In C++, a class with at least one pure virtual function (
virtual void draw() = 0;) is abstract and cannot be instantiated. - In Java, interface fields are implicitly
public static final. Since Java 8, interfaces can havedefaultandstaticmethods. - Python has no
privatekeyword. A leading double underscore triggers name mangling, which the Python classes tutorial describes. For Java, the Oracle OOP concepts tutorial is a short refresher.
Overloading vs Overriding
| Overloading | Overriding | |
|---|---|---|
| Where | Same class (or inherited into it) | Subclass redefines a superclass method |
| Signature | Same name, different parameter list | Same name and parameter list |
| Resolved | At compile time (static binding) | At run time (dynamic binding) |
| Return type alone differs? | Not allowed as an overload | Java allows a covariant return type |
| Kind of polymorphism | Compile-time | Run-time |
MCQ 7 (Java): which overload runs?
static void f(int x) { System.out.print("int "); }
static void f(long x) { System.out.print("long "); }
static void f(String x) { System.out.print("String "); }
f(5);
f(5L);
f('A');
Answer: int long int
5 is an int literal and matches exactly. 5L is a long. 'A' is a char, which has no exact match, so Java applies widening. char can widen to both int and long, and the compiler picks the most specific one, int. A char never converts to String automatically.
Static vs Dynamic Binding
Static binding means the method is chosen at compile time from the declared type. Dynamic binding means it is chosen at run time from the actual object.
In Java, instance methods are dynamically bound unless they are static, private or final. Fields are never polymorphic. In C++, only virtual functions called through a pointer or reference are dynamically bound.
MCQ 8 (C++): virtual vs non-virtual
class Base {
public:
void show() { cout << "Base::show "; }
virtual void print() { cout << "Base::print "; }
};
class Derived : public Base {
public:
void show() { cout << "Derived::show "; }
void print() override { cout << "Derived::print "; }
};
int main() {
Derived d;
Base& r = d;
r.show();
r.print();
}
Answer: Base::show Derived::print
show() is not virtual, so the call is bound to the declared type, Base. print() is virtual and called through a reference, so the actual object's version, Derived::print, runs.
MCQ 9 (Java): fields and static methods are not overridden
class A {
int v = 1;
int get() { return v; }
static String info() { return "A"; }
}
class B extends A {
int v = 2;
int get() { return v; }
static String info() { return "B"; }
}
A o = new B();
System.out.println(o.v + " " + o.get() + " " + o.info());
Answer: 1 2 A
o.vis a field access, resolved by the declared typeA:1.o.get()is an overridden instance method, soB.get()runs and returnsB'sv:2.info()is static, soB.info()hides rather than overrides it. The call is bound to the declared type:A.
Exceptions
- Java: checked exceptions (such as
IOException) must be caught or declared withthrows. Unchecked exceptions extendRuntimeException(such asNullPointerExceptionandArithmeticException). Catch a subclass before its superclass; the reverse order does not compile. - Integer
10 / 0throwsArithmeticExceptionin Java, but10.0 / 0givesInfinity. - C++: you can throw any type. Catch by reference (
catch (const std::exception& e)) to avoid slicing. - Python:
try / except / else / finally. Theelseblock runs only if no exception was raised.
MCQ 10 (Java): finally runs before the return completes
static int test() {
try {
return 1;
} finally {
System.out.print("finally ");
}
}
System.out.println(test());
Answer: finally 1
The value 1 is computed for return, then the finally block runs and prints, then the method returns and println prints 1. Practise more on the Exception & Error Handling topic.
Memory: Stack, Heap and References
| Stack | Heap | |
|---|---|---|
| Holds | Function call frames: locals, parameters, return addresses | Dynamically allocated objects |
| Lifetime | Ends when the function returns | Until freed (delete) or garbage-collected |
| Management | Automatic | Manual in C/C++; garbage collector in Java and Python |
| Typical errors | Stack overflow from deep recursion | Memory leaks, dangling pointers, double delete |
In Java, objects live on the heap and variables hold references to them. Java is always pass-by-value, but for objects the value passed is a copy of the reference. CPython frees most objects through reference counting plus a cycle detector.
MCQ 11 (Java): copying a reference
static void change(int[] arr, int n) {
arr[0] = 99;
n = 99;
arr = new int[] {7};
}
int[] a = {1, 2};
int n = 1;
change(a, n);
System.out.println(a[0] + " " + n);
Answer: 99 1
arrreceives a copy of the reference to the same array, soarr[0] = 99changes the caller's array.nis a copy of a primitive, so changing it has no effect outside.arr = new int[] {7}only reassigns the local copy of the reference. The caller'sastill points to the original array.
Revise these ideas on the Memory Management Concepts and OOP topics.
How to Revise This Area
- Do one topic set per section on the Programming subject page, and redo every missed question the next day.
- Write every trace on paper, even when it feels easy. Many code-trace mistakes come from skipped steps rather than missing knowledge.
- Keep a short "traps" list: integer division,
chararithmetic, fall-through, short-circuiting,==on strings, static method hiding,finallywithreturn. - Mix in Debugging & Error Analysis questions from Problem Solving, since they use the same tracing skill.
The question bank has 33,808+ MCQs with explanations across all ten subjects, so you can keep drilling these rules until tracing becomes routine.