প্রITProstutiAssistant Programmer (AP) Log in

Chapter 1

Solved Past Questions: 2023 and 2024

3 sections · 26 questions

This chapter gives full model answers to all technical questions of three BIBM Assistant Programmer written exams. Solutions for maths, English, translation and Focus Writing are in separate chapters. The questions were compiled from candidates' memory, so some wording was incomplete. Where an interpretation had to be assumed, it is stated clearly in the answer.

How to use First read only the question box and write your own answer on paper in 6–8 minutes. Then compare it with the model answer. Practise the step tables for heap, hashing and LRU, and the code, by hand.

1.1Combined 5 Bank — Assistant Programmer (03.02.2023)

ItemDetails
Date03.02.2023
Set byBIBM
Pattern80 MCQ (IT 75 + maths and GK 25); written 200 = IT 150 + 4 maths questions (20) + Focus 10 + translation B/E 20
TopicsHeap, SQL join, UML class diagram, Function Point, array function, TLS, CRC, graph representation, browser security, LRU
Question 1 Combined 5 Bank AP 2023 Show the Max Heap after each of the following operations [a–j]. Also show which value is returned whenever the root is extracted: Insert 5, Insert 6, Insert 8, Extract-Root, Insert 4, Insert 11, Extract-Root, Insert 7, Extract-Root, Extract-Root.
Remember the rules Insert: Place the new value at the end of the array. Then sift-up: swap while the parent (index ⌊(i−1)/2⌋) is smaller.
Extract-Root: Return the root (maximum value). Move the last element to the root and sift-down: swap with the larger child (children: 2i+1, 2i+2).
StepOperationWhat happensHeap (array)Returned
aInsert 5Heap is empty; 5 becomes the root[5]—
bInsert 66 goes to the end; parent 5 < 6, so swap[6, 5]—
cInsert 88 goes to index 2; parent 6 < 8, so swap[8, 5, 6]—
dExtract-Root8 is removed; last element 6 moves to the root; child 5 < 6, so nothing changes[6, 5]8
eInsert 44 goes to index 2; parent 6 > 4, so it stays[6, 5, 4]—
fInsert 1111 goes to index 3; swap with parent 5, then swap with root 6[11, 6, 4, 5]—
gExtract-Root11 is removed; 5 moves to the root; swap with the larger child 6[6, 5, 4]11
hInsert 77 goes to index 3; swap with parent 5, then swap with root 6[7, 6, 4, 5]—
iExtract-Root7 is removed; 5 moves to the root; swap with the larger child 6[6, 5, 4]7
jExtract-Root6 is removed; 4 moves to the root; child 5 > 4, so swap[5, 4]6
a) Insert 55[5] b) Insert 665[6, 5] c) Insert 8856[8, 5, 6] d) Extract → 865[6, 5] e) Insert 4654[6, 5, 4] f) Insert 1111645[11, 6, 4, 5] g) Extract → 11654[6, 5, 4] h) Insert 77645[7, 6, 4, 5] i) Extract → 7654[6, 5, 4] j) Extract → 654[5, 4]
Figure 1.1: Max Heap after each operation (red title = Extract, value after the arrow = returned value)

Answer: The Extract-Root operations return 8, 11, 7, 6 in order. The heap finally holds [5, 4].

Question 2 Combined 5 Bank AP 2023 A relational database has five tables: S(sid, A), T(tid, B), U(uid, C), R(sid, tid, D), Q(tid, uid, E). Primary keys are sid, tid, uid, (sid, tid) and (tid, uid) respectively. R implements a many-to-many relationship between S and T, and Q implements a many-to-many relationship between T and U. Write an SQL query that returns all records of the form (sid, uid), where sid is the key of an S-record, uid is the key of a U-record, and the two records are related through R and Q. Use SELECT, not SELECT DISTINCT.

Logic: An S-record and a U-record are related only when a common T-record (tid) exists such that R has (sid, tid) and Q has (tid, uid). So join R and Q on tid.

-- Short form (R.sid and Q.uid are foreign keys, so joining S and U is optional)
SELECT R.sid, Q.uid
FROM   R
JOIN   Q ON R.tid = Q.tid;

-- Full form (also confirms that the records really exist in S and U)
SELECT S.sid, U.uid
FROM   S
JOIN   R ON S.sid = R.sid
JOIN   Q ON R.tid = Q.tid
JOIN   U ON Q.uid = U.uid;
Why not DISTINCT, and what it means If the same (sid, uid) pair is linked through more than one tid, it appears more than once in the result (for example s1–t1–u1 and s1–t2–u1). The question forbids DISTINCT, so this repetition is acceptable. Mentioning this in one line shows the examiner that you understand join behaviour.
Question 3 Combined 5 Bank AP 2023 Draw a class diagram for a book: a book is composed of several parts, which are composed of several chapters; chapters are composed of sections. A book has a publisher, publication date and an ISBN; a part has a title and a number; a chapter has a title, a number and an abstract; a section has a title and a number.

"Composed of" means Composition (filled diamond ◆). The part cannot exist apart from the whole: if the book is deleted, its parts, chapters and sections are deleted too. Multiplicity is 1 on the whole side and 1..* on the part side ("several").

BookPartChapterSection - publisher: String- publicationDate: Date- isbn: String - title: String- number: int - title: String- number: int- abstract: String - title: String- number: int 11..*11..*11..* ◆ = Composition (whole–part, lifecycle dependent) · Book ◆→ Part ◆→ Chapter ◆→ Section
Figure 1.2: Book–Part–Chapter–Section class diagram (composition)

Write this explanation: (1) four classes and the attributes of each; (2) the relationships are composition, because a chapter exists only inside one part; (3) the multiplicity of every relationship is 1 → 1..*. You may also add operations, such as Book.addPart() or Chapter.getSections().

Question 4(a) Combined 5 Bank AP 2023 A software project estimates the unadjusted function point (UFP) as 180, the value adjustment factor (VAF) as 0.87, and the performance (productivity) factor as 4. Find the required effort in person-days.
FP = UFP × VAF   |   Effort = FP ÷ Productivity (FP per person-day)

Step 1: FP = 180 × 0.87 = 156.6
Step 2: Assume "performance factor 4" means productivity, i.e. 4 FP per person-day.
Effort = 156.6 ÷ 4 = 39.15 ≈ 40 person-days

State your assumption clearly The question does not give the unit of "performance factor". If it means "4 person-days per FP", then Effort = 156.6 × 4 = 626.4 person-days. In the exam, write one line "Assuming productivity = 4 FP/person-day" and give the first answer. VAF normally comes from the formula VAF = 0.65 + 0.01 × ΣFi; here it is given directly.
Question 4(b) Combined 5 Bank AP 2023 Write a function to find the smallest value in an array. The array is passed to the function as a parameter.

Logic: Treat the first element as min. Loop once over the remaining elements; if one is smaller than min, update min. Time O(n), extra space O(1).

/* C */
#include <stdio.h>

int findMin(int arr[], int n) {
    int min = arr[0];
    for (int i = 1; i < n; i++)
        if (arr[i] < min)
            min = arr[i];
    return min;
}

int main(void) {
    int a[] = {34, -7, 19, 0, 8};
    int n = sizeof(a) / sizeof(a[0]);
    printf("Smallest = %d\n", findMin(a, n));
    return 0;
}
/* Output: Smallest = -7 */
// Java
public class MinFinder {
    static int findMin(int[] arr) {
        if (arr == null || arr.length == 0)
            throw new IllegalArgumentException("empty");
        int min = arr[0];
        for (int i = 1; i < arr.length; i++)
            if (arr[i] < min) min = arr[i];
        return min;
    }

    public static void main(String[] args) {
        int[] a = {34, -7, 19, 0, 8};
        System.out.println("Smallest = " + findMin(a));
    }
}
// Output: Smallest = -7

In C, passing an array actually passes a pointer, so the size (n) must be passed as a separate parameter. In Java, the size comes from arr.length.

Question 5(a) Combined 5 Bank AP 2023 Suppose an attacker steals the private key of a website that uses Transport Layer Security (TLS) and remains undetected. What can the attacker do using the private key?

The server proves "I am the real site" using the private key that pairs with the public key in its certificate. If this key is stolen, the attacker can do the following:

  1. Impersonate the server: Run a fake site with the genuine, valid certificate. If users are redirected there by DNS spoofing, ARP spoofing or a fake Wi-Fi, the browser shows no warning.
  2. Active Man-in-the-Middle: Sit between the client and the real server and terminate the TLS connection on both sides. The attacker can read passwords, OTPs and card numbers, and can change the amount or destination account of a transaction.
  3. Decrypt recorded traffic (passive): If the server uses RSA key exchange (a non-forward-secret cipher suite of TLS 1.2), the session key comes from the premaster secret sent by the client, encrypted with that public key. So previously recorded sessions and all future sessions can be decrypted.
    If (EC)DHE is used (Forward Secrecy, mandatory in TLS 1.3), the private key is used only for signing in the handshake. Then past recorded traffic cannot be decrypted, but an active MitM (point 2) is still possible.
  4. Sign in the server's name: If the same key was also used to sign something else (such as code or messages), the attacker can forge signatures in the server's name.
Prevention and remedyWhy
Revoke the certificate immediately (CRL/OCSP) and generate a new key pairThe stolen key can no longer gain trust
Allow only ECDHE/TLS 1.3Ensures forward secrecy
Keep the private key in an HSMThe key cannot be extracted from the HSM
Certificate Transparency monitoringFake certificates get detected
Short-lived certificates, regular key rotationEven if stolen, the damage window is short
Question 5(b) Combined 5 Bank AP 2023 In cyclic redundancy check (CRC), the generator chosen is 11101010111. What is the probability of detecting a burst error of length 10?

The generator has 11 bits, so its degree is r = 11 − 1 = 10 (the CRC remainder is 10 bits).

Burst length LDetection probability
L ≤ r100% (all detected)
L = r + 11 − (1/2)r−1
L > r + 11 − (1/2)r

Here L = 10 and r = 10, so L ≤ r. The highest and lowest (x0) bits of the generator are both 1, so every burst error is detected; detection probability = 1 (100%).

For comparison: if L = 11, probability = 1 − 1/29 ≈ 0.998; if L ≥ 12, probability = 1 − 1/210 ≈ 0.999.

Question 6 Combined 5 Bank AP 2023 Consider the two standard representations of a directed graph: adjacency list and adjacency matrix. Give one problem that can be solved more efficiently with the adjacency-list representation than with the adjacency-matrix representation, and another problem that can be solved more efficiently with the adjacency matrix than with the adjacency list.
AspectAdjacency ListAdjacency Matrix
SpaceO(V + E): good for sparse graphsO(V²)
Find all neighbours of uO(out-degree(u))O(V), must scan the whole row
Is edge (u, v) present?O(out-degree(u))O(1)
BFS / DFSO(V + E)O(V²)
Find in-degreeO(V + E)O(V), one column

Faster with a list: In a sparse graph of 1 million nodes and 5 million edges (such as a bank customer transaction network), finding all reachable nodes by BFS/DFS, or counting the out-degree of every node. With a list this takes O(V + E); with a matrix, O(V²).
Faster with a matrix: Repeatedly asking "is there a direct edge from u to v?" (O(1) lookup), Floyd–Warshall all-pairs shortest path on a dense graph, or checking in O(V) time whether a vertex is a universal sink (in-degree V−1, out-degree 0).

Question 7(a) Combined 5 Bank AP 2023 Suppose A and B are two frames in a browser, loaded from different origins. Why is it a reasonable security policy to allow A to navigate B to another origin based only on whether the display area of A contains that of B, i.e., A already controls that area?

This question is about the browser's frame navigation policy. Current browsers follow the Descendant Policy: a frame may navigate only its own descendant frames to another URL.

  1. Pixel delegation argument: If B is inside the display area of A, that part of the screen was given by A itself. A could already show its own content there, remove B, or draw something over it. So allowing A to navigate B to another origin gives A no new power and does not reduce security.
  2. Same-Origin Policy stays intact: By navigating, A cannot read B's DOM, cookies or data; it only decides what loads in B's place. So confidentiality is not broken.
  3. Risk of a permissive policy: If any frame could navigate any frame (permissive policy), an attacker frame could send a login or payment frame inside another site to a fake page (frame hijacking / Guninski attack). The user would see the address of the real site, but the data would go to the attacker.
  4. Hence the limit: "Whoever owns the screen controls it." A can change only frames inside its own area. It cannot change frames of other origins beside or above it.
Question 7(b) Combined 5 Bank AP 2023 Consider the page reference string 1 2 3 4 2 3 4 1 2 1 1 3 1 4 with three frames. Using LRU, find the number of page faults.

In LRU (Least Recently Used), on a page fault the page that has not been used for the longest time is replaced. F = fault, H = hit.

Ref12342341211314
Frame 111144444444333
Frame 2–2222221111111
Frame 3––333333222224
F/HFFFFHHHFFHHFHF

Replacement decisions:

  • At ref 4, 1 is the oldest, so 1 is replaced.
  • At ref 1 (8th), the order is 2, 3, 4 (2 is the oldest), so 2 is replaced.
  • At ref 2 (9th), the order is 3, 4, 1, so 3 is replaced.
  • At ref 3 (12th), the order is 4, 2, 1, so 4 is replaced.
  • At ref 4 (14th), the order is 2, 3, 1, so 2 is replaced.

Answer: Page faults = 8, hits = 6; fault rate = 8/14 ≈ 57%.

1.2Bangladesh Bank — Assistant Programmer (03.02.2023)

ItemDetails
Date03.02.2023 (1 hour MCQ + 2 hours written)
Set byBIBM
Pattern80 MCQ; written = 9 subjective questions (150) + 4 maths questions (20) + Focus (10) + translation B/E (20)
TopicsHashing, graph representation, LCM program, SQL, UML, overriding/hiding, CIA and E2E encryption, Diffie-Hellman MitM
Question 1 BB AP 2023 Consider a hash table of size 13 with integer keys. The hash function is h(k) = k mod 13. Insert the keys 10, 3, 5, 6, 16, 17, 19 in the given order using linear probing to resolve collisions. Show all the work.
h(k) = k mod 13   |   Linear probing: hi(k) = (h(k) + i) mod 13, i = 0, 1, 2, …
Keyh(k) = k mod 13Probe sequenceFinal slot
101010 is empty10
333 is empty3
555 is empty5
666 is empty6
1633 (occupied by 3) → 4 is empty4
1744 (16) → 5 (5) → 6 (6) → 7 is empty7
1966 (6) → 7 (17) → 8 is empty8
Index0123456789101112
Key–––316561719–10––

Total collisions: 1 for 16, 3 for 17, 2 for 19, total 6. The continuous filled run from index 3 to 8 is an example of primary clustering, the main weakness of linear probing. Remedies are quadratic probing or double hashing. Load factor α = 7/13 ≈ 0.54.

Question 2 BB AP 2023 Give an adjacency-list representation for a complete binary tree on 7 vertices. Give an equivalent adjacency-matrix representation. Assume that vertices are numbered from 1 to 7 as in a binary heap.

With binary-heap numbering, the children of vertex i are 2i and 2i+1, and its parent is ⌊i/2⌋. The tree is treated as an undirected graph.

1234567
Figure 1.3: Complete binary tree with 7 vertices (heap numbering)

Adjacency List

1 → 2 → 3
2 → 1 → 4 → 5
3 → 1 → 6 → 7
4 → 2
5 → 2
6 → 3
7 → 3

If treated as directed (parent → child): 1→2,3; 2→4,5; 3→6,7; and the lists of 4–7 are empty.

Adjacency Matrix (symmetric)

1234567
10110000
21001100
31000011
40100000
50100000
60010000
70010000

Number of edges = V − 1 = 6. The list has 2 × 6 = 12 entries in total; the matrix has 7 × 7 = 49 cells, of which only 12 are 1. The tree is sparse, so the list saves more space here.

Question 3 BB AP 2023 Given two integers A and B as input, write a program to compute the LCM of A and B.
LCM(A, B) = |A × B| ÷ GCD(A, B)   |   GCD (Euclid): gcd(a, b) = gcd(b, a mod b), gcd(a, 0) = a

To avoid overflow, compute in the order (a / gcd) * b. This divides first, then multiplies.

/* C */
#include <stdio.h>
#include <stdlib.h>

long long gcd(long long a, long long b) {
    while (b != 0) {
        long long t = a % b;
        a = b;
        b = t;
    }
    return a;
}

int main(void) {
    long long a, b;
    printf("Enter A and B: ");
    scanf("%lld %lld", &a, &b);
    a = llabs(a); b = llabs(b);
    if (a == 0 || b == 0) {
        printf("LCM = 0\n");
        return 0;
    }
    long long lcm = (a / gcd(a, b)) * b;
    printf("LCM = %lld\n", lcm);
    return 0;
}
/* Input: 12 18  ->  LCM = 36 */
// Java
import java.util.Scanner;

public class LCM {
    static long gcd(long a, long b) {
        while (b != 0) {
            long t = a % b;
            a = b;
            b = t;
        }
        return a;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        long a = Math.abs(sc.nextLong());
        long b = Math.abs(sc.nextLong());
        long lcm = (a == 0 || b == 0) ? 0
                 : (a / gcd(a, b)) * b;
        System.out.println("LCM = " + lcm);
    }
}
// Input: 12 18  ->  LCM = 36

Trace (12, 18): gcd(12, 18) → gcd(18, 12) → gcd(12, 6) → gcd(6, 0) = 6; LCM = 12/6 × 18 = 36. Time complexity O(log min(A, B)).

Question 4 BB AP 2023 Write an SQL query that returns the number of movies that are romantic comedies. Tables: Movies(mid, title, year), People(pid, name), Genres(gid, genre), ActsIn(pid, mid), HasRole(pid, mid, role), HasGenre(gid, mid). In ActsIn and HasRole, pid is a foreign key into People and mid into Movies; in HasGenre, mid is a foreign key into Movies and gid into Genres.

Logic: "Romantic comedy" means the same movie has two genres: Romance and Comedy. Each genre is in a separate row of HasGenre, so the two conditions cannot be matched in a single row.

-- Method 1: GROUP BY + HAVING (cleanest)
SELECT COUNT(*) AS romantic_comedy_count
FROM (
    SELECT hg.mid
    FROM   HasGenre hg
    JOIN   Genres g ON g.gid = hg.gid
    WHERE  g.genre IN ('Romance', 'Comedy')
    GROUP  BY hg.mid
    HAVING COUNT(DISTINCT g.genre) = 2
) AS rc;

-- Method 2: two IN subqueries
SELECT COUNT(*) AS romantic_comedy_count
FROM   Movies m
WHERE  m.mid IN (SELECT hg.mid FROM HasGenre hg JOIN Genres g ON g.gid = hg.gid
                 WHERE g.genre = 'Romance')
  AND  m.mid IN (SELECT hg.mid FROM HasGenre hg JOIN Genres g ON g.gid = hg.gid
                 WHERE g.genre = 'Comedy');
Common mistake Writing WHERE genre = 'Romance' AND genre = 'Comedy' always returns 0, because one row's genre cannot be two values at the same time. Writing OR also counts movies that are only romance or only comedy. If the database has a single genre named "Romantic Comedy", the simple WHERE g.genre = 'Romantic Comedy' is enough. State this assumption in your answer.
Question 5 BB AP 2023 Draw a class diagram. A token-ring based local-area network (LAN) is a network consisting of nodes, in which network packets are sent around. Every node has a unique name within the network and refers to its next node. Different kinds of nodes exist: workstations are originators of messages; servers and printers are network nodes that can receive messages. Packets contain an originator, a destination and content, and are sent around on a network. A LAN is a circular configuration of nodes.
LAN«abstract»Node PacketWorkstationServerPrinter - topology = ring+ circulate(p: Packet) - name: String {unique}+ forward(p: Packet) - originator: Workstation- destination: Node- content: String + originate(): Packet+ receive(p: Packet)+ receive(p: Packet) 12..* consists of (ring) next1 destination 10..* originator 1originates ▸0..* △ = Generalization (is-a) · ◆ = Composition · → = Association
Figure 1.4: Class diagram of a token-ring LAN
SentenceWhat it means in the model
"LAN consists of nodes; circular configuration"LAN ◆— Node, composition, multiplicity 1 → 2..*; the ring is formed by a self-association
"Every node has a unique name and refers to its next node"Node has name {unique}; self-association next, multiplicity 1
"Different kinds of nodes"Node is an abstract superclass; Workstation, Server and Printer are its subclasses (generalization)
"Workstations are originators of messages"Workstation 1 —originates→ 0..* Packet
"Servers and printers can receive messages"Server and Printer have a receive(p: Packet) operation
"Packets contain originator, destination and content"Packet attributes or associations: originator (Workstation), destination (Node), content
Question 6 BB AP 2023 Determine the overloaded methods, the overridden methods and the hidden superclass methods in the following code:
public class A {
    public void m1() {}
    public void m2() {}
    public void m3(int i) {}
    public void m4(String i) {}
}
public class B extends A {
    public static void m1() {}
    public void m2() {}
    public void m3(int i) {}
    public static void m4(String i) {}
}
ConceptConditionWhen it is resolved
OverloadingSame name, different parameter list (in the same class or a subclass)Compile time
OverridingAn instance method with the same signature in the subclass; the parent's method is also an instance methodRuntime (dynamic dispatch)
HidingBoth parent and child methods are static, with the same signatureCompile time (based on the reference type)
MethodIn AIn BResult
m1()instancestaticCompile error: "m1() in B cannot override m1() in A; overriding method is static". A static method cannot hide an instance method.
m2()instanceinstance, same signatureOverridden
m3(int)instanceinstance, same signatureOverridden
m4(String)instancestaticCompile error (same reason as m1)

Conclusion: m2 and m3 are overridden. m1 and m4 will not compile, so no hiding happens here. No method has a different parameter list, so there is no overloading either. Also fix two problems in the code: extends a must be extends A, and one .java file cannot contain two public classes, so put them in two separate files.

When hiding and overloading would occur: If A's m1 were public static void m1(), B's static m1() would hide it. If B had public void m3(double d), it would overload A's m3(int).

class A {
    public static void s()   { System.out.println("A.s"); }
    public void m()          { System.out.println("A.m"); }
}
class B extends A {
    public static void s()   { System.out.println("B.s"); }   // hiding
    @Override public void m(){ System.out.println("B.m"); }   // overriding
    public void m(int x)     { System.out.println("B.m(int)"); } // overloading
}
public class Demo {
    public static void main(String[] args) {
        A ref = new B();
        ref.m();   // B.m  : at runtime, uses the object's type (B)
        ref.s();   // A.s  : at compile time, uses the reference's type (A), i.e. hiding
    }
}
Question 7 BB AP 2023 A question about the CIA triad: to protect its data, a company decided to add end-to-end encryption. Which layer of the OSI model is suitable for it, considering development time, software maintainability and development cost? Give reasons.

CIA Triad:

  • Confidentiality: Unauthorized parties cannot read the information.
  • Integrity: Information cannot be changed without authorization.
  • Availability: Authorized users get the information when they need it.

End-to-end encryption (E2EE) mainly ensures confidentiality and, with a MAC or AEAD, integrity.

Answer: Application Layer (Layer 7).

LayerExampleIs it E2E?Cost and maintenance
Network (L3)IPsecNo; it protects host-to-host or gateway-to-gateway, not user-to-userNeeds OS and router configuration; needs experts
Transport (L4)TLSNo; it is decrypted at every hop (server, proxy, load balancer), so the server sees plaintextEasy, but does not meet the goal
Application (L7)Signal Protocol, PGP, libsodiumYes; only the sender's and receiver's apps hold the keysReady-made libraries; no network infrastructure change

Reasons:

  1. Development time: Tested libraries (OpenSSL, libsodium, Bouncy Castle) can be used directly in the app code. No need to touch the kernel or network devices.
  2. Maintainability: The encryption logic stays inside the app. Nothing needs to change if the network, cloud provider or ISP changes, and updates ship like any normal software release.
  3. Development cost: No cost for special hardware (VPN concentrator) or for configuring every router.
  4. True end-to-end: Only at this layer can intermediate servers, even the company's own servers, not read the data. So confidentiality holds even if data leaks.

Limitations: it must be implemented separately in each app, and key management (key exchange, backup) must be designed carefully. In practice, TLS is also kept underneath Application-layer E2EE (defense in depth).

Question 8 BB AP 2023 Describe a man-in-the-middle attack on the Diffie-Hellman key exchange protocol in which the adversary generates two public key pairs for the attack.

Core weakness: Basic Diffie-Hellman has no authentication. Nobody verifies that a received public key really belongs to the other party. Public values: prime q and primitive root α.

Attack steps (attacker Darth, as described by Stallings):

  1. Darth picks two private keys XD1 and XD2 and computes the matching public keys: YD1 = αXD1 mod q, YD2 = αXD2 mod q.
  2. Alice sends YA to Bob. Darth intercepts it, sends YD1 to Bob, and computes K2 = YAXD2 mod q.
  3. Bob receives YD1 and computes K1 = YD1XB mod q.
  4. Bob sends YB to Alice. Darth intercepts it, sends YD2 to Alice, and computes K1 = YBXD1 mod q.
  5. Alice receives YD2 and computes K2 = YD2XA mod q.

Result: Alice and Darth share the same key K2, and Bob and Darth share the same key K1. Alice and Bob think they share a secret key with each other. Darth can decrypt and read or modify every message, then re-encrypt it and forward it.

Numerical example: q = 23, α = 5 Alice: XA = 6 → YA = 56 mod 23 = 8  |  Bob: XB = 15 → YB = 515 mod 23 = 19
Darth: XD1 = 3 → YD1 = 125 mod 23 = 10  |  XD2 = 7 → YD2 = 57 mod 23 = 17
Alice: K2 = 176 mod 23 = 12  |  Darth: K2 = 87 mod 23 = 12 ✔
Bob: K1 = 1015 mod 23 = 5  |  Darth: K1 = 193 mod 23 = 5 ✔
Without the attack, Alice and Bob would get the same key: 196 mod 23 = 815 mod 23 = 2.
AliceDarthBob X_D1 = 3, X_D2 = 7 → Y_D1 = 10, Y_D2 = 17 ① Y_A = 8 (intercepted) ② Y_D1 = 10 (posing as Alice) ③ Y_B = 19 (intercepted) ④ Y_D2 = 17 (posing as Bob) K2 = 17^6 mod 23 = 12K2 = 8^7 = 12 · K1 = 19^3 = 5 (mod 23)K1 = 10^15 mod 23 = 5 Alice ↔ Darth share K2, Darth ↔ Bob share K1; Darth can read and modify all messages both ways
Figure 1.5: MitM attack on Diffie-Hellman using two key pairs

Prevention:

  • Authenticate the public keys: DH with digital signatures or certificates (Station-to-Station protocol, signed ECDHE in TLS).
  • Compare key fingerprints over a separate channel (e.g. Signal's safety number).
  • Use a pre-shared key or PKI.

1.3Combined 5 Bank (Job ID 10198) — Assistant Programmer (09.02.2024)

ItemDetails
BanksSonali Bank, BKB, Karmasangsthan Bank, ICB, etc.
Date09.02.2024 (1 hour MCQ + 2 hours written)
Question setterBIBM
Type80 MCQ (IT 50 + Math and GK 20); written = 10 subjective (150) + 4 math (20) + Focus (20) + Letter (10)
FeatureProgramming-heavy: 3 programs to write, 1 output to find, 3 SQL queries, then theory and a question about your own project
Question 1 Combined 5 Bank AP 2024 Write a C/Java program that shows the prime numbers between 1 and n, where n is given by user input.

Logic: x is prime if x ≥ 2 and no number from 2 to √x divides x. Using the loop condition d * d <= x avoids the need for a sqrt function. Each number costs O(√x), total O(n√n). For large n, the Sieve of Eratosthenes is faster: O(n log log n).

/* C */
#include <stdio.h>

int isPrime(int x) {
    if (x < 2) return 0;
    for (int d = 2; d * d <= x; d++)
        if (x % d == 0) return 0;
    return 1;
}

int main(void) {
    int n;
    printf("Enter n: ");
    scanf("%d", &n);
    printf("Primes between 1 and %d:\n", n);
    for (int i = 2; i <= n; i++)
        if (isPrime(i))
            printf("%d ", i);
    printf("\n");
    return 0;
}
// Java
import java.util.Scanner;

public class Primes {
    static boolean isPrime(int x) {
        if (x < 2) return false;
        for (int d = 2; d * d <= x; d++)
            if (x % d == 0) return false;
        return true;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter n: ");
        int n = sc.nextInt();
        for (int i = 2; i <= n; i++)
            if (isPrime(i))
                System.out.print(i + " ");
        System.out.println();
    }
}

Sample: Enter n: 30 → 2 3 5 7 11 13 17 19 23 29. 1 is not prime, so the loop starts at 2.

Question 2 Combined 5 Bank AP 2024 Write a C/Java program that calculates the sum of the series 1 + 2 + 4 + 7 + 11 + … up to the n-th term.

Pattern: The differences between adjacent terms are 1, 2, 3, 4, …. So each term is the previous term plus k (k = 1, 2, 3, …).

k-th term: tk = 1 + k(k − 1)/2   |   Sum of n terms: Sn = n + (n − 1)n(n + 1)/6

Check: t5 = 1 + 5·4/2 = 11 ✔; S5 = 5 + 4·5·6/6 = 5 + 20 = 25 = 1 + 2 + 4 + 7 + 11 ✔

/* C */
#include <stdio.h>

int main(void) {
    int n;
    long long term = 1, sum = 0;
    printf("Enter n: ");
    scanf("%d", &n);
    for (int k = 1; k <= n; k++) {
        printf("%lld%s", term, k < n ? " + " : "");
        sum += term;
        term += k;      /* next term = term + k */
    }
    printf("\nSum = %lld\n", sum);
    return 0;
}
// Java
import java.util.Scanner;

public class SeriesSum {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter n: ");
        int n = sc.nextInt();
        long term = 1, sum = 0;
        for (int k = 1; k <= n; k++) {
            System.out.print(term + (k < n ? " + " : ""));
            sum += term;
            term += k;
        }
        System.out.println("\nSum = " + sum);
        // closed form check:
        long f = n + (long)(n - 1) * n * (n + 1) / 6;
        System.out.println("Formula = " + f);
    }
}

Sample: n = 5 → 1 + 2 + 4 + 7 + 11, Sum = 25. For n = 7 the terms go up to 16 and 22, Sum = 63 (by formula 7 + 6·7·8/6 = 63 ✔).

Question 3 Combined 5 Bank AP 2024 Write a program in C/Java to print the following Floyd's triangle (0–1 pattern). N is given by user input. For n = 5:
1
01
101
0101
10101

Pattern analysis: Row i has i digits. Odd rows start with 1 and even rows start with 0, then 1 and 0 alternate. Both rules combine into one: if (i + j) is even print 1, if odd print 0 (i and j counted from 1).

/* C */
#include <stdio.h>

int main(void) {
    int n;
    printf("Enter n: ");
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++)
            printf("%d", (i + j) % 2 == 0 ? 1 : 0);
        printf("\n");
    }
    return 0;
}
// Java
import java.util.Scanner;

public class BinaryFloyd {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        for (int i = 1; i <= n; i++) {
            StringBuilder row = new StringBuilder();
            for (int j = 1; j <= i; j++)
                row.append((i + j) % 2 == 0 ? 1 : 0);
            System.out.println(row);
        }
    }
}

Check: i = 1: j = 1 → 2 is even → "1". i = 2: 3 → 0, 4 → 1 → "01". i = 4: 5, 6, 7, 8 → "0101". Matches the sample in the question exactly ✔. If you want the usual number-based Floyd's triangle (1 / 2 3 / 4 5 6 …), keep a counter and write printf("%d ", c++) each time.

Question 4 Combined 5 Bank AP 2024 Find the output of the following program:
#include <stdio.h>
int fun(int i) {
    if (i <= 0) return;
    printf("%d, ", i--);
    fun(--i);
    printf("%d, ", i);
}
int main() {
    fun(5);
}

Remember: i-- (post-decrement) uses the value first, then decrements. --i (pre-decrement) decrements first, then uses the value. So in each call, i decreases by 2 in total. The second printf runs after the recursive call returns, so those values print in reverse order.

CallFirst printfChange in iRecursive callSecond printf after return
fun(5)"5, "i-- → 4, --i → 3fun(3)"3, " (last)
fun(3)"3, "i-- → 2, --i → 1fun(1)"1, "
fun(1)"1, "i-- → 0, --i → −1fun(−1)"−1, "
fun(−1)—i ≤ 0, so it returns without printing anything

Order: going down: 5, 3, 1 → fun(−1) returns → coming back up: −1 (fun(1)), 1 (fun(3)), 3 (fun(5)).

Output: 5, 3, 1, -1, 1, 3,
Subtle point (write it in one line in the answer) int fun() is a non-void function, yet return; has no value and there is no return at the end. In C99/C11 this is a constraint violation or a warning, but since the returned value is never used, most compilers (gcc) give a warning and still produce the output above. The "I", "Printf" and "Ø" in the question paper are OCR or typing errors; they are taken as i, printf and 0.
Questions 5–6 Combined 5 Bank AP 2024 Given two tables Department and Employee:
CREATE TABLE Department (DeptCode INT, DeptName VARCHAR(20), Location VARCHAR(20));
CREATE TABLE Employee   (EmpCode INT, EmpFname VARCHAR(20), Salary INT,
                         Commission INT, DeptCode VARCHAR(20));
(a) Select every EmpFname with total salary (total salary = salary + commission). (b) Select EmpFname and Location of employees whose salary is greater than the average salary, ordered by EmpFname. (c) Select EmpFname and the count of employees, ordered by the employee count ascending.

Schema correction (mention in the answer): The type of Employee's DeptCode should be INT, the same as Department's DeptCode, so that the join and foreign key work properly. In the original DDL there is no comma after Commission INT and there is an extra comma at the end; both are syntax errors.

CREATE TABLE Department (
    DeptCode  INT PRIMARY KEY,
    DeptName  VARCHAR(20),
    Location  VARCHAR(20)
);
CREATE TABLE Employee (
    EmpCode    INT PRIMARY KEY,
    EmpFname   VARCHAR(20),
    Salary     INT,
    Commission INT,
    DeptCode   INT REFERENCES Department(DeptCode)
);

-- (a) Total salary; if Commission is NULL, treat it as 0
SELECT EmpFname,
       Salary + COALESCE(Commission, 0) AS TotalSalary
FROM   Employee;

-- (b) Name and Location of those who earn more than the average salary
SELECT   e.EmpFname, d.Location
FROM     Employee e
JOIN     Department d ON e.DeptCode = d.DeptCode
WHERE    e.Salary > (SELECT AVG(Salary) FROM Employee)
ORDER BY e.EmpFname;

-- (c) Number of employees for each EmpFname, in order of count
SELECT   EmpFname, COUNT(EmpCode) AS EmpCount
FROM     Employee
GROUP BY EmpFname
ORDER BY EmpCount ASC;
Explanation and alternatives (a): NULL + number = NULL, so without COALESCE (or IFNULL in MySQL, ISNULL in SQL Server), an employee with no commission would show a NULL total salary.
(b): AVG() cannot be used directly in WHERE, so a subquery is needed.
(c): The question is ambiguous. If a non-aggregate column (EmpFname) is kept with an aggregate, it must be in GROUP BY. Above, it is taken as "how many employees share the same name". If the intent is the number of employees in each department:
SELECT d.DeptName, COUNT(e.EmpCode) AS EmpCount
FROM Department d LEFT JOIN Employee e ON e.DeptCode = d.DeptCode
GROUP BY d.DeptName
ORDER BY EmpCount ASC;
And to show the total number of employees beside each name, use a window function: SELECT EmpFname, COUNT(*) OVER () AS TotalEmp FROM Employee ORDER BY EmpCode;. Write your own interpretation in one line on the answer sheet.
Question 7 Combined 5 Bank AP 2024 What is the difference between a stack and a queue? Also write two uses of each.
AspectStackQueue
PrincipleLIFO (Last In First Out)FIFO (First In First Out)
EndsOne end (top). Both insert and delete happen hereTwo ends: insert at rear, delete at front
Operationspush, pop, peekenqueue, dequeue, front
Pointertopfront and rear
Complexitypush/pop O(1)enqueue/dequeue O(1) (in a circular array or linked list)
Variants—Circular queue, priority queue, deque
Real-life exampleA pile of platesA line at a bank counter
Uses of a stack
  1. Call stack for function calls and recursion, holding return addresses and local variables.
  2. Expression evaluation and infix → postfix conversion; checking balanced parentheses.
  3. (Extra) Undo/Redo, browser Back button, DFS.
Uses of a queue
  1. CPU scheduling (Round Robin ready queue) and printer spooling.
  2. BFS traversal; packet buffer in a network router.
  3. (Extra) Bank token system, message queues (RabbitMQ, Kafka).
Question 8 Combined 5 Bank AP 2024 What is polymorphism? Describe the different types of polymorphism.

Definition: Polymorphism (poly = many, morph = form) means using the same interface or name to get different behavior from objects of different types. It is one of the four pillars of OOP; the other three are encapsulation, inheritance and abstraction.

TypeOther nameHowBinding
Compile-timeStatic polymorphismMethod overloading (same name, different parameters); operator overloading in C++Early/static binding
RuntimeDynamic polymorphismMethod overriding + upcasting (parent reference, child object); virtual functions in C++Late/dynamic binding
ParametricGenerics / TemplatesJava's List<T>, C++ templates. The same code works with different typesCompile time
// Compile-time: overloading
class Calculator {
    int    add(int a, int b)          { return a + b; }
    double add(double a, double b)    { return a + b; }
    int    add(int a, int b, int c)   { return a + b + c; }
}

// Runtime: overriding
abstract class Account {
    abstract double interest(double balance);
}
class Savings extends Account {
    @Override double interest(double b) { return b * 0.05; }
}
class FixedDeposit extends Account {
    @Override double interest(double b) { return b * 0.09; }
}

public class Bank {
    public static void main(String[] args) {
        Calculator c = new Calculator();
        System.out.println(c.add(2, 3));        // 5    (int version)
        System.out.println(c.add(2.5, 3.5));    // 6.0  (double version)

        Account[] list = { new Savings(), new FixedDeposit() };
        for (Account a : list)                    // same call, different behavior
            System.out.println(a.interest(10000)); // 500.0, 900.0
    }
}

Benefits: Adding a new account type does not require changing Bank's loop (Open–Closed principle). Code becomes reusable and extensible.

Question 9 Combined 5 Bank AP 2024 Describe the different types of relationships in a DBMS.

In the ER model, a relationship is an association between two or more entities. It is classified in three ways.

(a) By cardinality (mapping)

TypeMeaningExampleImplementation in tables
One-to-One (1:1)One record of A relates to at most one of BCustomer — NID; Employee — DeskUNIQUE foreign key on either side
One-to-Many (1:N)One record of A relates to many of BBranch — Accounts; Department — EmployeesForeign key in the "many" side table
Many-to-One (N:1)1:N seen from the opposite sideAccounts — BranchSame
Many-to-Many (M:N)Many on both sidesCustomer — Account (joint account); Student — CourseJunction (bridge) table, composite PK from the two FKs, like R and Q in Question 2

(b) By degree

  • Unary (recursive): An entity is related to itself, e.g. Employee manages Employee, or Node next Node (token ring).
  • Binary: Two entities, e.g. Customer holds Account. This is the most common.
  • Ternary: Three entities together, e.g. Doctor–Patient–Medicine (prescribes), or Supplier–Part–Project.

(c) By participation

  • Total (mandatory): Every record must take part in the relationship, e.g. every Loan must have a Borrower. In an ER diagram it is shown with a double line.
  • Partial (optional): Not every record needs to take part, e.g. not every Customer has a Loan.

If "relation" means a table: base relation (stored table), view (virtual relation) and query result (derived relation). Add this in one line at the end of the answer if needed.

Question 10 Combined 5 Bank AP 2024 Describe a real-life software project you have built. What problems or challenges did you face during that time, and how did you solve them?
Strategy Pick your own thesis, internship or job project and write it in the structure below. A banking-related project is even better. The examiner checks whether you can identify problems and give technical solutions. Writing only "it was very hard" earns no marks. For each challenge, name the specific tool or technique.

Model answer (adapt it to your own project):

1. Project overview: "Micro-Loan Management System" — a web application that manages loan applications, approval, installment collection and reports for an NGO or microfinance institution. About 50 field workers and 10 branch managers use it; about 20,000 customer records.

2. Technology and my role: Java (Spring Boot) REST API, MySQL, React frontend, Git and Docker. As backend developer, I built the database design, the installment calculation module and reporting. Work followed Agile (2-week sprints).

ChallengeCauseSolution
Same installment posted twice (double posting)On a weak network, field workers pressed Submit repeatedly; concurrent requestsUsed transactions (@Transactional) and row-level locks; an idempotency key on every payment; disabled the button after a click
Monthly report very slow (about 40 seconds)Full table scan on large tables; N+1 queriesAnalyzed with EXPLAIN; composite index on (branch_id, due_date); JOIN FETCH; summary table updated by a nightly batch. Time dropped below 2 seconds
Requirements kept changingInterest rates and penalty rules differ by branchKept the rules in a configuration table instead of hard-coding them; took feedback with a demo at the end of every sprint
SecuritySensitive financial and personal dataPassword hashing with bcrypt; role-based access (RBAC); prepared statements to prevent SQL injection; HTTPS; audit log
"It works on my PC but not on the server" in deploymentEnvironment differencesDocker image, CI pipeline (GitHub Actions) and automated unit and integration tests

3. Result and lessons: A real-time dashboard replaced paper registers, and calculation errors fell to almost zero. Lessons: ensure data integrity (transactions, constraints) from the start, measure performance before optimizing, and keep regular communication with users. As a bank Assistant Programmer, this experience applies directly to building CBS-adjacent apps or internal tools.

ITProstuti — free preparation notes for Bangladesh bank and government IT job exams.

Past questions belong to their setters (BSCS, BIBM and others); solutions and notes are written for learning. Spotted a mistake? Note the page and section and report it.