HomeSubjectsUniversityBlogAbout

NSCT Programming and OOP Revision with Code-Trace MCQs

By Published

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

  1. a / b is evaluated first, and both operands are int, so the result is integer 3.
  2. Only then is 3 converted to double, giving 3.0. cout prints a whole-valued double as 3.
  3. % and * have the same precedence and associate left to right: a % b is 1, then 1 * 3 is 3, then + 1 gives 4.

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 = 5 assigns b first.
  • In Python, ** is right-associative: 2 ** 3 ** 2 is 2 ** 9, which is 512, not 64.

MCQ 2 (Java): string concatenation order

System.out.println(1 + 2 + "3" + 4 + 5);
System.out.println('A' + 1);

Answer: 3345, then 66

  1. + associates left to right. 1 + 2 is integer addition, giving 3.
  2. 3 + "3" involves a String, so it becomes concatenation: "33".
  3. From here every + is concatenation: "334", then "3345".
  4. In the second line, 'A' is a char with value 65. char + int is numeric addition, so the result is the int 66. To print B, 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

  1. Java evaluates operands left to right. x++ yields 5, then x becomes 6.
  2. ++x makes x equal to 7 and yields 7. So y = 5 + 7 = 12.
  3. a > 0 is false, so && short-circuits and ++a never runs. a stays 0.

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 length field, String has a length() method, and ArrayList has size().
  • Java array elements get default values: 0 for numbers, false for boolean, null for references.
  • In C and C++, char s[] = "abc"; occupies 4 bytes, because of the terminating '\0'.
  • In Java, == on objects compares references; use equals() to compare string contents.
  • Python slicing never raises an IndexError for 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

  1. 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.
  2. s[::-1] reverses the string; its first character is the original last one, P.
  3. s[-3:] is the last three characters: REP.
  4. b = a copies the reference, not the list, so b.append(4) changes the one shared list. a[:] makes a new shallow copy, so appending to c leaves a alone.

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 have default and static methods.
  • Python has no private keyword. 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

  1. o.v is a field access, resolved by the declared type A: 1.
  2. o.get() is an overridden instance method, so B.get() runs and returns B's v: 2.
  3. info() is static, so B.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 with throws. Unchecked exceptions extend RuntimeException (such as NullPointerException and ArithmeticException). Catch a subclass before its superclass; the reverse order does not compile.
  • Integer 10 / 0 throws ArithmeticException in Java, but 10.0 / 0 gives Infinity.
  • C++: you can throw any type. Catch by reference (catch (const std::exception& e)) to avoid slicing.
  • Python: try / except / else / finally. The else block 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

  1. arr receives a copy of the reference to the same array, so arr[0] = 99 changes the caller's array.
  2. n is a copy of a primitive, so changing it has no effect outside.
  3. arr = new int[] {7} only reassigns the local copy of the reference. The caller's a still points to the original array.

Revise these ideas on the Memory Management Concepts and OOP topics.

How to Revise This Area

  1. Do one topic set per section on the Programming subject page, and redo every missed question the next day.
  2. Write every trace on paper, even when it feels easy. Many code-trace mistakes come from skipped steps rather than missing knowledge.
  3. Keep a short "traps" list: integer division, char arithmetic, fall-through, short-circuiting, == on strings, static method hiding, finally with return.
  4. 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.