CSS Prepare

optional · CSS study notes

1. Programming Fundamentals (C/C++)

FPSC CSS Computer Science past papers (2016–2026) — 50 questions: 7 MCQs, 43 subjective parts. Newest first.


Part A — Subjective Questions

2026 · Paper-I · Q3(a) (6 marks)

Question

What is bit manipulation in programming, and why is it used? Give two examples of its use.

Solution

Bit manipulation is the technique of directly operating on the individual binary bits of a data value using bitwise operators (AND &, OR |, XOR ^, NOT ~, left shift <<, right shift >>), instead of working with the value as a whole number.

It is used because it is extremely fast (bitwise operations map directly to single CPU instructions), memory-efficient (bit flags can pack many boolean states into a single integer instead of many separate variables), and is essential for low-level tasks such as hardware/register control, cryptography, graphics, and compact data encoding.

Two examples:

  1. Fast multiplication/division by powers of two: x << 1 doubles x (multiply by 2), and x >> 1 halves x (integer divide by 2) — much faster than using the *// operators on some hardware.
  2. Checking even/odd or toggling flags: x & 1 checks if x is odd (1) or even (0) by inspecting only the least-significant bit; similarly, flags |= MASK sets a specific flag bit on, flags &= ~MASK clears it, and flags ^= MASK toggles it — commonly used to store multiple boolean settings compactly in one integer, such as file-permission flags.

2026 · Paper-I · Q3(c) (8 marks)

Question

Write pseudocode to reverse an array using pointers.

Solution

Pseudocode using two pointers moving towards each other from both ends, swapping as they go:

Function ReverseArray(arr, n):
    left  <- pointer to arr[0]           // pointer to first element
    right <- pointer to arr[n-1]         // pointer to last element

    while left < right:                  // pointers have not crossed
        temp     <- *left
        *left    <- *right
        *right   <- temp

        left  <- left + 1                // move left pointer forward
        right <- right - 1               // move right pointer backward

    return arr

Equivalent C++ code:

void reverseArray(int* arr, int n) {
    int* left = arr;
    int* right = arr + n - 1;
    while (left < right) {
        int temp = *left;
        *left = *right;
        *right = temp;
        left++;
        right--;
    }
}

This runs in O(n) time using only O(1) extra space, since it reverses the array in place by repeatedly swapping the elements pointed to by two pointers that converge from opposite ends until they meet or cross.


2025 · Paper-I · Q3(b) (6 marks)

Question

State the difference between const keyword and static keyword in C++. Illustrate each keyword with suitable examples.

Solution

const declares that a variable, object, pointer, or member function will not modify its value/state after initialization — the compiler enforces read-only access. static gives a variable a single, persistent storage location that lasts for the program's lifetime (instead of being recreated each call), or restricts a global/function's linkage to the file that declares it; for a class member, static makes the member shared by all objects of the class rather than each object having its own copy.

Examples:

const int MAX = 100;              // cannot be reassigned
void show(const int &x);          // function promises not to modify x
class Circle {
 public:
    double getRadius() const;     // const member function: cannot modify object
};

void counter() {
    static int calls = 0;         // retains value across calls
    calls++;
    cout << calls;
}

class Employee {
 public:
    static int count;             // one copy shared by ALL Employee objects
};
int Employee::count = 0;

In short: const is about immutability of a value/behaviour, while static is about storage duration/scope/sharing — they solve different problems and can even be combined, e.g., static const int LIMIT = 10;.


2025 · Paper-I · Q4(a) (6 marks)

Question

Write a C++ program to output the arithmetic series of n terms. The series formula for calculating the sum of n terms is as follows: Sn = n/2 [2a + (n-1) d] , with values a = 5, d= 3 and n= 6, where a = first term, d= common difference and n = number of terms.

Solution

#include <iostream>
using namespace std;

int main() {
    int a = 5, d = 3, n = 6;
    int Sn = (n * (2 * a + (n - 1) * d)) / 2;

    cout << "Arithmetic series terms: ";
    int term = a;
    for (int i = 0; i < n; i++) {
        cout << term;
        if (i != n - 1) cout << ", ";
        term += d;
    }
    cout << endl;
    cout << "Sum of " << n << " terms (Sn) = " << Sn << endl;
    return 0;
}

Working: terms are 5, 8, 11, 14, 17, 20. Sn = 6/2 [2(5) + 5(3)] = 3[10+15] = 3(25) = 75. Sample output: Arithmetic series terms: 5, 8, 11, 14, 17, 20 and Sum of 6 terms (Sn) = 75.


2025 · Paper-I · Q4(b) (6 marks)

Question

Write a C++ program to calculate and display the product of two matrices of order 2 x 2. The program should prompt the user to provide values of both matrices

Solution

#include <iostream>
using namespace std;

int main() {
    int A[2][2], B[2][2], C[2][2] = {0};

    cout << "Enter elements of matrix A (2x2):\n";
    for (int i = 0; i < 2; i++)
        for (int j = 0; j < 2; j++)
            cin >> A[i][j];

    cout << "Enter elements of matrix B (2x2):\n";
    for (int i = 0; i < 2; i++)
        for (int j = 0; j < 2; j++)
            cin >> B[i][j];

    for (int i = 0; i < 2; i++)
        for (int j = 0; j < 2; j++)
            for (int k = 0; k < 2; k++)
                C[i][j] += A[i][k] * B[k][j];

    cout << "Product matrix (A x B):\n";
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++)
            cout << C[i][j] << " ";
        cout << endl;
    }
    return 0;
}

For example, if A = [[1,2],[3,4]] and B = [[5,6],[7,8]], the product is [[19,22],[43,50]].


2025 · Paper-I · Q4(c) (8 marks)

Question

Write a C++ program to demonstrate the two different complex numbers using structure. The program should use function to calculate the sum of complex numbers and display their result in the specific format such as (a + bi), where a and b are the real and imaginary part respectively and i is imaginary unit such as i = sqrt(-1).

Solution

#include <iostream>
using namespace std;

struct Complex {
    double real;
    double imag;
};

Complex addComplex(Complex c1, Complex c2) {
    Complex result;
    result.real = c1.real + c2.real;
    result.imag = c1.imag + c2.imag;
    return result;
}

void display(Complex c) {
    if (c.imag >= 0)
        cout << "(" << c.real << " + " << c.imag << "i)" << endl;
    else
        cout << "(" << c.real << " - " << -c.imag << "i)" << endl;
}

int main() {
    Complex c1 = {3.0, 4.0};
    Complex c2 = {1.0, -2.0};

    Complex sum = addComplex(c1, c2);

    cout << "First complex number: "; display(c1);
    cout << "Second complex number: "; display(c2);
    cout << "Sum: "; display(sum);
    return 0;
}

With c1 = 3+4i and c2 = 1-2i, the sum is (4 + 2i), printed via the display() function in the required (a + bi) format.


2024 · Paper-I · Q3(a) (6 marks)

Question

Write a program that prompts the user to enter a letter grade A, B, C, D, or F and displays its corresponding numeric value 4, 3, 2, 1, or 0.

Solution

#include <iostream>
using namespace std;

int main() {
    char grade;
    cout << "Enter a letter grade (A, B, C, D, F): ";
    cin >> grade;

    int numericValue;
    switch (grade) {
        case 'A': case 'a': numericValue = 4; break;
        case 'B': case 'b': numericValue = 3; break;
        case 'C': case 'c': numericValue = 2; break;
        case 'D': case 'd': numericValue = 1; break;
        case 'F': case 'f': numericValue = 0; break;
        default:
            cout << "Invalid grade entered." << endl;
            return 1;
    }
    cout << "Numeric value: " << numericValue << endl;
    return 0;
}

For input 'B', the program outputs "Numeric value: 3".


2024 · Paper-I · Q3(b) (6 marks)

Question

Write pseudocode OR C-language script for the following expression: a . b = sum_{i=1}^{n} a_i b_i = a_1 b_1 + a_2 b_2 + ... + a_n b_n

Solution

#include <stdio.h>

int main() {
    int n;
    printf("Enter number of elements (n): ");
    scanf("%d", &n);

    double a[100], b[100], dot = 0.0;
    for (int i = 0; i < n; i++) {
        printf("Enter a[%d] and b[%d]: ", i+1, i+1);
        scanf("%lf %lf", &a[i], &b[i]);
    }

    for (int i = 0; i < n; i++)
        dot += a[i] * b[i];   // accumulate a_i * b_i

    printf("Dot product = %.2f\n", dot);
    return 0;
}

This program reads two n-dimensional vectors a and b, then computes their dot product by summing the pairwise products a_i * b_i for i = 1 to n, exactly matching the given mathematical expression.


2024 · Paper-I · Q4(a) (6 marks)

Question

Write a program that displays the area and perimeter of a rectangle with the width of 4.5 and height of 7.9 using the following formula: area = width * height.

Solution

#include <iostream>
using namespace std;

int main() {
    double width = 4.5, height = 7.9;
    double area = width * height;
    double perimeter = 2 * (width + height);

    cout << "Area = " << area << endl;
    cout << "Perimeter = " << perimeter << endl;
    return 0;
}

Calculation: area = 4.5 x 7.9 = 35.55; perimeter = 2 x (4.5 + 7.9) = 2 x 12.4 = 24.8. Output:

Area = 35.55
Perimeter = 24.8

2024 · Paper-I · Q4(b) (6 marks)

Question

Write a program that reads a Celsius degree from the console, then converts it to Fahrenheit and displays the result. The formula for the conversion is as follows: Fahrenheit = (9 / 5) * Celsius + 32.

Solution

#include <iostream>
using namespace std;

int main() {
    double celsius;
    cout << "Enter a Celsius temperature: ";
    cin >> celsius;

    double fahrenheit = (9.0 / 5.0) * celsius + 32;
    cout << "Fahrenheit = " << fahrenheit << endl;
    return 0;
}

Note the use of 9.0/5.0 (floating-point division) instead of 9/5 (which would truncate to integer 1 in C++, giving a wrong result). For example, entering 100 gives Fahrenheit = 212.


2024 · Paper-I · Q4(c) (8 marks)

Question

Write a program that prompts the user to enter the month and year and displays the number of days in the month. For example, if the user entered month 2 and year 2024, the program should display that February 2024 had 29 days. If the user entered month 3 and year 2015, the program should display that March 2015 had 31 days.

Solution

#include <iostream>
using namespace std;

bool isLeapYear(int year) {
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

int main() {
    int month, year;
    cout << "Enter month and year: ";
    cin >> month >> year;

    int days;
    switch (month) {
        case 1: case 3: case 5: case 7: case 8: case 10: case 12:
            days = 31; break;
        case 4: case 6: case 9: case 11:
            days = 30; break;
        case 2:
            days = isLeapYear(year) ? 29 : 28; break;
        default:
            cout << "Invalid month." << endl;
            return 1;
    }
    cout << "Month " << month << " " << year << " has " << days << " days." << endl;
    return 0;
}

Verification against the examples: month=2, year=2024 -> 2024 is divisible by 4 and not by 100, so it is a leap year -> 29 days (matches). month=3, year=2015 -> March always has 31 days (matches).


2023 · Paper-I · Q3(a) (8 marks)

Question

How does dynamic memory allocation is managed programmatically in a C++ program? Clarify yours understanding through a viable program.

Solution

In C++, dynamic memory is allocated from the heap (free store) at run time using the new operator, and released using delete (for a single object) or delete[] (for an array), rather than being fixed at compile time like automatic (stack) variables. new returns a pointer to the allocated memory; the programmer is responsible for freeing it, otherwise a memory leak occurs, since the memory is not automatically reclaimed until the program ends.

#include <iostream>
using namespace std;

int main() {
    int n;
    cout << "Enter size: ";
    cin >> n;

    int* arr = new int[n];        // dynamically allocate an array of n ints
    for (int i = 0; i < n; i++)
        arr[i] = i * i;

    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    cout << endl;

    delete[] arr;                 // free the array (must match new[] with delete[])
    arr = nullptr;

    int* p = new int(42);         // dynamically allocate a single int, initialized to 42
    cout << *p << endl;
    delete p;                     // free single object (matches plain new with delete)

    return 0;
}

The size n is decided at run time (unlike a fixed-size array), demonstrating that dynamic allocation lets a program's memory usage adapt to data determined only while the program is executing.


2023 · Paper-I · Q3(c) (6 marks)

Question

What is bit twiddling? Give brief description.

Solution

Bit twiddling (bit manipulation) refers to directly manipulating the individual bits of a data value using bitwise operators - AND (&), OR (|), XOR (^), complement (~), and shift (<<, >>) - instead of using higher-level arithmetic, typically for efficiency, compactness, or low-level hardware/embedded programming.

Common bit-twiddling tricks include: checking if a number is odd/even with n & 1; testing/setting/clearing a specific bit k with n & (1<<k), n | (1<<k), n & ~(1<<k); swapping two variables without a temporary using XOR (a^=b; b^=a; a^=b;); multiplying/dividing by powers of two using shifts (n<<1 doubles, n>>1 halves); and using bitmasks to pack multiple flags into a single integer. Because these operations map directly to single machine instructions, bit twiddling is widely used in performance-critical code, cryptography, graphics, and embedded systems where speed and memory are constrained.


2022 · Paper-I · Q2(a) (8 marks)

Question

Using C++ write a function pattern (int n) that produces the following output. Pay special attention to the spaces and clearly state the return type of the function. Note that the following is just an example; your solution should work for any input "n" (example shown for n=7): 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6 1 2 3 4 5 6 7

Solution

The function should return void because it only prints output and does not need to return any value to the caller. Row i (1 <= i <= n) prints the numbers 1..i, right-shifted so that all rows align to a common right edge; this is achieved by printing (n-i) blocks of two spaces (matching the width of "digit + space") before printing the numbers of that row.

#include <iostream>
using namespace std;

void pattern(int n) {
    for (int i = 1; i <= n; i++) {
        // leading spaces to right-align the staircase
        for (int s = 1; s <= (n - i); s++)
            cout << "  "; // 2 spaces per missing column
        // print numbers 1..i separated by a single space
        for (int j = 1; j <= i; j++) {
            cout << j;
            if (j != i) cout << " ";
        }
        cout << endl;
    }
}

int main() {
    int n;
    cout << "Enter n: ";
    cin >> n;
    pattern(n);
    return 0;
}

Sample output for n=7 matches the staircase shown in the question, with each row shifted two spaces less than the previous one.


2022 · Paper-I · Q2(c) (6 marks)

Question

Write output of the following C++ code assuming that there is no error in the code: int ary[4] = {1,2,3,4}; int *p1 = ary + 3; cout << p1[-2] << endl; int *p2 = &p1[-2]; *p2 = 10; cout << ary[1] << endl;

Solution

p1 = ary + 3 points to ary[3] (value 4). p1[-2] is *(p1-2), i.e. two elements before ary[3], which is ary[1] = 2, so the first output is 2. p2 = &p1[-2] takes the address of that same element, i.e. p2 = &ary[1]. Then *p2 = 10 sets ary[1] to 10. The second cout prints ary[1], which is now 10.

Output:

2
10

2022 · Paper-I · Q3(c) (6 marks)

Question

Write output of the following C++ code assuming that there is no error in the code: int v1 = 55; int* p1 = &v1; int* p2; p2 = p1; *p1 = 20; cout << *p2 << endl; cout << v1 << endl;

Solution

p1 stores the address of v1. p2 = p1 makes p2 point to the same memory location as p1, i.e. v1. *p1 = 20 changes the value stored at that address, so v1 becomes 20. Since p2 points to the same location, *p2 also reads 20. Then v1 itself is printed, also 20.

Output:

20
20

2022 · Paper-I · Q4(a) (12 marks)

Question

Write a C++ program to check whether a string is palindrome or not. A palindrome is a string, which when read in both forward and backward ways is the same, e.g., "radar", "madam" etc. Note that these are only examples, you will take the string as an input from a user using the cin.getline function and your code should be general that can work on any input string. You are not allowed to use any string-related library function.

Solution

#include <iostream>
using namespace std;

bool isPalindrome(char str[], int length) {
    int start = 0, end = length - 1;
    while (start < end) {
        if (str[start] != str[end])
            return false;
        start++;
        end--;
    }
    return true;
}

int main() {
    char str[1000];
    cout << "Enter a string: ";
    cin.getline(str, 1000);

    // compute length manually (no library function allowed)
    int length = 0;
    while (str[length] != '\0')
        length++;

    if (isPalindrome(str, length))
        cout << str << " is a palindrome." << endl;
    else
        cout << str << " is not a palindrome." << endl;

    return 0;
}

For input "radar", the two-pointer comparison from both ends matches at every step, so the program prints "radar is a palindrome."


2022 · Paper-I · Q4(b) (8 marks)

Question

Write output of the following C++ code assuming that there is no error in the code: #include <iostream.h> int main() { int a = 12, b = 25; cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "a | b = " << (a | b) << endl; return 0; }

Solution

12 in binary is 01100 and 25 is 11001. Bitwise OR combines the bits: 01100 | 11001 = 11101, which is 29 in decimal.

Output:

a = 12
b = 25
a | b = 29

2022 · Paper-I · Q6(a) (8 marks)

Question

Complete the following recursive function using C++ to calculate k raised to the power n, i.e., k^n. Use of any built-in (library) function is not allowed. int power(int k, int n) { // write your code here }

Solution

The base case is n == 0, where any k^0 = 1. The recursive case multiplies k by the result of k raised to the power (n-1).

int power(int k, int n)
{
    if (n == 0)
        return 1;
    return k * power(k, n - 1);
}

For example, power(2, 5) computes 2 * power(2,4) = 2 * (2 * power(2,3)) = ... = 32, unwinding recursion 5 levels deep down to the base case power(2,0) = 1.


2021 · Paper-I · Q3(b) (5 marks)

Question

Write a program that should output the factors of the number passed as input – one factor on each line. Factors of a number, say x, are those whole numbers which can be multiplied with other whole numbers to get x.

Solution

#include <iostream>
using namespace std;

int main() {
    int x;
    cout << "Enter a number: ";
    cin >> x;
    cout << "Factors of " << x << ":" << endl;
    for (int i = 1; i <= x; i++) {
        if (x % i == 0)
            cout << i << endl;
    }
    return 0;
}

Sample run: x = 12 -> output: 1, 2, 3, 4, 6, 12 (each on its own line).


2021 · Paper-I · Q3(d) (4 marks)

Question

Write a program in C/C++ to convert a decimal number to hexadecimal.

Solution

#include <iostream>
#include <string>
using namespace std;

int main() {
    int n;
    cout << "Enter a decimal number: ";
    cin >> n;
    if (n == 0) { cout << "Hexadecimal: 0" << endl; return 0; }

    string hexDigits = "0123456789ABCDEF";
    string result = "";
    int num = n;
    while (num > 0) {
        int remainder = num % 16;
        result = hexDigits[remainder] + result;
        num /= 16;
    }
    cout << "Hexadecimal: " << result << endl;
    return 0;
}

Sample run: 255 -> Hexadecimal: FF.


2021 · Paper-I · Q4(c) (6 marks)

Question

What do you mean by runtime and compile time errors?

Solution

Compile-time errors are detected by the compiler while translating source code into an executable, BEFORE the program ever runs. They include syntax errors (e.g. a missing semicolon or unmatched brace), type mismatches, and references to undeclared variables/functions. The compiler reports the exact line and typically the nature of the mistake, and no executable is produced until they are fixed. Runtime errors occur DURING program execution, after the program has compiled successfully — for example, division by zero, dereferencing a null/invalid pointer, accessing an array index out of bounds, or trying to open a file that does not exist. The program compiles and starts running normally but crashes or misbehaves once the offending code path actually executes with specific input/state. In general, compile-time errors are easier to find and fix (the compiler points directly at them), while runtime errors require careful testing and debugging with the right input conditions to even surface, since the source code itself is syntactically and semantically valid.


2021 · Paper-I · Q5(b) (6 marks)

Question

What is pass by value and pass by reference? Can we pass an object as a parameter to call a method in java?

Solution

Pass by value: a copy of the argument's value is passed into the function/method's parameter; changes made to the parameter inside the function do not affect the original variable in the caller. Pass by reference: the parameter becomes an alias for the original variable itself (no copy), so changes made inside the function DO affect the caller's original variable. Yes, we can pass an object as a parameter to call a method in Java, but it is important to understand the exact semantics: Java has no true pass-by-reference — ALL arguments in Java, including object references, are passed BY VALUE. For an object argument, what is copied is the object's REFERENCE (the value of the reference/pointer), not the object itself. This means the method cannot make the caller's variable point to a completely different object, but since the copied reference still points to the SAME underlying object, the method CAN mutate that object's internal fields via its methods, and those changes will be visible to the caller after the method returns — effectively letting you pass an object and have its state modified.


2020 · Paper-I · Q2(b) (7 marks)

Question

Write a C/C++ program which inputs a number from a user and prints Fibonacci series up to the number.

Solution

#include <iostream>
using namespace std;

int main() {
    int n;
    cout << "Enter a number: ";
    cin >> n;
    int a = 0, b = 1;
    cout << "Fibonacci series up to " << n << ": ";
    while (a <= n) {
        cout << a << " ";
        int next = a + b;
        a = b;
        b = next;
    }
    cout << endl;
    return 0;
}

Sample run: n = 20 -> 0 1 1 2 3 5 8 13.


2020 · Paper-I · Q4(c) (4 marks)

Question

Write a program to convert numbers into words. For instance, if the user types 123, the program should give output one hundred and twenty three. The program should continue functioning until the user types quit.

Solution

#include <iostream>
#include <string>
using namespace std;

string ones[] = {"zero","one","two","three","four","five","six","seven","eight",
                 "nine","ten","eleven","twelve","thirteen","fourteen","fifteen",
                 "sixteen","seventeen","eighteen","nineteen"};
string tens[] = {"","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"};

string convertTwoDigit(int n) {
    if (n < 20) return ones[n];
    return tens[n/10] + (n%10 ? " " + ones[n%10] : "");
}

string convertToWords(int n) {
    if (n == 0) return "zero";
    string result = "";
    if (n >= 1000) { result += ones[n/1000] + " thousand "; n %= 1000; }
    if (n >= 100) {
        result += ones[n/100] + " hundred ";
        n %= 100;
        if (n > 0) result += "and ";
    }
    if (n > 0) result += convertTwoDigit(n);
    return result;
}

int main() {
    string input;
    while (true) {
        cout << "Enter a number (or 'quit' to exit): ";
        cin >> input;
        if (input == "quit") break;
        int num = stoi(input);
        cout << convertToWords(num) << endl;
    }
    return 0;
}

Sample run: input 123 -> output one hundred and twenty three; input quit -> program exits.


2020 · Paper-I · Q7(a) (5 marks)

Question

How many tokens are there in in this C code : printf("k = %d, &k = %x", k, &k);

Solution

A token is the smallest individually meaningful unit the compiler's lexer identifies (keywords, identifiers, literals, operators, punctuators). Tokenising the statement: printf ( "k = %d, &k = %x" , k , & k ) ; That is: 1.printf (identifier), 2.(, 3.the whole string literal "k = %d, &k = %x" (a single token), 4.,, 5.k, 6.,, 7.& (address-of operator), 8.k, 9.), 10.;. Total = 10 tokens.


2019 · Paper-I · Q3(a) (10 marks)

Question

See the following C++ program to declare whether an input number is a prime number or not. Identify the logical errors in the given program (if any). Give your correct statement(s) exactly at the same line number.

  1. n, i;
  2. bool is Prime = false;
  3. cout<< "Enter a positive integer: ";
  4. cin>> n;
  5. for(i = 1; i< n / 2; ++i)
  6. {
  7. if(n /i == 0)
  8. {
  9. is Prime = false;
  10. break;
  11. }
  12. }
  13. if (is Prime)
  14. cout<< "This is a prime number";
  15. else
  16. cout<< "This is not a prime number";

Solution

There are four logical/compilation errors: Line 1: n, i; has no data type and will not compile. Correct: int n, i; Line 2: isPrime is initialised to false. Since the algorithm's logic assumes the number IS prime unless a divisor is found, it must start true. Correct: bool isPrime = true; Line 5: the loop bound i < n / 2 misses valid divisors — e.g. for n = 4, n/2 = 2, and i < 2 only tests i = 1, so 4 would be wrongly reported prime. It must include n/2 itself. Correct: for(i = 2; i <= n / 2; ++i) (also starting at 2 since every number is divisible by 1, which would otherwise always trigger a false 'not prime'). Line 7: n / i == 0 is integer DIVISION, which is never 0 for 1 <= i <= n, so a divisor is never detected — every number would be reported prime. The divisibility test must use the modulus operator. Correct: if (n % i == 0) Corrected program:

#include <iostream>
using namespace std;

int main() {
    int n, i;                       // line 1 fixed
    bool isPrime = true;            // line 2 fixed
    cout << "Enter a positive integer: ";
    cin >> n;
    for (i = 2; i <= n / 2; ++i) {  // line 5 fixed
        if (n % i == 0) {           // line 7 fixed
            isPrime = false;
            break;
        }
    }
    if (isPrime)
        cout << "This is a prime number";
    else
        cout << "This is not a prime number";
    return 0;
}

(An additional robustness note, not part of the original logic: numbers 0 and 1 should ideally be special-cased as 'not prime' since the loop body never executes for them and isPrime stays true.)


2019 · Paper-I · Q3(b) (5 marks)

Question

What is the difference between call by value and call by reference?

Solution

Call by value: a copy of the actual argument's value is passed into the function's parameter. The function works on this copy, so any change made inside the function has no effect on the original variable in the caller. It is safer (no accidental side effects) but costs extra memory/time for copying, especially for large objects. Call by reference: the function parameter becomes an alias (in C++, declared with &) for the actual argument itself, so no copy is made. Any modification inside the function directly changes the caller's original variable. It is more efficient for large data and is required whenever a function must modify the caller's variable(s) or return more than one value. Example: void f(int x) is call by value; void f(int &x) is call by reference — calling f(a) can change a itself in the second case but never in the first.


2019 · Paper-I · Q3(c) (5 marks)

Question

What is the role of preprocessor directives? Give three examples in C++.

Solution

Preprocessor directives are instructions processed by the preprocessor BEFORE actual compilation begins. They perform textual manipulation of the source file: including other files, defining macros/constants, and conditionally compiling parts of the code. They begin with # and are not C++ statements themselves (no semicolon, not subject to scope rules). Three examples:

  1. #include <iostream> — inserts the contents of a header file into the source file before compilation.
  2. #define PI 3.14159 — defines a macro constant/text substitution, replacing every later occurrence of PI with 3.14159.
  3. #ifndef HEADER_H / #define HEADER_H / #endif — an include guard that conditionally compiles code, preventing a header file from being included (and its contents redefined) more than once.

2019 · Paper-I · Q5(b) (5 marks)

Question

What is bit twiddling? Give brief description.

Solution

Bit twiddling (bit manipulation/bit hacking) is the practice of directly manipulating individual bits of data using bitwise operators (&, |, ^, ~, <<, >>) instead of higher-level arithmetic, typically for efficiency in low-level/performance-critical or embedded code. Common tricks include: checking if a number is even/odd with n & 1, testing power-of-two with n & (n-1) == 0, clearing the lowest set bit with n & (n-1), swapping two variables without a temporary via XOR (a^=b; b^=a; a^=b;), setting/clearing/toggling a specific bit with masks, and packing multiple flags into a single integer. It is widely used in systems programming, graphics, cryptography and hardware driver code where speed and memory footprint matter more than readability.


2018 · Paper-I · Q3(a) (5 marks)

Question

Write a program grade average calculator, User will input marks for five subjects and program will output the average of its marks. Print appropriate message on the base of its mark's average e.g.; Well done, Keep it up, Better luck next time etc.

Solution

#include <iostream>
using namespace std;

int main() {
    float marks[5], sum = 0, average;

    for (int i = 0; i < 5; i++) {
        cout << "Enter marks for subject " << (i+1) << ": ";
        cin >> marks[i];
        sum += marks[i];
    }

    average = sum / 5;
    cout << "Average marks: " << average << endl;

    if (average >= 80)
        cout << "Well done!" << endl;
    else if (average >= 60)
        cout << "Keep it up!" << endl;
    else if (average >= 40)
        cout << "Needs improvement." << endl;
    else
        cout << "Better luck next time." << endl;

    return 0;
}

The program takes 5 marks, computes the average, and prints a motivational message based on configurable grade thresholds.


2018 · Paper-I · Q3(b) (2 marks)

Question

Given that i,j,k,n & m are integer variables. Write a condition such that: i- hello is only printed when, any of the following conditions are met: i is twice the value of j, j is smaller than k and less than n, or m is negative. int i,j,k,n,m; cin>>i>>j>>k>>n>>m; if( ) cout<<"hello"; ii. hello is only printed when i does not lies in the interval 6-9 int i; cin>>i; if( ) cout<<"hello";

Solution

i. if ( i == 2*j || (j < k && j < n) || m < 0 ) cout<<"hello";

ii. if ( i < 6 || i > 9 ) cout<<"hello"; (equivalently: if ( !(i >= 6 && i <= 9) ))


2018 · Paper-I · Q3(c) (1 marks)

Question

Write equivalent instruction to following instruction without the use of += operator: where w,z are integers. w+=2*z+4;

Solution

w = w + 2*z + 4; (equivalently written as w = w + (2*z + 4);)


2018 · Paper-I · Q3(d) (2 marks)

Question

Predict the values of variables a & b after every instruction: integer a=5 b=6; a=(b++) + 3; b=--a;

Solution

Initial: a=5, b=6.

Line 1: a = (b++) + 3; - post-increment: the expression uses b's CURRENT value (6) first, then b is incremented afterward. -> a = 6 + 3 = 9; then b becomes 7. After line 1: a=9, b=7.

Line 2: b = --a; - pre-decrement: a is decremented FIRST, then the new value is used/assigned. -> a becomes 9-1 = 8; then b = 8. After line 2: a=8, b=8.

Final values: a = 8, b = 8.


2018 · Paper-I · Q3(e) (5 marks)

Question

Complete the code such that it prompts the user for +ve number n. Then displays the output.(whatever the value of n is)(HINT: instead of triangles of stars its triangles of increasing numbers) for n=4 it will print 1 2 3 4 1 2 3 1 2 1 void main() { int n; cin>>n; // your loops will go here }

Solution

void main()
{
    int n; cin >> n;
    for (int i = n; i >= 1; i--) {
        for (int j = 1; j <= i; j++) {
            cout << j;
            if (j != i) cout << " ";
        }
        cout << endl;
    }
}

For n=4, the outer loop runs i=4,3,2,1 (decreasing row length), and the inner loop prints 1..i on each row, producing exactly: 1 2 3 4 1 2 3 1 2 1


2018 · Paper-I · Q3(f) (5 marks)

Question

In following code replace the character at pos-th location in the string st with the character ch. For example in string helloworld replacing 2nd character with i would result in hilloworld: void main( ) {char st[15]; int pos; char ch; int size=0; cin>>st; cin>>pos>>ch; while(st[size]!='\0') { size++; // calculating length of current string } // write your code here }

Solution

void main()
{
    char st[15]; int pos; char ch;
    int size = 0;
    cin >> st;
    cin >> pos >> ch;
    while (st[size] != '\0')
    {
        size++; // calculating length of current string
    }
    // write your code here
    if (pos >= 1 && pos <= size)
        st[pos - 1] = ch;   // pos is treated as 1-based, as in the example
    cout << st;
}

Check against the example: string "helloworld", pos=2 (the '2nd character', i.e. index1='e' using 1-based counting), ch='i' -> st[1]='i' gives "hilloworld", exactly matching the example given in the question.


2018 · Paper-I · Q5(a) (3 marks)

Question

What is dangling pointer?

Solution

A dangling pointer is a pointer that still holds the memory address of an object/variable that has already been deleted, freed, or gone out of scope, so the memory it points to is no longer valid for that pointer's use. Dereferencing a dangling pointer causes undefined behavior (crashes, data corruption, or silently reading/writing garbage/reused memory).

Common causes: calling delete/free() on a pointer without setting it to nullptr afterward, or returning the address of a local (stack) variable from a function after the function returns (the stack frame is destroyed but the pointer still points to that now-invalid location). Good practice: set pointers to nullptr immediately after freeing them, and avoid returning addresses of local variables.


2017 · Paper-I · Q3(b) (6 marks)

Question

Write a function that calculates the quadratic equation in x = (-b +- sqrt(b^2-4ac)) / 2a. You may use the math library for this purpose. The program should ask the user to enter values of a, b and c and should print the result. A sample execution of the program is shown below: Enter value of a: 1 Enter value of b: 2 Enter value of c: 1 The values of x are -1, -1

Solution

#include <iostream>
#include <cmath>
using namespace std;

void solveQuadratic(float a, float b, float c) {
    float discriminant = b*b - 4*a*c;
    if (discriminant < 0) {
        cout << "Roots are complex (no real solution)." << endl;
        return;
    }
    float x1 = (-b + sqrt(discriminant)) / (2*a);
    float x2 = (-b - sqrt(discriminant)) / (2*a);
    cout << "The values of x are " << x1 << ", " << x2 << endl;
}

int main() {
    float a, b, c;
    cout << "Enter value of a: "; cin >> a;
    cout << "Enter value of b: "; cin >> b;
    cout << "Enter value of c: "; cin >> c;
    solveQuadratic(a, b, c);
    return 0;
}

Check: a=1,b=2,c=1 -> discriminant = 4-4 = 0 -> x1=x2 = -2/2 = -1, matching the sample output 'The values of x are -1, -1'.


2017 · Paper-I · Q3(c) (6 marks)

Question

Consider that you are required to create a program for a supermarket checkout machine. The machine has a database of the items available in the supermarket which consists of the items name, code and price. Make a program that requires the cashier (user) to enter the code or name of the product and the quantity that has been bought. It should allow for multiple entries to be made. Once all the entries have been made. The program prints the total amount to be charged on the screen. A sample execution is shown below: Enter product name or code: 1 Enter quantity: 1 Do you have more products to add (Y/N): N The total amount is 500 You may construct the database as a structure.

Solution

#include <iostream>
#include <cstring>
using namespace std;

struct Product {
    int code;
    char name[30];
    float price;
};

int main() {
    Product db[3] = { {1, "Sugar", 500}, {2, "Rice", 300}, {3, "Oil", 800} };
    int inputCode, qty;
    float total = 0;
    char more = 'Y';

    while (more == 'Y' || more == 'y') {
        cout << "Enter product name or code: ";
        cin >> inputCode;
        cout << "Enter quantity: ";
        cin >> qty;

        for (int i = 0; i < 3; i++) {
            if (db[i].code == inputCode) {
                total += db[i].price * qty;
                break;
            }
        }
        cout << "Do you have more products to add (Y/N): ";
        cin >> more;
    }
    cout << "The total amount is " << total << endl;
    return 0;
}

Check: entering code=1 (Sugar, price 500) with quantity 1 gives total = 500, matching the sample.


2017 · Paper-I · Q8(a) (5 marks)

Question

Write short notes on any FOUR of the following (5 each): (a) Global, Local and shared variables for nested function access

Solution

Local variables are declared within a function (or block) and are only accessible within that function/block; they are created on the stack when the function is called and destroyed when it returns - other functions, including nested ones, cannot directly access another function's local variables unless explicitly passed as parameters.

Global variables are declared outside all functions, at file scope; they are accessible by every function in the file (and other files, if declared extern), persisting for the entire program's lifetime - useful for data genuinely shared across many functions, but overuse harms modularity and makes debugging harder since any function can silently modify shared state.

Shared variables (for nested/inner function access, as in languages supporting nested functions/closures) refer to variables from an enclosing function's scope that an inner/nested function can access directly (via lexical scoping/closures), without them being fully global; this is common in languages like Python or JavaScript (closures) - C++ does not support true nested functions, but achieves similar sharing via reference parameters, static/global variables, or lambda captures ([&] or [=]) which let a lambda 'nested' inside a function access the outer function's local variables by reference or by value.


2016 · Paper-I · Q2(a) (6 marks)

Question

Write a program to input choice from user for temperature conversion from Fahrenheit to Celsius or Celsius to Fahrenheit. After the choice, input temperature from user and display the converted answer. Sample execution of the program is given below;

  1. Fahrenheit to Celsius
  2. Celsius to Fahrenheit Enter your choice: 1 Enter Temperature in Fahrenheit: 98 Same Temperature in Celsius: 36.7 Press Any Key to Continue....

Solution

#include <iostream>
using namespace std;

int main() {
    int choice;
    float temp, result;

    cout << "1. Fahrenheit to Celsius" << endl;
    cout << "2. Celsius to Fahrenheit" << endl;
    cout << "Enter your choice: ";
    cin >> choice;

    if (choice == 1) {
        cout << "Enter Temperature in Fahrenheit: ";
        cin >> temp;
        result = (temp - 32) * 5.0 / 9.0;
        cout << "Same Temperature in Celsius: " << result << endl;
    } else if (choice == 2) {
        cout << "Enter Temperature in Celsius: ";
        cin >> temp;
        result = (temp * 9.0 / 5.0) + 32;
        cout << "Same Temperature in Fahrenheit: " << result << endl;
    } else {
        cout << "Invalid choice." << endl;
    }
    cout << "Press Any Key to Continue...." << endl;
    return 0;
}

Sample check: for choice 1 and Fahrenheit=98, Celsius = (98-32)*5/9 = 36.7, matching the given sample output.


2016 · Paper-I · Q3(a) (6 marks)

Question

Define a function named monthly-profit which will calculate the monthly profit on the given investment amount. Function will take two float arguments, percent profit rate and investment amount and return the monthly profit (float). Write function prototype, function definition and a main program to demonstrate the functionality. Sample execution of the program is given below. Note that monthly profit 4000 has been calculated by the function by doing (8/100) * 50000. User can enter any values therefore write generalized function (user variables, not given values). Enter percent profit rate: 8 Enter investment amount: 50000 Monthly profit: 4000 Press Any Key to Continue....

Solution

#include <iostream>
using namespace std;

// function prototype
float monthly_profit(float rate, float investment);

int main() {
    float rate, investment, profit;
    cout << "Enter percent profit rate: ";
    cin >> rate;
    cout << "Enter investment amount: ";
    cin >> investment;

    profit = monthly_profit(rate, investment);
    cout << "Monthly profit: " << profit << endl;
    cout << "Press Any Key to Continue...." << endl;
    return 0;
}

// function definition
float monthly_profit(float rate, float investment) {
    return (rate / 100) * investment;
}

Sample check: rate=8, investment=50000 -> (8/100)*50000 = 4000, matching the given sample.


2016 · Paper-I · Q4(a) (6 marks)

Question

Define a structure to store records of Persons. We want to store only Name, age and address of Person. Write main program to input record of one person and display 'Young' if its age is less than 20 or 'Old' if the age is greater than 50 and 'Middle' if the age of person is between 21 and 49. Sample execution of the main program is given below: Enter Name = Kashif Enter Age = 19 Enter Address = H 120, St: 08, KAR. Person is YOUNG Press Any Key to Continue ......

Solution

#include <iostream>
using namespace std;

struct Person {
    char name[50];
    int age;
    char address[100];
};

int main() {
    Person p;
    cout << "Enter Name = "; cin >> p.name;
    cout << "Enter Age = "; cin >> p.age;
    cout << "Enter Address = "; cin.ignore(); cin.getline(p.address, 100);

    if (p.age < 20)
        cout << "Person is YOUNG" << endl;
    else if (p.age > 50)
        cout << "Person is OLD" << endl;
    else
        cout << "Person is MIDDLE" << endl;

    cout << "Press Any Key to Continue ......" << endl;
    return 0;
}

For age=19 the output is 'Person is YOUNG', matching the sample.


Part B — MCQs

2026 · Paper-I · Q3 (MCQ)

A programmer wants to group different data types. What should he/she use?

  • A. Structures
  • B. Arrays
  • C. Unions
  • D. None of these

Answer: A

Explanation: A structure groups variables of different data types together under one name, each with its own memory, which is exactly what is needed to bundle heterogeneous data (arrays hold only one data type, and unions share memory rather than truly 'grouping' all values simultaneously).


2026 · Paper-I · Q7 (MCQ)

A function needs to modify an input variable. How should the parameter be passed?

  • A. By value
  • B. By reference
  • C. By pointer
  • D. None of these

Answer: B

Explanation: Passing by reference lets the function operate directly on the caller's original variable (an alias to it), so any modification inside the function is reflected back in the caller, unlike pass-by-value which only modifies a local copy.


2026 · Paper-I · Q8 (MCQ)

A developer wants to define a class with methods that can be used with different data types. What to use?

  • A. Templates
  • B. Inheritance
  • C. Polymorphism
  • D. None of these

Answer: A

Explanation: C++ templates let a single class/function definition be generically instantiated for any data type at compile time, exactly matching the need for type-independent, reusable methods.


2026 · Paper-I · Q13 (MCQ)

In Recursion, what is crucial to prevent infinite loops?

  • A. Base case
  • B. Recursive call
  • C. Loop usage
  • D. None of these

Answer: A

Explanation: A base case is the terminating condition that stops further recursive calls; without it, a recursive function would call itself indefinitely, causing infinite recursion and a stack overflow.


2025 · Paper-I · Q6 (MCQ)

Which of the following is the false statement in C language?

  • A. static a = 10;
  • B. static int func (int);
  • C. static static int a;
  • D. None of these

Answer: C

Explanation: A storage-class specifier such as static cannot be repeated in a single declaration, so 'static static int a;' is a syntax error, while the other two are legal (old-style implicit int and a static function prototype).


2025 · Paper-I · Q15 (MCQ)

What is the output of the following code? int main(){ int a = 40; int* ptr = &a; int& ref = *ptr; ref = 60; cout << a; }

  • A. 40
  • B. 60
  • C. Error
  • D. None of these

Answer: B

Explanation: ref is a reference bound to *ptr, which is a itself, so ref is just another name for a; assigning ref = 60 changes a to 60, which is what gets printed.


2024 · Paper-I · Q16 (MCQ)

Select the correct output of the following code. #include <stdio.h> int main() { int arr[5]={10,20,30,40,50}; printf("%d", arr[5]); return 0; }

  • A. Garbage value
  • B. 20
  • C. 30
  • D. None of these

Answer: A

Explanation: arr has valid indices 0-4; arr[5] accesses memory one element past the end of the array, which is undefined behavior in C and typically prints whatever garbage value happens to be in that memory location.