0
0
Cprogramming~20 mins

Left shift and right shift in C - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Shift Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of left shift operation
What is the output of this C code snippet?
C
int main() {
    unsigned int x = 5; // binary: 0000 0101
    unsigned int y = x << 2;
    printf("%u", y);
    return 0;
}
A40
B10
C5
D20
Attempts:
2 left
💡 Hint
Left shift by 2 moves bits two places to the left, multiplying by 4.
Predict Output
intermediate
2:00remaining
Output of right shift operation
What is the output of this C code snippet?
C
int main() {
    unsigned int x = 32; // binary: 0010 0000
    unsigned int y = x >> 3;
    printf("%u", y);
    return 0;
}
A4
B8
C16
D64
Attempts:
2 left
💡 Hint
Right shift by 3 moves bits three places to the right, dividing by 8.
🧠 Conceptual
advanced
2:30remaining
Effect of left shift on signed integers
Consider the following code. What is the output and why?
C
int main() {
    int x = 1073741824; // 2^30
    int y = x << 2;
    printf("%d", y);
    return 0;
}
A-1073741824
B1073741824
C0
D4294967296
Attempts:
2 left
💡 Hint
Left shift by 2 shifts bit 30 to bit 32, which is discarded in 32-bit int.
🔧 Debug
advanced
2:30remaining
Identify the error in right shift usage
What error will this code produce when compiled and run?
C
int main() {
    int x = -16;
    unsigned int y = x >> 2;
    printf("%u", y);
    return 0;
}
APrints -4
BCompilation error due to mixing signed and unsigned types
CPrints a large positive number due to sign extension and conversion
DRuntime error: undefined behavior
Attempts:
2 left
💡 Hint
Right shifting a negative signed int keeps the sign bit, then converting to unsigned prints a large number.
🚀 Application
expert
3:00remaining
Calculate the number of bits set after shifts
Given the code below, what is the number of bits set to 1 in variable z after execution?
C
int main() {
    unsigned int x = 0b1011; // decimal 11
    unsigned int y = x << 3;  // shift left by 3
    unsigned int z = y >> 2;  // shift right by 2
    int count = 0;
    for (int i = 0; i < 32; i++) {
        if ((z & (1 << i)) != 0) count++;
    }
    printf("%d", count);
    return 0;
}
A2
B3
C4
D1
Attempts:
2 left
💡 Hint
Track the bits step by step after each shift.