Israel Bagrut Computer Science 5 Units study materials
Israel Bagrut Computer Science 5 Units study resources

Israel Bagrut Computer Science 5 Units practice questions

One question at a time. Build your Israel Bagrut Computer Science 5 Units understanding.

First 50 of 199 questions. Each one lists the choices, the correct answer, and an explanation. The checker at the top of this page saves progress in this browser when it is available.

Continue in the practice tool above to load more questions, 50 at a time.

Question 1Algorithms and Problem Solving

In the Bagrut 5-unit algorithm track, which data structure is described as LIFO (last in, first out)?

  1. Binary search tree
  2. Queue
  3. Stack Correct answer.
  4. Hash table

Explanation

A stack removes elements in reverse order of insertion, so the most recently pushed element is the first popped. That behaviour is exactly what LIFO means. A queue removes the oldest element first, and a binary search tree or hash table has no such ordering rule.

Question 2Algorithms and Problem Solving

A recursive function on a list of n elements calls itself once per element and performs O(1) work at each level. Which recurrence describes its running time?

  1. T(n) = 2T(n/2) + O(n)
  2. T(n) = n * T(n-1)
  3. T(n) = T(n-1) + O(1) Correct answer.
  4. T(n) = T(n/2) + O(1)

Explanation

Each call reduces the problem size by one and adds a constant amount of work, which is written T(n) = T(n-1) + O(1). Expanding the recurrence gives a linear total, O(n). The other forms describe divide-and-conquer or exponential recursion, not a single step per element.

Question 3Algorithms and Problem Solving

A binary search is run on a sorted array of 1024 elements. What is the maximum number of comparisons needed in the worst case?

  1. 11 Correct answer.
  2. 10
  3. 32
  4. 1024

Explanation

Binary search halves the remaining range each step, so the worst case is ceil(log2(n)) + 1 comparisons. For n = 1024, log2(1024) = 10, and one extra comparison is needed to confirm the final element. Therefore the worst case is 11 comparisons.

Question 4Algorithms and Problem Solving

Which sorting algorithm is stable and runs in O(n log n) worst-case time while using O(n) auxiliary memory?

  1. Merge sort Correct answer.
  2. Selection sort
  3. Quicksort
  4. Heapsort

Explanation

Merge sort splits the array, sorts each half, and merges them, guaranteeing O(n log n) time in every case. The merge step needs an auxiliary array of size O(n), and equal keys keep their relative order, making it stable. Quicksort and heapsort are not stable, and selection sort is quadratic.

Question 5Algorithms and Problem Solving

A two-dimensional array A is declared with 5 rows and 4 columns and stored in row-major order with 1-based indexing. At which address does A[3][2] begin if the base address is 100 and each element occupies 4 bytes?

  1. 128
  2. 136 Correct answer.
  3. 140
  4. 148

Explanation

In row-major order the offset is ((row - 1) * columns + (column - 1)) elements before the target. Here that is (2 * 4 + 1) = 9 elements, so the byte offset is 9 * 4 = 36. Adding the base address 100 gives 136.

Question 6Algorithms and Problem Solving

Which statement about a correct loop invariant is true?

  1. It must be false at the start so the loop can run
  2. It must hold before the loop, after each iteration, and therefore after termination Correct answer.
  3. It must hold only after the loop terminates
  4. It guarantees the loop always terminates

Explanation

A loop invariant is a property that is true before the first iteration and preserved by every iteration. By induction it therefore holds when the loop ends, which supports the correctness proof. An invariant alone does not prove termination, because termination needs a separate argument such as a decreasing variant.

Question 7Algorithms and Problem Solving

Which algorithm design technique repeatedly makes the locally best choice without backtracking?

  1. Greedy algorithm Correct answer.
  2. Dynamic programming
  3. Divide and conquer
  4. Backtracking

Explanation

A greedy algorithm builds a solution step by step, always taking the option that looks best at that moment and never revisiting it. Correctness then depends on proving the greedy-choice property. Dynamic programming and backtracking explicitly consider alternatives, and divide and conquer splits the input.

Question 8Algorithms and Problem Solving

What does the Big-O notation f(n) = O(g(n)) formally mean?

  1. f and g are equal for every input size
  2. f grows at least as fast as g for large n
  3. f is always faster than g on the actual computer
  4. There exist constants c > 0 and n0 such that f(n) <= c * g(n) for all n >= n0 Correct answer.

Explanation

Big-O gives an asymptotic upper bound: beyond some threshold n0, f(n) is bounded above by a constant multiple of g(n). It describes growth rate, not measured runtime. Saying f = O(g) therefore does not claim f and g are equal or that f is faster in practice.

Question 9Algorithms and Problem Solving

An algorithm performs 3n^2 + 50n + 200 basic operations. Which complexity class describes it?

  1. O(n^2) Correct answer.
  2. O(n log n)
  3. O(n^3)
  4. O(n)

Explanation

When n grows, the quadratic term 3n^2 dominates the linear term and the constant. Constants and lower-order terms are dropped in Big-O, so the expression is O(n^2). Choosing O(n^3) would be a valid but loose upper bound, not the tight class.

Question 10Algorithms and Problem Solving

Which traversal of a binary search tree outputs the keys in ascending sorted order?

  1. Inorder Correct answer.
  2. Postorder
  3. Preorder
  4. Level order

Explanation

In a binary search tree every key in the left subtree is smaller than the root and every key in the right subtree is larger. An inorder traversal visits left subtree, then root, then right subtree, so the output is sorted. Preorder and postorder visit the root before or after both subtrees and do not yield sorted order.

Question 11Algorithms and Problem Solving

A hash table uses chaining and currently holds n keys in m slots. What is the average time to search for a key when the hash function distributes keys uniformly?

  1. O(log n)
  2. O(1)
  3. O(1 + n/m) Correct answer.
  4. O(n^2)

Explanation

With uniform hashing, the average chain length is the load factor n/m. A search scans the chain of the target slot, so the expected cost is proportional to 1 + n/m. When the table is kept at a bounded load factor this is effectively constant.

Question 12Algorithms and Problem Solving

An array holds the values 4, 8, 15, 16, 23, 42 in ascending order. A binary search looks for the value 16. Which sequence of examined middle elements is correct?

  1. 15, 16, 23
  2. 16, 15, 23
  3. 8, 15, 16
  4. 15, 23, 16 Correct answer.

Explanation

The first middle of six elements is index 3 (value 15). Since 16 > 15, the search continues in the right half 16, 23, 42, whose middle is 23. Since 16 < 23, the search moves left and finds 16.

Question 13Algorithms and Problem Solving

A dynamic programming solution fills an n-by-n table, and each cell is computed from a constant number of previously filled cells. What are the time and space complexities?

  1. Time O(n^2), space O(1)
  2. Time O(n log n), space O(n)
  3. Time O(n^2), space O(n^2) Correct answer.
  4. Time O(2^n), space O(n)

Explanation

Filling every one of the n^2 cells in constant time each gives O(n^2) time. Storing the whole table requires O(n^2) memory, unless only the last row or diagonal is kept. The exponential bound would apply to naive recursion without memoization.

Question 14Algorithms and Problem Solving

A queue is implemented with an array of fixed size using a front index and a rear index that wrap around. Why is the circular arrangement used?

  1. To keep the queue sorted automatically
  2. To guarantee that enqueue never needs a comparison
  3. To allow removal of the middle element in O(1)
  4. To avoid wasting the slots that become free at the front after dequeues Correct answer.

Explanation

In a plain array queue, dequeuing advances the front and leaves unusable space at the beginning. Letting the rear index wrap around modulo the array size reuses those freed slots. This keeps enqueue and dequeue at O(1) without shifting elements.

Question 15Algorithms and Problem Solving

A linked list of n nodes is searched for a given value. Why is the worst case O(n) even though insertion at the head is O(1)?

  1. Because the list must be sorted before searching
  2. Because each node stores a large amount of data
  3. Because the head pointer must be updated on every comparison
  4. Because the nodes are not stored in contiguous memory, so reaching the k-th node requires following k links Correct answer.

Explanation

A linked list offers no index arithmetic, so the only way to reach a node is to follow the next pointers from the head. Reaching the last node therefore costs n steps. Insertion at the head is cheap because it only rewires one pointer.

Question 16Algorithms and Problem Solving

A recursive function computes Fibonacci numbers as fib(n) = fib(n-1) + fib(n-2) with no memoization. Why is its running time exponential?

  1. Because the recursion depth equals n factorial
  2. Because the same subproblems are recomputed many times, producing a branching call tree Correct answer.
  3. Because each call uses a large stack frame
  4. Because addition of large integers takes exponential time

Explanation

Without memoization, fib(n-2) is recomputed inside every call to fib(n-1), so the call tree branches repeatedly and the number of calls grows exponentially. Memoization or iteration reduces the work to linear time. The depth of recursion is only n, not the cause of the blow-up.

Question 17Algorithms and Problem Solving

A greedy algorithm chooses the activity with the earliest finishing time to schedule the maximum number of non-overlapping activities. Which property justifies its correctness?

  1. Sorting the activities by start time makes the choice optimal
  2. The algorithm tries all possible subsets of activities
  3. The problem has no overlapping subproblems
  4. Every optimal solution contains the earliest-finishing activity, so it is a safe first choice Correct answer.

Explanation

The exchange argument shows that some optimal schedule can always be modified to include the activity that finishes first, without reducing the count. That is the greedy-choice property, and the remaining problem has the same form, giving optimal substructure. Sorting by start time does not yield this guarantee.

Question 18Algorithms and Problem Solving

What is the result of evaluating the postfix expression 5 3 + 8 2 - * ?

  1. 40
  2. 64
  3. 24 Correct answer.
  4. 48

Explanation

A stack evaluation pushes 5 and 3, then + replaces them with 8. Next 8 and 2 are pushed and - gives 6. Finally the two remaining values 8 and 6 are multiplied to give 48.

Question 19Algorithms and Problem Solving

A merge-sort implementation on n elements is analysed by the recurrence T(n) = 2T(n/2) + O(n). What does the master theorem give?

  1. T(n) = O(log n)
  2. T(n) = O(n^2)
  3. T(n) = O(n)
  4. T(n) = O(n log n) Correct answer.

Explanation

The recurrence has two subproblems of half the size and a linear merge cost, which is the balanced case of the master theorem. Each of the log n levels costs O(n), giving O(n log n). A quadratic bound would require the merge step to be linear in n at each of n levels.

Question 20Algorithms and Problem Solving

A program must decide whether a given graph with V vertices and E edges contains a cycle. Using adjacency lists, which approach runs in O(V + E) time?

  1. Depth-first search that reports a back edge Correct answer.
  2. Sorting the vertices by degree
  3. Computing all-pairs shortest paths
  4. Checking every pair of vertices for an edge

Explanation

A depth-first search visits each vertex and each edge once, and a back edge to a vertex still on the recursion stack proves a cycle. The total work is therefore O(V + E) with adjacency lists. All-pairs shortest paths and pairwise checks are far more expensive.

Question 21Algorithms and Problem Solving

A hash function maps keys to m slots, and the table uses open addressing with linear probing. What is the main drawback as the load factor approaches 1?

  1. The table needs a balanced binary tree to store collisions
  2. Clusters of occupied slots grow, so probe sequences become long Correct answer.
  3. The keys are no longer stored in sorted order
  4. The hash function must be recomputed for every comparison

Explanation

Linear probing places a colliding key in the next free slot, so adjacent occupied slots merge into long runs called primary clusters. As the load factor rises, searches must probe through these clusters, and performance degrades sharply. Keeping the load factor low or using a different probing scheme mitigates this.

Question 22Algorithms and Problem Solving

An algorithm processes n items and, for each item, performs a binary search in a sorted array of n elements. What is the overall time complexity?

  1. O(log n)
  2. O(n)
  3. O(n^2)
  4. O(n log n) Correct answer.

Explanation

Each binary search costs O(log n), and the algorithm repeats it n times. Multiplying gives O(n log n). A linear bound would ignore the search cost, and a quadratic bound would assume a linear scan per item.

Question 23Algorithms and Problem Solving

A student claims a certain comparison-based sorting algorithm sorts any n-element array in O(n) time in the worst case. Why is this claim impossible?

  1. Because comparison-based sorting has an Omega(n log n) lower bound on the number of comparisons Correct answer.
  2. Because arrays cannot be sorted faster than they can be copied
  3. Because O(n) algorithms always require extra memory
  4. Because comparisons cannot be performed in constant time

Explanation

The decision-tree argument shows that any comparison-based sort must distinguish n! possible orderings, which needs Omega(n log n) comparisons in the worst case. A linear-time sort is possible only when it uses extra information such as key ranges, as in counting sort. Therefore no comparison-based algorithm can achieve O(n) worst-case time.

Question 24Algorithms and Problem Solving

A dynamic programming solution for the 0/1 knapsack problem uses a table of (n+1) rows and (W+1) columns, where n is the number of items and W is the capacity. What does this imply about the algorithm's complexity?

  1. It is O(n^2) because the table is square
  2. It is exponential in n regardless of W
  3. It is O(n * W), which is pseudo-polynomial because W is a numeric value, not the input length Correct answer.
  4. It is polynomial in n only, independent of W

Explanation

The table has O(n * W) cells, each filled in constant time, so the running time is O(n * W). Because W is encoded in binary in the input, its magnitude can be exponential in the input length, which makes the algorithm pseudo-polynomial rather than truly polynomial. The table is rectangular, not necessarily square.

Question 25Algorithms and Problem Solving

A directed graph is tested for a topological order. Which condition makes such an order exist?

  1. The graph has more edges than vertices
  2. The graph is connected
  3. Every vertex has out-degree at least one
  4. The graph contains no directed cycle Correct answer.

Explanation

A topological order lists vertices so that every directed edge points forward, which is possible exactly when the graph is a DAG. A directed cycle makes such an ordering impossible because the cycle's vertices would each have to precede the next. Connectivity and degree conditions are irrelevant to acyclicity.

Question 26Algorithms and Problem Solving

In the Bagrut algorithms unit, a problem is classified as belonging to class P when which property holds?

  1. A deterministic algorithm solves every instance in polynomial time in the input size Correct answer.
  2. A non-deterministic algorithm verifies a proposed solution in polynomial time
  3. The best known algorithm for the problem runs in exponential time
  4. Every instance can be solved by exhaustive search over all candidate solutions

Explanation

Class P contains decision and search problems for which a deterministic algorithm exists whose running time is bounded by a polynomial in the length of the input. Polynomial verification by a non-deterministic machine defines NP, which is a different (and broader) class. Exhaustive search and exponential-time algorithms describe approaches or upper bounds, not membership in P.

Question 27Algorithms and Problem Solving

A program stores student records in a stack. It pushes record A, then B, then C, then performs one pop and one push of record D. Which record is on top of the stack afterwards?

  1. C
  2. A
  3. B
  4. D Correct answer.

Explanation

A stack removes the most recently pushed element, so the pop removes C and leaves A and B with B on top. Pushing D then places D above B, making D the top element. The last-in-first-out discipline guarantees the newest push is always on top.

Question 28Algorithms and Problem Solving

A binary search tree contains distinct integer keys and is used to answer range queries. Which property must every node satisfy for the search procedure to be correct?

  1. Every key in the left subtree is smaller than the node's key and every key in the right subtree is larger Correct answer.
  2. Every key in the left subtree is smaller than the node's key, and the right subtree may contain any key
  3. Keys are stored in level order so that each level is sorted from left to right
  4. The left and right subtrees have heights that differ by at most one

Explanation

The binary search tree ordering property requires all keys in the left subtree to be less than the node key and all keys in the right subtree to be greater, applied recursively at every node. This global subtree condition is what makes comparisons at each node safely discard an entire subtree. Height balance and level-order sorting are unrelated properties.

Question 29Algorithms and Problem Solving

A recursive procedure visits every node of a binary tree exactly once and performs constant work per node. Which statement about its running time is correct?

  1. It is O(n^2) because each node is compared with every other node
  2. It is O(n log n) because each level of the tree costs n operations
  3. It is O(log n) because recursion halves the problem at each call
  4. It is O(n) because the recursion tree has one call per visited node Correct answer.

Explanation

When each node is visited once and the work per visit is constant, the total work is proportional to the number of nodes, giving O(n). The recursion depth may be up to n in a degenerate tree, but the sum of work over all calls is still linear. Halving arguments apply to divide-and-conquer searches, not to full traversals.

Question 30Algorithms and Problem Solving

A sorting routine is required to be stable. Which pair of input and output demonstrates a stable sort?

  1. Input (5,a),(3,b),(5,c) producing (5,c),(5,a),(3,b)
  2. Input (5,a),(3,b),(5,c) producing (3,b),(5,c),(5,a)
  3. Input (5,a),(3,b),(5,c) producing (5,a),(3,b),(5,c)
  4. Input (5,a),(3,b),(5,c) producing (3,b),(5,a),(5,c) Correct answer.

Explanation

Stability means records with equal keys keep their original relative order. Here the two records with key 5 were originally a before c, and the output preserves a before c while placing the smaller key 3 first. Any output that reverses the equal-key records or fails to sort is not stable.

Question 31Algorithms and Problem Solving

An undirected graph with V vertices and E edges is stored using an adjacency matrix. A program must answer whether two given vertices are adjacent. What is the cost of that query and the space used?

  1. Query O(log V) and space O(V)
  2. Query O(E) and space O(V^2)
  3. Query O(V) and space O(V+E)
  4. Query O(1) and space O(V^2) Correct answer.

Explanation

An adjacency matrix keeps a V-by-V table in which entry (i,j) directly records whether an edge exists, so an adjacency query is a single array access in O(1). The table itself occupies V^2 cells regardless of how many edges exist. Adjacency lists trade this constant-time query for linear space.

Question 32Algorithms and Problem Solving

A directed graph is given for a shortest-path computation with non-negative edge weights. Dijkstra's algorithm is chosen. Which data structure choice gives the best asymptotic bound for sparse graphs with E edges and V vertices?

  1. A stack that pops the most recently inserted vertex
  2. An unsorted array scanned to find the minimum each iteration
  3. A binary min-heap with decrease-key operations Correct answer.
  4. A queue that processes vertices in insertion order

Explanation

With a binary min-heap the extract-min and decrease-key operations cost O(log V), giving a total of O((V+E) log V), which suits sparse graphs. Scanning an unsorted array for the minimum costs O(V) per extraction, yielding O(V^2). A stack or plain queue does not order vertices by tentative distance and breaks correctness.

Question 33Algorithms and Problem Solving

A student writes a recursive function that computes n! and forgets the base case. What is the direct consequence at run time?

  1. The function returns 0 because the multiplication chain starts at zero
  2. The recursion never reaches a stopping condition and the call stack overflows Correct answer.
  3. The function returns 1 for every input
  4. The compiler rejects the program before execution

Explanation

Every recursion needs a base case that terminates the chain of calls. Without it, each call issues another call with a smaller argument forever, and since each frame stays on the stack, the program eventually exhausts stack memory. The failure appears at run time, not at compile time.

Question 34Algorithms and Problem Solving

A hash table uses m slots and resolves collisions by chaining. A well-distributed hash function is assumed. What happens to the average search cost as the load factor grows?

  1. It grows roughly linearly with the load factor because chains get longer Correct answer.
  2. It grows logarithmically because chains are kept sorted
  3. It decreases because more slots become occupied
  4. It stays constant because chaining removes collisions entirely

Explanation

Under chaining the average unsuccessful search examines about the load factor, the ratio of stored keys to slots, and a successful search examines roughly one plus half that value. As the load factor rises, chains lengthen and the average number of comparisons rises proportionally. Chaining does not eliminate collisions, it only stores the colliding keys.

Question 35Algorithms and Problem Solving

A problem requires finding the shortest path in a weighted graph that may contain negative edge weights but no negative cycles. Which algorithm applies?

  1. Depth-first search, because it visits every edge once
  2. Bellman-Ford, which relaxes every edge V-1 times Correct answer.
  3. Dijkstra, because greedy selection always works
  4. Breadth-first search, because it explores by distance layers

Explanation

Bellman-Ford repeatedly relaxes all edges, and after V-1 rounds every shortest path with at most V-1 edges has been found, so negative edges are handled correctly. Dijkstra's greedy finalisation is invalid when a later negative edge could shorten a settled distance. BFS and DFS ignore edge weights entirely.

Question 36Algorithms and Problem Solving

Two algorithms solve the same problem: algorithm X runs in O(n log n) and algorithm Y runs in O(n^2). For very large n, which conclusion is justified?

  1. Both have the same growth rate because both are polynomials
  2. No comparison is possible without measuring exact running times
  3. X will eventually be faster, although constants may make Y faster for small n Correct answer.
  4. Y will always be faster because quadratic growth is simpler to implement

Explanation

Big-O compares growth rates, and n log n grows more slowly than n^2, so beyond some threshold X performs fewer operations. Asymptotic bounds hide constant factors, so for small inputs Y may still win in practice. The comparison is about eventual behaviour, not about implementation simplicity.

Question 37Algorithms and Problem Solving

A dynamic programming solution is designed for a problem that exhibits optimal substructure and overlapping subproblems. Which pair of features distinguishes it from a plain divide-and-conquer solution?

  1. It explores all possible solutions and returns the first valid one
  2. It stores subproblem results in a table and reuses them instead of recomputing Correct answer.
  3. It guarantees a better asymptotic bound than any greedy algorithm
  4. It always uses recursion and never uses iteration

Explanation

Dynamic programming exploits overlapping subproblems by memoising or tabulating results so each distinct subproblem is solved once. Divide-and-conquer also relies on optimal substructure but assumes subproblems are independent and does not share results. The defining feature is reuse of stored answers, not recursion style or comparison with greedy methods.

Question 38Algorithms and Problem Solving

A programmer must choose a data structure for a text editor supporting insert, delete and search by exact word in a large dictionary. Which structure gives expected O(1) search with reasonable memory?

  1. A singly linked list traversed from the head
  2. A hash table with a good hash function Correct answer.
  3. A min-heap ordered by word length
  4. A sorted array with binary search

Explanation

A hash table maps each word to a slot through a hash function, giving expected constant-time lookup when the load factor is controlled. A sorted array gives O(log n) search but costly insertions and deletions, and a linked list requires linear scanning. A heap ordered by length does not support exact-word search.

Question 39Algorithms and Problem Solving

A program must determine whether a large integer n is prime using trial division up to the square root of n. Which statement about this approach is correct?

  1. It runs in polynomial time in the number of bits of n
  2. It is correct because any composite n has a factor not exceeding its square root Correct answer.
  3. It fails for even values of n and must skip them
  4. It is incorrect because factors larger than the square root may exist

Explanation

If n equals a times b with both factors greater than the square root, their product would exceed n, so at least one factor must be at most the square root. Testing divisors only up to that bound is therefore sufficient. The method is correct but exponential in the number of bits, since the square root is about 2^(b/2) for b bits.

Question 40Algorithms and Problem Solving

An algorithm solves a problem by trying all subsets of n items and, for each subset, checking feasibility in O(n) time. A student claims this gives a polynomial algorithm. Which evaluation is correct?

  1. The claim is wrong: there are 2^n subsets, so the total is O(n * 2^n), which is exponential Correct answer.
  2. The claim is right: the factor n makes the bound polynomial
  3. The claim is wrong: the total is O(n^2) because each check is linear
  4. The claim is right: checking feasibility reduces the subset count

Explanation

Enumerating all subsets produces 2^n candidates, and spending O(n) on each yields O(n * 2^n), which grows exponentially in n. A polynomial factor multiplying an exponential term does not make the algorithm polynomial. The feasibility check neither reduces the number of subsets nor changes the exponential growth.

Question 41Programming in a High-Level Language (Java/C#)

In Java, which declaration creates a two-dimensional array of int with 3 rows and 4 columns, all elements initialized to zero?

  1. int[][] grid = new int[3,4];
  2. int[][] grid = new int[3][4]; Correct answer.
  3. int[][] grid = new int[4][3];
  4. int grid[3][4] = new int();

Explanation

In Java the first bracket pair gives the number of rows and the second gives the number of columns, so new int[3][4] allocates 3 rows of 4 columns each, and numeric elements default to 0. The comma-separated form and the C-style declaration are not valid Java syntax.

Question 42Programming in a High-Level Language (Java/C#)

What does the expression 17 % 5 evaluate to in Java?

  1. 12
  2. 2 Correct answer.
  3. 3.4
  4. 3

Explanation

The % operator returns the remainder of integer division. Since 17 divided by 5 is 3 with remainder 2, the result is 2. Both operands are int, so the result is also int, not a decimal.

Question 43Programming in a High-Level Language (Java/C#)

Given int i = 0; while (i < 5) { System.out.print(i); i++; }, what is printed?

  1. 01234 Correct answer.
  2. 1234
  3. 12345
  4. 012345

Explanation

The loop body prints the current value and then increments i. The condition i < 5 stops the loop once i reaches 5, so the printed values are 0 through 4 with no separator.

Question 44Programming in a High-Level Language (Java/C#)

Which statement about a static method in Java is correct?

  1. It can be overridden polymorphically like an instance method.
  2. It must be declared abstract in an interface.
  3. It can access instance fields directly without an object reference.
  4. It can be called through the class name without creating an instance. Correct answer.

Explanation

A static method belongs to the class rather than to any object, so it is invoked using the class name. It has no implicit this reference, cannot touch instance fields directly, and is hidden rather than overridden.

Question 45Programming in a High-Level Language (Java/C#)

What is the value of the String expression "Bagrut".substring(2, 5)?

  1. "gru"
  2. "agr"
  3. "gr"
  4. "agru" Correct answer.

Explanation

substring(begin, end) returns characters from index begin up to but not including index end. Indices 2, 3 and 4 of "Bagrut" are 'a', 'g' and 'r', giving "agr".

Question 46Programming in a High-Level Language (Java/C#)

In C#, which access modifier restricts a class member to the declaring class and to classes derived from it?

  1. protected Correct answer.
  2. internal
  3. private
  4. public

Explanation

The protected modifier allows access from the declaring class and from derived classes. Internal limits access to the same assembly, private to the declaring type, and public to everyone.

Question 47Programming in a High-Level Language (Java/C#)

Given int[] a = {4, 8, 15, 16}; what is the value of a[a.length - 1]?

  1. 16 Correct answer.
  2. 4
  3. 15
  4. an ArrayIndexOutOfBoundsException

Explanation

Array indices in Java start at 0 and end at length - 1. Here length is 4, so a.length - 1 is 3 and a[3] holds the last element, 16.

Question 48Programming in a High-Level Language (Java/C#)

Which loop is most appropriate when the number of iterations is unknown in advance and the body must execute at least once?

  1. a for loop with a fixed counter
  2. an enhanced for loop over an array
  3. a while loop whose condition is tested first
  4. a do-while loop Correct answer.

Explanation

A do-while loop tests its condition after executing the body, so the body always runs at least once regardless of the condition. It also suits situations where the termination condition is only known after processing.

Question 49Programming in a High-Level Language (Java/C#)

What is printed by: int x = 7; int y = 2; System.out.println(x / y + " " + (double) x / y);

  1. 3.5 3
  2. 3 3
  3. 3.5 3.5
  4. 3 3.5 Correct answer.

Explanation

Integer division of 7 by 2 truncates toward zero and yields 3. The cast to double makes the second division floating-point, producing 3.5, and string concatenation joins the two results with a space.

Question 50Programming in a High-Level Language (Java/C#)

Which statement correctly compares two String objects s1 and s2 by their character content in Java?

  1. if (s1 == s2)
  2. if (s1.equals(s2)) Correct answer.
  3. if (s1.compare(s2) == 0)
  4. if (s1.hashCode() == s2.hashCode())

Explanation

The equals method compares the character sequences of two strings. The == operator compares references, and hashCode equality does not guarantee content equality because collisions are possible.