in Programming and DS recategorized
1,784 views
4 votes
4 votes

Consider the following C language code:

#include<stdio.h>
int main() {
    int x=64;
    int i=0;
    while (i++<3)
        x=(((x<<2)+(x>>1))>>1);
    printf("%d", x);
    return 0;
}


What is the output of the above code?

in Programming and DS recategorized
1.8k views

4 Comments

welcome @Magma

0
0

@akash.dinkar12

In left shift, we add 0 , at right end

and in right shift, do we not add 1 in left end? or we add 0 at left end?

0
0
729
0
0

1 Answer

7 votes
7 votes
replace x as $x=\frac{(x \times 2^2)+(\frac{x}{2})}{2}$ (Only if when X is even)

When X is odd right shifting makes division but with some loss of precision.So, in case of Odd data do bitwise calculation only.

and code would work same.
edited by

4 Comments

@Ayush Upadhyaya

in ...  x = ( (x<<2) + (x>>1) ) >>1 ;

how it will figure that x<<2 should be executed first or x>>1 first

If x<<2 executed first then x>>1 will use updated value of x ??

correct me if wrong sir,

0
0

@jatin khachane 1-Actually I also had the same doubt.But right shift and left shift operators don't change the variable value untill it is reassigned to it.

Like x++ changes the variable value.

But if only you do x>>2 or x<<1, then untill this is assigned back to x, x won't change.

x<<2; //x won't change.

x=x<<2; //now x would change.

2
2
ok that means x<<2 + x>>1 here x<<2 will be a temp result not assigned back to x yet

but in x++ + x++ , first x++ may assign x as x+1 and second x++ may use it or may not both may use intital x ?
1
1
Answer:

Related questions