LABORATORY 04

Operators and Expressions

Duration: 2 hours Language: C / C++ Previous: Laboratory 3 PDF handout RO versiunea română

Operators applied to operands form expressions. C/C++ has one of the richest collections of operators among programming languages - which gives expressive power, but makes precedence rules and implicit conversions matter enormously.

1Lab objectives

a + b * c > d>+da*bcevaluated lastevaluated first
Fig. - The evaluation tree of the expression. Precedence decides the shape of the tree: multiplication binds tighter than addition, and comparison more loosely than both - so it applies last.
  • Classifying operators by number of operands and by kind of operation
  • Correctly using integer division and the modulo operator
  • Telling logical operators apart from bitwise ones
  • Applying precedence and associativity rules
  • Understanding the difference between pre-increment and post-increment
  • Controlling implicit and explicit type conversions

2Classifying operators

Operators can be grouped by number of operands:

CategorySyntaxExample
Unaryoperator operand-x, !ok, ~mask, ++i
Binaryop1 operator op2a + b, x < y, m & n
Ternaryop1 ? op2 : op3(a > b) ? a : b
Operators with a double meaningThe symbols +, -, *, and & are defined both as unary and as binary operators. The interpretation is decided implicitly by the number of operands: *p is dereferencing, while a * b is multiplication.

Operators specific to C++, which do not exist in C: new, delete, the scope operator ::, the pointer-to-member .*, and its equivalent form ->*.

3Arithmetic operators

OperatorOperationExampleResult
+addition7 + 29
-subtraction7 - 25
*multiplication7 * 214
/division7 / 23 (integer!)
/real division7.0 / 23.5
%remainder (modulo)7 % 21
++incrementi++i increases by 1
--decrementi--i decreases by 1
Integer divisionIf both operands are integers, the result is an integer, and the fractional part is lost. int average = sum / n; truncates. For a real result, at least one operand must be real: (float)sum / n.
The % operatorApplies only to integer operands. 7.5 % 2 is a compile error. It is useful for: testing parity (n % 2 == 0), extracting digits (n % 10), and cyclically limiting an index (i % size).

4Relational and logical operators

OperatorMeaningExampleResult
==equal to3 == 31 (true)
!=not equal to3 != 30 (false)
< > <= >=comparisons2 <= 51
&&logical AND(a>0) && (b>0)1 if both
||logical OR(a>0) || (b>0)1 if at least one
!logical NOT!01
Confusing = with ==if (x = 5) assigns 5 to x, and the result is 5, which is true - the condition is always satisfied. The correct form is if (x == 5). The compiler accepts both, so the mistake is not flagged.
Short-circuit evaluationWith &&, if the first operand is false, the second is not evaluated. With ||, if the first is true, the second is skipped. This is used for protection: if (p != NULL && *p > 0) - the dereference only happens if the pointer is valid.

5Bitwise operators

OperatorNameEffect on each bitTypical use
&bitwise AND1 only if both bits are 1testing / masking bits
|bitwise OR1 if at least one bit is 1setting bits
^exclusive OR1 if the bits differtoggling bits
~negationinverts every bitbuilding masks
<<left shiftmoves bits to the leftfast multiplication by 2ⁿ
>>right shiftmoves bits to the rightfast division by 2ⁿ
& is not &&1 & 2 gives 0 (the bits do not overlap), but 1 && 2 gives 1 (both values are nonzero, so both are true). Confusing the two produces logic errors that are very hard to find.

6Bit playground

Toggle the bits directly on the binary representation and watch how the result forms, position by position. Try << and >> in particular, to see the equivalence with multiplying and dividing by powers of 2.

Bitwise operators - interactive binary representation

7Precedence and associativity

LevelOperatorsAssociativity
1 (highest)() [] -> .left → right
2! ~ ++ -- unary +/-, * & sizeof (cast)right → left
3* / %left → right
4+ -left → right
5<< >>left → right
6< <= > >=left → right
7== !=left → right
8&left → right
9^left → right
10|left → right
11&&left → right
12||left → right
13?:right → left
14 (lowest)= += -= *= /= %=right → left
Practical consequenceBitwise operators have lower precedence than relational ones. The expression x & 1 == 0 evaluates as x & (1 == 0), i.e. x & 0, which is always 0. Correct: (x & 1) == 0. When in doubt, use parentheses - they cost nothing at run time.

8Simulator: pre-increment vs. post-increment

The difference between ++i and i++ only shows up when the expression's result is used. Watch step by step what value the variable has and what value the expression has.

How ++i and i++ are evaluated
Undefined behaviorExpressions of the form i = i++ + ++i; have no result guaranteed by the standard - different compilers produce different values. Never modify the same variable twice within the same expression.

9Type conversions

When the operands have different types, the compiler automatically converts toward the "larger" type:

the implicit conversion hierarchy
char / short  ->  int  ->  unsigned int  ->  long  ->  float  ->  double
ExpressionResult typeValue
7 / 2int3
7 / 2.0double3.5
(float)7 / 2float3.5
(float)(7 / 2)float3.0 - the conversion happens too late
'A' + 1int66
Comparing signed and unsigned int i = -1; unsigned u = 1; if (i < u) is false! The value −1 is converted to unsigned and becomes 4,294,967,295, which is greater than 1. Avoid mixing the two types in comparisons.

10Source code

division.c - integer vs. real
#include <stdio.h>

int main(void)
{
    int a = 7, b = 2;

    printf("a / b       = %d\n",   a / b);            // 3  - truncated
    printf("a %% b       = %d\n",   a % b);            // 1  - the remainder
    printf("(float)a/b  = %.3f\n", (float)a / b);     // 3.500 - correct
    printf("(float)(a/b)= %.3f\n", (float)(a / b));   // 3.000 - too late!

    // extracting the digits of a four-digit number
    int n = 4739;
    printf("\nDigits of %d, from the right: ", n);
    printf("%d ", n % 10);          // the last digit
    printf("%d ", n / 10 % 10);     // drop the last digit, then take the last one again
    printf("%d ", n / 100 % 10);
    printf("%d\n", n / 1000);       // the first digit
    // a number with any number of digits needs a loop (Lab 6)
    return 0;
}
bits.c - classic mask techniques
#include <stdio.h>

int main(void)
{
    unsigned char reg = 0x0A;         // 0000 1010 = 10 decimal

    printf("initial:         0x%02X\n", reg);

    reg |=  (1 << 4);                 // SET bit 4     -> 0001 1010
    printf("after set b4:    0x%02X\n", reg);

    reg &= ~(1 << 1);                 // CLEAR bit 1   -> 0001 1000
    printf("after clear b1:  0x%02X\n", reg);

    reg ^=  (1 << 0);                 // TOGGLE bit 0  -> 0001 1001
    printf("after toggle b0: 0x%02X\n", reg);

    // TEST a bit: the result is 1 if the bit is set and 0 otherwise
    printf("bit 4 = %d\n", (reg >> 4) & 1);

    // fast multiplication and division
    int x = 12;
    printf("\n%d << 2 = %d  (that is %d * 4)\n", x, x << 2, x);
    printf("%d >> 2 = %d  (that is %d / 4)\n",   x, x >> 2, x);

    return 0;
}
ternary.c - the conditional operator
#include <stdio.h>

int main(void)
{
    int a = 17, b = 42;

    int maximum = (a > b) ? a : b;          // equivalent to an if-else
    printf("The maximum is %d\n", maximum);

    // these can be chained, but readability drops quickly
    int n = 0;
    printf("The number is %s\n",
           (n > 0) ? "positive" : (n < 0) ? "negative" : "zero");

    // watch the precedence: the parentheses are NOT optional here
    printf("Sum: %d\n", a + ((a > b) ? a : b));

    return 0;
}

11Code workshop

Operators have precedence rules and side effects that are hard to remember from text alone. Run these and, especially, use Step by step to see exactly when each variable changes.

Prefix and postfix increment
#include <stdio.h>

int main(void)
{
    int a = 5, b;

    b = a++;                  /* assigns first, then increments */
    printf("after b = a++ :  a = %d, b = %d\n", a, b);

    a = 5;
    b = ++a;                  /* increments first, then assigns */
    printf("after b = ++a :  a = %d, b = %d\n", a, b);

    int x = 10;
    printf("\nx / 3   = %d   (integer division)\n", x / 3);
    printf("x %% 3   = %d   (the remainder)\n", x % 3);
    printf("x / 3.0 = %.4f (one real operand -> real result)\n", x / 3.0);
    return 0;
}
Bitwise operators - exercise
#include <stdio.h>

int main(void)
{
    unsigned char a = 0x2C;   /* 0010 1100 */

    printf("a        = 0x%02X\n", a);
    printf("a | 0x03 = 0x%02X\n", a | 0x03);
    printf("a & 0x0F = 0x%02X\n", a & 0x0F);

    /* Complete this: set bit 7 of a, then clear bit 2.
       Hints: to set, use   |= (1 << 7)
              to clear, use &= ~(1 << 2)
       The "bit lab" above shows the bits of any of these values. */

    printf("result   = 0x%02X\n", a);
    return 0;
}

12Exercises with automatic checking

This is where you write the code. The ✓ Check button runs your program on several data sets and shows you right away where the result differs. At the end you submit the track you chose, and the instructor grades it automatically.

Every exercise has the program already started, and the comments tell you what is left to add. Write the code, press ✓ Check and read what each failed test says. If you get stuck, open the hints one at a time. You may also print messages for the user (such as Enter n:); the test looks at what you print at the end.

P1

The average of three grades

Read three integer grades and print their average with two decimals.

input7 8 10
output8.33
#include <stdio.h>

int main(void)
{
    int a, b, c;
    double avg;
    scanf("%d %d %d", &a, &b, &c);

    /* Trap: (a + b + c) / 3 is a division between integers and loses the decimals,
       even if the result goes into a double. Make the division a real one. */

    printf("%.2f\n", avg);
    return 0;
}
P2

The last digit

Read a natural number n (at least 10). On one line print its last digit and the number left after you cut it off. Example: for 1237 print 7 123.

input1237
output7 123
#include <stdio.h>

int main(void)
{
    int n;
    scanf("%d", &n);

    /* The remainder of dividing by 10 (n % 10) is the last digit.
       The quotient of integer division by 10 (n / 10) is the number without it. */

    return 0;
}
P3

Even or odd with the ternary operator

Read an integer n and print even or odd without if: use the conditional operator ? :.

input4
outputeven
#include <stdio.h>

int main(void)
{
    int n;
    scanf("%d", &n);

    /* condition ? value_if_true : value_if_false
       The values can even be strings: printf("%s\n", ... ? "even" : "odd"); */

    return 0;
}
P4

The bit at position k

Read a non-negative integer n and a position k (0 ≤ k ≤ 30). Print bit k of n (0 or 1). Position 0 is the least significant bit.

input6 0
output0
#include <stdio.h>

int main(void)
{
    int n, k;
    scanf("%d %d", &n, &k);

    /* Move the wanted bit to position 0 with n >> k,
       then keep only that bit with & 1. */

    return 0;
}
P5

A number in a range

Read three integers x a b (with a ≤ b). Print 1 if x lies in the closed interval [a, b] and 0 otherwise.

input5 1 10
output1
#include <stdio.h>

int main(void)
{
    int x, a, b;
    scanf("%d %d %d", &x, &a, &b);

    /* Trap: a <= x <= b does NOT do what it seems in C. First a <= x is
       computed (0 or 1), and only then that result is compared with b.
       Write two comparisons joined with &&. */

    return 0;
}

Problems start from an empty main. The output format must be followed exactly (spaces and newlines do not matter unless the statement says otherwise), so do not print prompts. The visible tests cover only the simple cases; grading also runs hidden tests chosen to catch the edge cases.

A1

Printing a byte in binary

Read an integer n (0 ≤ n ≤ 255) and print it in binary using exactly 8 digits, with shifts and masks only (loops come in Lab 6).

input5
output00000101
#include <stdio.h>

int main(void)
{
    /* write your solution here */

    return 0;
}
A2

The four bit operations

Read an unsigned integer n (32 bits) and a position k (0 ≤ k ≤ 31). On one line print: n with bit k set (1), n with bit k cleared (0), n with bit k toggled, and the value of bit k.

input10 0
output11 10 11 0
#include <stdio.h>

int main(void)
{
    /* write your solution here */

    return 0;
}
A3

Swapping the halves of a byte

A byte has two halves of 4 bits each (nibbles). Read an integer n (0 ≤ n ≤ 255) and print the byte obtained by swapping the two halves, in decimal and in two-digit upper-case hexadecimal. Example: 0xA5 (165) becomes 0x5A, so print 90 5A.

input165
output90 5A
#include <stdio.h>

int main(void)
{
    /* write your solution here */

    return 0;
}
A4

Power of two

Read an unsigned integer n (32 bits). Print yes if n is a power of two and no otherwise, using a single bitwise expression (no loops).

input64
outputyes
#include <stdio.h>

int main(void)
{
    /* write your solution here */

    return 0;
}

13Work tasks

  • Compute the arithmetic mean of three integers, obtaining a correct real result.
  • Write a program that extracts and prints the digits of a number, using % and /.
  • Implement the function that prints a byte in binary and test it for the values 0, 1, 128, and 255.
  • Apply the four classic bit operations (set, clear, toggle, test) to a variable.
  • Verify experimentally that x & 1 == 0 gives a different result from (x & 1) == 0.
  • Test the difference between ++i and i++ inside a printf.
  • Compare a negative int with a positive unsigned and explain the result.
  • Rewrite a simple if-else structure using the ternary operator.

14Extended application

ExtensionWrite a program that, using only bitwise operators (no if, no multiplication or division), determines: whether a number is even, whether it is a power of 2, how many 1 bits it contains, and the position of its highest set bit. Hint for the power of 2: n & (n - 1) is 0 only in that case.

15Review questions

16Resources