In C, pointer multiplication and pointer division are not allowed.
Here,
j = j * 2;
and
k = k / 2;
are invalid operations.
Consider the following pseudo-code fragment in which an invariant for the loop is $m \times x^k=p^n$ and $k\ge 0$.
Pre-conditions: $p\ge 1$ and $n\ge 0$
Assume that overflow never occurs.
int x = p;
int k = n;
int m = 1;
while (k != 0) {
if (k is odd) then m = m * x;
x = x * x;
k = floor(k / 2);
}
Which of the following must be true at the end of the while loop?
Given loop invariant is
$m \times x^k=p^n$
At the end of the while loop, condition becomes false.
So,
$k=0$
Putting $k=0$ in invariant,
$m \times x^0=p^n$
Since,
$x^0=1$
Therefore,
$m=p^n$
Consider the following C-code fragment running on a $32$-bit x86 machine:
typedef struct {
union {
unsigned char a;
unsigned short b;
} U;
unsigned char c;
} S;
S B[10];
S *p = address of B[4];
S *q = address of B[5];
p->U.b = 0x1234;
If $M$ is the value of $q-p$ and $N$ is the value of address of $(p->c)$ minus address of $p$, then $(M,N)$ is:
Given that structure $S$ takes $32$ bits.
So,
$32\text{ bits}=4\text{ bytes}$
Now,
$p$ points to $B[4]$
$q$ points to $B[5]$
Since $p$ and $q$ are pointers of type $S$, pointer subtraction gives the difference in number of structures.
So,
$q-p=1$
Therefore,
$M=1$
Now, union $U$ contains $unsigned\ char\ a$ and $unsigned\ short\ b$.
Size of union $U$ is $2$ bytes.
After union $U$, variable $c$ is stored.
So, offset of $c$ from the beginning of structure is $2$ bytes.
Therefore,
$N=2$
Hence,
$(M,N)=(1,2)$
Consider the following C++ function $f()$:
unsigned int f(unsigned int n) {
unsigned int b = 0;
while (n) {
b = b + (n bitwise AND 1);
n = n shifted right by 1;
}
return b;
}
The function $f()$ returns the integer that represents the $P$ in the binary representation of positive integer $n$, where $P$ is:
The expression $n$ bitwise AND $1$ checks the last bit of $n$.
If the last bit is $1$, then $b$ increases by $1$.
After that, $n$ is shifted right by one bit.
So, the loop checks each bit of $n$ one by one.
Therefore, $b$ counts the total number of $1$'s in the binary representation of $n$.
p is a pointer variable and must store the address of x, written as:
p = &x;
But the program assigns:
p = x;
which means an integer is assigned to a pointer, causing a compilation error (type mismatch).
Outer loop runs for:
$i=0,1,2,3,4$
Inner loop runs only when $j<i$.
But inside inner loop, there is a $break$ statement, so inner loop executes only one time for each valid value of $i$.
For $i=0$:
$j<0$ is false, so inner loop does not execute.
For $i=1$:
$x=x+(1+0-1)=0+0=0$
For $i=2$:
$x=x+(2+0-1)=0+1=1$
For $i=3$:
$x=x+(3+0-1)=1+2=3$
For $i=4$:
$x=x+(4+0-1)=3+3=6$
So, final value of $x$ is:
$x=6$
Online Test Series, Information About Examination,
Syllabus, Notification
and More.
Online Test Series, Information About Examination,
Syllabus, Notification
and More.