Loops
Q1.
Consider the C program fragment below which is meant to divide x by y using repeated subtractions. The variables x, y, q and r are all unsigned int. while (r >= y) { r = r - y; q = q +1; } Which of the following conditions on the variables x, y, q and r before the execution of the fragment will ensure that the loop terminates in a state satisfying the condition x==(y*q+r)?Q2.
Consider the following C program main() { int x, y, m, n; scanf ("%d %d", &x, &y); /* Assume x > 0 and y > 0 */ m = x; n = y; while (m! = n) { if (m > n) m = m - n; else n = n - m; } print f ("% d", n); } The program computesQ3.
Consider the following pseudo code, where x and y are positive integers. begin q := 0 r := x while r \geq y do begin r := r - y q := q + 1 end end The post condition that needs to be satisfied after the program terminates isQ4.
Consider the following segment of C-code: int j, n; j = 1; while (j <=n) j=j*2; The number of comparisons made in the execution of the loop for any n \gt 0 is:Q5.
Consider the following C function in which size is the number of elements in the array E: int MyX(int *E, unsigned int size) { int Y = 0; int Z; int i, j, k; for(i = 0; i < size; i++) Y = Y + E[i]; for(i = 0; i < size; i++) for(j = i; j < size; j++) { Z = 0; for(k = i; k <= j; k++) Z= Z + E[k]; if (Z > Y) Y = Z; } return Y; } The value returned by the function MyX is theQ6.
Consider the following program fragment for reversing the digits in a given integer to obtain a new integer. Let n=d_{1}d_{2}...d_{m}. int n, rev; rev = 0; while (n > 0) { rev = rev*10 + n%10; n = n/10; } The loop invariant condition at the end of the i^{th} iteration is:Q7.
Consider the following pseudo code. What is the total number of multiplications to be performed? D= 2 for i = 1 to n do for j = i to n do for k = j + 1 to n do D = D * 3Q8.
Consider the following C function. float f(float x, int y) { float p, s; int i; for (s=1, p=1, i=1; i < y; i ++) { p*= x/i; s+=p; } return s; } For large values of y, the return value of the function f best approximatesQ9.
The following function computes the maximum value contained in an integer array p[] of size n (n>=1). int max(int*p, int n){ int a=0,b=n-1; while (__________){ if (p[a]<=p[b]){a=a+1;} else {b=b-1;} } return p[a]; } The missing loop condition isQ10.
The following function computes X^{Y} for positive integers X and Y. int exp(int X,int Y){ int res=1, a=X, b=Y; while (b!=0){ if(b%2==0){a=a*a; b=b/2;} else {res=res*a; b=b-1;} } return res; } Which one of the following conditions is TRUE before every iteration of the loop?