โž• 6. Operators

๐ŸŽ“ Learn Operators Step by Step

An operator tells C what to do with a value. For example, + adds two numbers and > compares them. Other operators store values, combine conditions, or work with individual bits. For each operator, learn what values it needs and what result it gives.

6.1 What Is an Operator?

Consider this statement:

int total = 10 + 20;

Here 10 and 20 are the operands, and + is the operator. The operator tells C to add the two operands. The result, 30, is then stored in total.

Think of an operator like an instruction.

A calculator button such as + tells the calculator what to do. In C, operators play the same role inside expressions. For example, a + b means โ€œtake the values of a and b and perform addition.โ€

Term Meaning Example
Operator Symbol or form that performs an operation +, ==, &&
Operand Value or expression operated on In a + 5, a and 5
Expression A combination of operands and operators that produces a value or effect a + b * 2
Result The value produced by evaluating an expression 10 + 20 produces 30

6.2 Why Are Operators Important?

A C program cannot do useful work with variables alone. Operators allow a program to calculate, compare, decide, repeat, update, and manipulate data. For example:

int marks = 75;
int pass = marks > = 40;

int salary = 30000;
salary += 5000;

int age = 22;
if (age > = 18 && age < = 60)
    printf("Eligible");

In these examples, one expression compares marks, another increases salary, and another combines two conditions. The operator determines the action in each case.

What the program needs to do Typical operators
Calculate a value + - * / %
Compare two values < < = > > = == ! =
Combine conditions && || !
Store or update a value = += -= *= /= %=
Increase or decrease a value ++ --
Work with individual bits & | ^ ~ << >>
Choose one of two values ? :

6.3 Operators Based on Number of Operands

One useful way to understand operators is to count how many operands they work with. This is called their arity.

Type Number of operands Example Meaning
Unary One -x Negate one value
Binary Two a + b Operate on two values
Ternary / conditional Three operands age > = 18 ? 1 : 0 Choose between two expressions based on a condition
Important:

The same symbol can have different meanings depending on how it is used. For example, - can mean subtraction in a - b, but it can mean unary negation in -a. Similarly, * can mean multiplication in a * b and is also used with pointers in expressions such as *ptr.

6.4 Arithmetic Operators

Arithmetic operators perform numerical calculations. The five basic arithmetic operators are:

Operator Name Example Result
+ Addition 10 + 3 13
- Subtraction 10 - 3 7
* Multiplication 10 * 3 30
/ Division 10 / 3 3 for integer operands
% Remainder 10 % 3 1

Simple Example

#include <stdio.h>

int main(void)
{
    int a = 20;
    int b = 6;

    printf("Addition       = %d\n", a + b);
    printf("Subtraction    = %d\n", a - b);
    printf("Multiplication = %d\n", a * b);
    printf("Division       = %d\n", a / b);
    printf("Remainder      = %d\n", a % b);

    return 0;
}

Output:

Addition       = 26
Subtraction    = 14
Multiplication = 120
Division       = 3
Remainder      = 2

How Does / Work With Integers?

When both operands are integers, / gives an integer quotient. C discards the fractional part; it does not round to the nearest integer. For example, 7 / 2 gives 3 and -7 / 2 gives -3.

printf("%d\n", 7 / 2);     /* 3 */
printf("%.1f\n", 7.0 / 2); /* 3.5 */

In the first expression both operands are integers, so the result is an integer. In the second expression, 7.0 is a floating-point value, so floating- point division is performed.

What Does % Really Mean?

The remainder operator gives what is left after integer division. For example, 17 % 10 gives 7, the last digit of 17. It is also useful for checking whether a number is even or odd.

int n = 27;

printf("%d\n", n % 10); /* last digit = 7 */
printf("%d\n", n % 2);  /* 1 means odd */
Common mistake:

Do not use % with floating-point operands. The C remainder operator is for integer arithmetic. For floating-point remainder, the standard library provides functions such as fmod().

6.5 Relational Operators โ€” Comparing Values

Relational operators ask a question such as โ€œIs a greater than b?โ€ The result of a comparison in C is an int value: 1 for true and 0 for false.

Operator Question Example
< Is left value less than right value? a < b
< = Is left value less than or equal to right value? a < = b
> Is left value greater than right value? a > b
> = Is left value greater than or equal to right value? a > = b
== Are the two values equal? a == b
! = Are the two values different? a ! = b
int age = 20;

printf("%d\n", age > = 18); /* 1 */
printf("%d\n", age < 18);  /* 0 */
Very important: = is not ==.

= means assignment. It stores a value. == means equality comparison. It asks whether two values are equal.

int x = 10;       /* assignment */

if (x == 10)      /* comparison */
{
    printf("x is 10");
}

6.6 Logical Operators โ€” Combining Conditions

Logical operators are mainly used when a program has more than one condition. C treats 0 as false and any nonzero value as true when a scalar value is used as a condition.

Operator Name Meaning
&& Logical AND True only when both conditions are true
|| Logical OR True when at least one condition is true
! Logical NOT Reverses the truth value

Logical AND &&

int age = 25;

if (age > = 18 && age < = 60)
{
    printf("Age is in the required range");
}

Both conditions must be true:

age > = 18     โ†’ true
age < = 60     โ†’ true
                  โ†“
             true && true
                  โ†“
                true

Logical OR ||

int day = 6;

if (day == 6 || day == 7)
{
    printf("Weekend");
}

Only one condition needs to be true for the complete OR expression to be true.

Logical NOT !

int loggedIn = 0;

if (!loggedIn)
{
    printf("Please log in");
}

Because loggedIn is zero, it represents false. Applying ! changes false to true.

6.7 Truth Table for Logical Operators

A B A && B A || B
0000
0101
1001
1111

For NOT:

A !A
01
10

6.8 Short-Circuit Evaluation

Short-circuit evaluation is one of the most useful behaviors of logical operators. With &&, C evaluates the right side only when the left side is true. With ||, C evaluates the right side only when the left side is false.

if (x != 0 && 100 / x > 5)
{
    printf("Condition satisfied");
}

Suppose x is 0. The first condition x ! = 0 is false. Therefore C does not evaluate 100 / x. This prevents a division-by-zero operation.

Remember:

These rules are guaranteed by C. Place the safety check on the left and the operation that depends on it on the right. For example, check that a divisor is nonzero before dividing by it.

6.9 Assignment Operator =

The assignment operator stores a value in a modifiable object.

int marks;

marks = 85;

Think of the statement as:

marks
  โ†‘
85 is stored here

For a simple assignment to a variable, C calculates the right-hand value, converts it to the variableโ€™s type if necessary, and stores it. The previous value of the variable is replaced.

int x;

x = 10 + 5;

printf("%d", x); /* 15 */

Assignment is different from comparison:

x = 5;   /* put 5 into x */
x == 5;   /* ask whether x is equal to 5 */

6.10 Compound Assignment Operators

A compound assignment updates a variable using its current value. It combines the calculation and assignment in one short form.

Operator Example Conceptual meaning
+=x += 5x = x + 5
-=x -= 5x = x - 5
*=x *= 5x = x * 5
/=x /= 5x = x / 5
%=x %= 5x = x % 5
&=x &= maskBitwise AND assignment
|=x |= maskBitwise OR assignment
^=x ^= maskBitwise XOR assignment
<<=x <<= 1Left-shift assignment
>>=x >>= 1Right-shift assignment
int score = 50;

score += 10;  /* 60 */
score -= 5;   /* 55 */
score *= 2;   /* 110 */
score /= 10;  /* 11 */

printf("%d", score);
Why compound assignment is useful

Compound assignment is useful for running totals and counters. It also evaluates its left operand only once. The table shows the basic meaning for a simple variable; an expression with side effects needs more care.

6.11 Increment and Decrement Operators

The increment operator ++ increases a value by one. The decrement operator -- decreases a value by one.

int count = 5;

count++;
printf("%d\n", count); /* 6 */

count--;
printf("%d\n", count); /* 5 */

There are two forms: prefix and postfix.

Form Example Value of the expression What happens to the variable
Prefix ++x New value Increment happens before the value is used
Postfix x++ Old value The expression gives the old value and also increments x
int a = 5;

int p = ++a;
/* a = 6, p = 6 */

a = 5;

int q = a++;
/* q = 5, a = 6 */
Beginner rule:

If you are only changing a variable and not using the expression's value, count++ and ++count both clearly express an increment. The important difference appears when the increment expression itself is part of a larger expression.

6.12 Avoid Tricky Increment Expressions

Beginners often see expressions such as:

printf("%d %d", i++, ++i);

The examples above change the same variable in ways that C does not order safely. Their behavior is undefined: C gives no reliable output to predict. Adding parentheses does not solve this problem. Write the updates as separate statements instead.

Prefer simple statements:

printf("%d\n", i);
i++;
printf("%d\n", i);
Professional C rule:

Keep each update easy to follow. A few clear statements are easier to check than one complicated expression.

6.13 Conditional Operator ? :

The conditional operator is C's only ternary operator. It is useful when a program needs to choose between two expressions based on a condition.

int a = 25;
int b = 40;

int max = (a > b) ? a : b;

printf("Maximum = %d", max);

Read it as:

condition ? value_if_true : value_if_false

For the example:

(a > b) ? a : b
   โ†“
Is a greater than b?
   โ†“
No
   โ†“
Choose b
   โ†“
max = 40

Only the selected second or third operand is evaluated. This makes the conditional operator useful for compact choices, but a normal if/else statement is usually clearer when the logic becomes large.

6.14 Bitwise Operators โ€” Working With Individual Bits

Core idea

Bitwise operators work directly on the individual bits of integer values. Instead of treating 5 only as a decimal number, C can work with its binary form:

5 = 0101
  • They are common in systems programming, embedded programming and device registers.
  • They are useful for flags, permissions, masks, networking and low-level data manipulation.
  • They are different from logical operators such as &&, || and !.
OperatorNameWhat it doesEasy memory trick
&Bitwise AND1 only when both bits are 1Keep common 1s
|Bitwise OR1 when at least one bit is 1Combine 1s
^Bitwise XOR1 when the two bits are differentDifferent = 1
~Bitwise NOTFlips every bit0 โ†” 1
<<Left shiftMoves bits toward the leftShift left
>>Right shiftMoves bits toward the rightShift right
Original value5 = 0101
โ†’
Bitwise operator& | ^ ~ << >>
Common starting example

To understand the operators, compare two small positive integers:

5 = 0101
3 = 0011

Bitwise AND & โ€” Keep Only Common 1 Bits

Rule
  • 1 & 1 โ†’ 1
  • Every other combination produces 0.
Example
  0101   (5)
& 0011   (3)
------
  0001   (1)

Only the positions where both numbers contain 1 remain 1.

Bitwise OR | โ€” Combine 1 Bits

Rule
  • 0 | 0 โ†’ 0
  • If either bit is 1, the result is 1.
Example
  0101   (5)
| 0011   (3)
------
  0111   (7)

Bitwise XOR ^ โ€” Detect Differences

Rule
  • Same bits โ†’ 0
  • Different bits โ†’ 1
Example
  0101   (5)
^ 0011   (3)
------
  0110   (6)

Bitwise NOT ~ โ€” Flip Every Bit

Remember

The ~ operator changes every bit:

0 โ†’ 1
1 โ†’ 0

Do not confuse bitwise NOT ~ with logical NOT !.

Bitwise NOT visualized
Original00000101
After ~11111010

So, conceptually:

5       = 00000101
~5      = 11111010

Why Does ~5 Become -6?

Most important point

The ~ operator only flips bits. It does not directly say โ€œmake the number negative.โ€ The final numeric result depends on how the resulting bit pattern is interpreted.

  • With a signed integer, the pattern can represent a negative value.
  • With an unsigned integer, the same pattern represents a non-negative value.
  • C also performs integer promotions before applying operators such as ~, so the operand's type matters.
Start with 5 as a typical 32-bit signed integer
5 = 00000000 00000000 00000000 00000101
Flip every bit
~5 = 11111111 11111111 11111111 11111010

Notice that the most significant bit is now 1.

Interpret the pattern as signed two's complement

On the usual modern two's-complement signed-integer systems, a most significant bit of 1 indicates a negative value. To find its magnitude, invert the bits and add 1:

11111111 11111111 11111111 11111010   original pattern
00000000 00000000 00000000 00000101   invert bits
00000000 00000000 00000000 00000110   add 1
                                      = 6

Therefore the original pattern represents -6.

Useful signed-integer shortcut
~x = -x - 1

~5 = -5 - 1
   = -6

Use the formula for quick calculations, but understand the bit-level process for interviews and low-level programming.

Signed vs Unsigned: Same Bits, Different Meaning

Signed integer
  • Uses a sign representation; modern systems normally use two's complement.
  • A leading 1 can indicate a negative value.
  • For a typical 32-bit signed int, ~5 is -6.
~5 = 11111111 ... 11111010
                 โ†“
                -6
Unsigned integer
  • All value bits represent non-negative quantities.
  • There is no negative sign interpretation.
  • The same flipped bits therefore produce a large positive value.
8-bit concept:
5   = 00000101
~5  = 11111010
    = 250
Important distinction: The 8-bit example is a conceptual unsigned example. In an actual C expression, smaller integer types such as unsigned char are commonly promoted to int before ~ is applied. Always consider the promoted type.

Actual 32-bit Unsigned Example

unsigned int x = 5;

5  = 00000000 00000000 00000000 00000101
~5 = 11111111 11111111 11111111 11111010

Result = 4294967290

For a typical 32-bit unsigned int, the result is 4294967290.

General unsigned relationship
~x = UINT_MAX - x

For an 8-bit unsigned value, the maximum is conceptually 255:

~5 = 255 - 5
   = 250

For real C code, the width of unsigned int is implementation-defined, so UINT_MAX from <limits.h> gives the maximum value of that type.

CasePattern after ~5InterpretationTypical result
Signed two's-complement int11111111 ... 11111010Negative value-6
8-bit unsigned representation11111010Positive value250
Typical 32-bit unsigned int11111111 ... 11111010Positive value4294967290
Quick understanding:
  • ~ always flips bits.
  • The type determines how those bits are interpreted.
  • Signed two's-complement interpretation can produce a negative value.
  • Unsigned interpretation produces a non-negative value.
  • Integer promotions matter for char and short.

Bitwise Shift Operators << and >>

Left shift <<
5 = 00000101
5 << 1 = 00001010 = 10

Bits move left and zeros enter from the right. For suitable non-negative values, shifting left by one position corresponds to multiplying by 2.

Right shift >>
5 = 00000101
5 >> 1 = 00000010 = 2

For a non-negative integer and a valid shift count, shifting right by one position gives the integer quotient after division by 2.

Placement warning: For these first examples, use non-negative values and valid shift counts. A signed left shift can be invalid if the result is too large. Do not apply the multiplication shortcut without checking the type and range.

6.15 Logical Operators vs Bitwise Operators

This is one of the most common C interview and beginner mistakes because the symbols look similar.

Logical Bitwise What it does
&& & Logical condition vs bit-by-bit AND
|| | Logical condition vs bit-by-bit OR
! ~ Reverse truth value vs flip bits
int a = 5;
int b = 3;

printf("%d\n", a && b); /* 1: both values are nonzero */
printf("%d\n", a & b);   /* 1: 0101 & 0011 = 0001 */

The first expression asks a logical question. The second expression manipulates the binary representation bit by bit.

6.16 Shift Operators << and >>

Shift operators move the bits of an integer value. They are commonly used with masks and low-level data processing.

Left Shift

unsigned int x = 5;

/*
5       = 00000101
5 << 1  = 00001010 = 10
5 << 2  = 00010100 = 20
*/

For an unsigned operand, a valid left shift moves bits left and fills the right-hand positions with zeros. Bits shifted beyond the typeโ€™s width are lost. Therefore the result need not equal ordinary multiplication if that multiplication would exceed the range.

Right Shift

unsigned int x = 20;

/*
20       = 00010100
20 >> 1  = 00001010 = 10
20 >> 2  = 00000101 = 5
*/

For unsigned values, right shift moves bits toward less significant positions and fills the high-order positions with zeroes.

Important:

The shift count must be at least zero and smaller than the number of bits in the promoted left operand. A negative count or a count equal to that width is invalid. Use unsigned types for these bit examples and keep the count within range.

6.17 Unary Operators You Must Recognize

Unary operators work with one operand. Some of them become especially important when you later learn pointers and dynamic memory.

Form Purpose Example
-xUnary minus / negation-10
+xUnary plus+10
!xLogical NOT!loggedIn
~xBitwise complement~mask
++x / x++Increment++count
--x / x--Decrementcount--
&xAddress-of&number
*ptrDereference a pointer*ptr
(type)xExplicit type conversion(float)x

You will use address-of and dereference when studying pointers. A cast changes the type used for a value in an expression. Recognize these forms now; later lessons explain them with complete examples.

6.18 sizeof, Casts, Member Access and Other Important Operators

C has several operators that do not fit into simple arithmetic or logical categories.

Operator / form Purpose Example
sizeof Find the size in bytes of a type or object sizeof(int)
(type) Explicitly convert a value to another type (float)5 / 2
& Address-of operator in a pointer context &x
* Dereference operator in a pointer context *ptr
. Access a structure/union member through an object student.age
-> Access a structure/union member through a pointer ptr->age
[] Array subscripting marks[2]
() Function call printf("Hi")
, Comma operator in contexts where the comma operator is used (x = 1, y = 2)

sizeof Is an Operator, Not a Function

int x;

printf("%zu\n", sizeof(x));
printf("%zu\n", sizeof(int));

sizeof gives the size in C bytes. A C byte contains at least eight bits, and the size of a type can vary between implementations. Use the result reported by your compiler instead of assuming that every int uses four bytes.

Explicit Type Conversion

int total = 5;
int count = 2;

double average = (double) total / count;

printf("%.2f", average); /* 2.50 */

Without the cast, total / count would divide two integers and discard the fractional part. Casting one operand before division makes this a floating-point calculation.

6.19 Type Conversion and Operators

Before calculating an expression, check the operand types. The same operator can give different results with integer and floating-point operands:

int a = 5;
int b = 2;

printf("%d\n", a / b);          /* 2 */
printf("%.2f\n", (double)a / b); /* 2.50 */

C sometimes converts operands before calculating a result. These rules are called integer promotions and usual arithmetic conversions. Start with this habit: always check the operand types before predicting the result.

Placement tip:

In output questions, check the types before doing the arithmetic. A correct calculation with the wrong assumed type can still give the wrong answer.

6.20 Common Operator Mistakes

Common mistake Correct understanding
= used when comparison is intended Use == for equality comparison
Expecting 7 / 2 to produce 3.5 Both operands are integers, so the result is 3
Using % with floating-point values Use integer operands for %; use fmod() for floating-point remainder
Confusing && with & Logical AND combines conditions; bitwise AND works on bits
Confusing || with | Logical OR combines conditions; bitwise OR works on bits
Confusing ! with ~ ! changes truth value; ~ flips bits
Assuming prefix and postfix increment are identical The variable changes by one in both, but the expression values differ
Using complicated increment expressions Separate updates into simple statements
Dividing by zero Check the divisor before division or remainder
Ignoring operand types Check whether the operands are integer, floating-point, signed, or unsigned
Assuming every shift is safe Use valid shift counts and understand signedness
Writing very long expressions Use parentheses or split the calculation into meaningful statements

6.21 How to Read an Operator Expression Step by Step

Read a difficult expression in small steps: identify the values, check their types, and work out the grouping before calculating the answer.

Step 1 โ†’ Identify the variables and their types
        โ†“
Step 2 โ†’ Identify each operator
        โ†“
Step 3 โ†’ Check parentheses
        โ†“
Step 4 โ†’ Determine which operation is evaluated first
        โ†“
Step 5 โ†’ Calculate one operation at a time
        โ†“
Step 6 โ†’ Check the resulting type
        โ†“
Step 7 โ†’ Check whether any variable was modified
        โ†“
Step 8 โ†’ Determine the final result

For example:

int a = 10;
int b = 3;
int result = a + b * 2;

Do not simply read from left to right. First identify that multiplication and addition are different operations. The detailed rules that determine grouping are covered in the dedicated Operator Precedence & Associativity topic. For now, use parentheses whenever they make your intended calculation clearer.

int result = a + (b * 2);

6.22 Operator Safety Checklist

  • Check the data types of the operands.
  • Know the difference between assignment = and equality ==.
  • Remember that integer division discards the fractional part.
  • Use % for integer remainder calculations.
  • Never allow an unexpected zero divisor.
  • Use && and || when combining conditions.
  • Remember that logical operators short-circuit.
  • Do not confuse logical operators with bitwise operators.
  • Understand the difference between prefix and postfix increment/decrement.
  • Avoid modifying the same variable multiple times in a complicated expression.
  • Use unsigned types when deliberately manipulating bit patterns.
  • Use valid shift counts.
  • Use parentheses when they improve readability.
  • Do not memorize output; trace the expression step by step.

6.23 Unsigned Arithmetic, Signed Overflow and Safe Addition

An unsigned result wraps into the typeโ€™s range when it becomes too large. Signed overflow has undefined behavior, so do not expect it to wrap. In this example, both operands are positive. The program checks the upper limit before adding them.

Complete C program:

#include <stdio.h>
#include <limits.h>

int main(void)
{
    int a = INT_MAX, b = 1;
    if (b > 0 && a > INT_MAX - b)
        puts("Addition would overflow");
    else
        printf("Sum: %d\n", a + b);
    return 0;
}

Expected output:

Addition would overflow

Step-by-step explanation:

  1. INT_MAX is the largest representable int.
  2. The check occurs before computing a + b.
  3. The program reports the unsafe operation instead of triggering undefined behavior.
Remember: This example checks addition with a positive second operand. Subtraction, multiplication, and addition with a negative second operand need their own checks.

6.24 Quick Revision

โž• Arithmetic โ†’ + - * / %

๐Ÿ” Relational โ†’ < < = > > =

โš–๏ธ Equality โ†’ == ! =

๐Ÿง  Logical โ†’ && || !

๐Ÿ“ฅ Assignment โ†’ =

๐Ÿ”„ Compound assignment โ†’ += -= *= /= %=

โฌ†๏ธ Increment / decrement โ†’ ++ --

โ“ Conditional โ†’ ? :

๐Ÿ”ข Bitwise โ†’ & | ^ ~ << >>

๐Ÿ“ Size โ†’ sizeof

๐Ÿ”„ Cast โ†’ (type)

๐Ÿ‘‰ Pointer-related forms โ†’ & and *

๐ŸŽฏ The main idea to remember

An operator is not just a symbol to memorize. To understand an expression, ask four questions:

  1. What are the operands?
  2. What type are the operands?
  3. What does the operator do?
  4. What value or side effect does the expression produce?

Once you can answer those four questions, C expressions become much easier to read, debug, and predict.

6.25 Quick MCQs

Select an answer first, then click Check Answer. A correct choice becomes green. If the choice is wrong, it becomes red and the correct option is shown in green. The correct answer and explanation appear below after checking.

1. What is the result of 10 % 3?
2. Which operator is used for equality comparison?
3. What is the result of 5 / 2 when both operands are integers?
4. Which operator means logical AND?
5. What is the value of a after: int a = 5; ++a;
6. Which operator is used for bitwise XOR?
PRACTICE

6.26 ๐ŸŽฏ Programming Problems

Try every problem yourself first. Use ๐Ÿ’ป Solve It Yourself to write and test your C code. Open Hint only when needed, and use Show Program after attempting the problem.

๐Ÿ“ˆ Operators Practice Progress
Solved 0 / 8
Completed with Solution 0
Total Score 0 / 160
Completion 0%
A problem counts as Solved when all test cases pass without opening the full solution. Problems completed after viewing the official solution are tracked separately.
1. Basic Arithmetic Operations

Problem 1: Read two integers and print their sum, difference, product, quotient and remainder.

Input: Two integers a and b, where b is not zero.

Output: Print sum, difference, product, integer quotient and remainder.

2. Even or Odd Using Modulus

Problem 2: Check whether a given integer is even or odd using the modulus operator.

Input: One integer n.

Output: Print "Even" or "Odd".

3. Largest of Three Numbers

Problem 3: Read three numbers and find the largest using relational and logical operators.

Input: Three integers a, b and c.

Output: Print the largest value.

4. Pre-Increment vs Post-Increment

Problem 4: Demonstrate the difference between pre-increment and post-increment.

Input: One integer a.

Output: Using separate copies of the input, print the result of pre-increment and post-increment.

5. Number Between 10 and 100

Problem 5: Check whether a number lies between 10 and 100 using logical operators.

Input: One integer n.

Output: Print "Inside Range" when 10 <= n <= 100, otherwise print "Outside Range".

6. Larger Number Using Conditional Operator

Problem 6: Find the larger of two numbers using the conditional operator.

Input: Two integers a and b.

Output: Print the larger value.

7. Bitwise AND, OR and XOR

Problem 7: Perform AND, OR and XOR operations on two integers.

Input: Two non-negative integers a and b.

Output: Print the results of a & b, a | b and a ^ b.

8. Left Shift and Right Shift

Problem 8: Demonstrate left-shift and right-shift operations using a positive integer.

Input: A positive integer n and a non-negative shift count k.

Output: Print n << k and n >> k.

6.27 Key Takeaway

๐ŸŽฏ Operators are the building blocks of expressions and conditions.

Before solving a coding problem, identify:

What calculation is required?

What comparison is required?

Are multiple conditions involved?

Is integer or floating-point arithmetic required?

Once you understand operators well, decision-making and loops become much easier.
INTERACTIVE LEARNING

๐ŸŽฌ Operators โ€” Expression Evaluation

Follow how C evaluates result = a + b * 2 when a = 10 and b = 3.

PROGRAM TRACING

๐Ÿ”Ž Program Tracing โ€” Operators

Trace the important difference between pre-increment and post-increment.

INTERVIEW PREPARATION

๐ŸŽค Operators โ€” Interview Questions

1. What is an operator in C?
2. What is the difference between = and ==?
3. What is the difference between logical && and bitwise &?
4. What is short-circuit evaluation?
5. What is the difference between ++a and a++?
6. What is the purpose of the conditional operator ?: ?
7. What is the difference between / and % for integer operands?
8. What do << and >> do?
PLACEMENT TIPS

๐Ÿ’ก Operators โ€” Extra Tips

  • Be very clear about the difference between = and ==. It is one of the most common beginner mistakes.
  • Memorize the behavior of integer division and modulus with simple examples.
  • Know that && and || use short-circuit evaluation. This is frequently tested in output-prediction questions.
  • For ++a and a++, first ask whether the value of the expression itself is being used.
  • Keep changes to a variable in separate statements when the order matters. Parentheses control grouping; they cannot repair unsequenced changes.
  • For bitwise questions, convert small positive integers to binary and trace each bit position.
EXTRA PRACTICE

โœ๏ธ Operators โ€” Extra Practice Questions

  1. Predict the values of a and b after int a = 5; int b = ++a;.
  2. Predict the values of a and b after int a = 5; int b = a++;.
  3. Explain why x ! = 0 && 10 / x > 2 can safely avoid division by zero.
  4. Evaluate 10 + 3 * 2 and explain which operator is applied first.
  5. For a = 12 and b = 10, calculate a & b, a | b, and a ^ b.
  6. Rewrite if (a > b) max = a; else max = b; using the conditional operator.
โ† Previous Topic: Input & Output Next Topic: Expressions โ†’