💻 Unit 1 – Part C

C Programming

⬅ Back to Unit 1

Ad Space

Part C: Additional Questions

1. Explain the different types of operators with a suitable program.

Operators are symbols that perform operations on variables and values. C supports different types of operators, grouped as follows:

1. Arithmetic Operators

Used for mathematical operations.

OperatorMeaning
+Addition
-Subtraction
*Multiplication
/Division
%Modulus
Example:
#include <stdio.h>
int main() {
    int a = 10, b = 3;
    
    printf("a + b = %d\n", a + b);
    printf("a - b = %d\n", a - b);
    printf("a * b = %d\n", a * b);
    printf("a / b = %d\n", a / b);
    printf("a %% b = %d\n", a % b);
    
    return 0;
}
Output:
a + b = 13
a - b = 7
a * b = 30
a / b = 3
a % b = 1

2. Relational Operators

Used to compare values. They return 1 (true) or 0 (false).

OperatorMeaning
==Equal to
!=Not equal to
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to
Example:
int x = 5, y = 10;
printf("%d\n", x > y); // 0 (false)
printf("%d\n", x < y); // 1 (true)

3. Logical Operators

Used for logical conditions.

OperatorMeaning
&&Logical AND
||Logical OR
!Logical NOT
Example:
int a = 5, b = 10;
printf("%d\n", (a > 0 && b > 0)); // 1 (true)
printf("%d\n", (a > 0 || b < 0)); // 1 (true)
printf("%d\n", !(a > 0)); // 0 (false)

4. Assignment Operators

Used to assign values.

OperatorExampleEquivalent
=a = 10a = 10
+=a += 5a = a + 5
-=a -= 5a = a - 5
*=a *= 5a = a * 5
/=a /= 5a = a / 5
%=a %= 5a = a % 5

5. Increment and Decrement Operators

Used to increment or decrement a value by 1.

OperatorMeaning
++Increments by 1
--Decrements by 1
Example:
int a = 5;
printf("%d\n", a++); // 5 (post-increment, a becomes 6)
printf("%d\n", ++a); // 7 (pre-increment, a becomes 7)

6. Conditional (Ternary) Operator

Used as a shorthand for if-else.

Syntax:
condition ? expr1 : expr2;
Example:
int a = 10, b = 20;
int largest = (a > b) ? a : b;
printf("Largest = %d", largest);
Output:
Largest = 20

7. Bitwise Operators

Work at the bit level.

OperatorMeaning
&Bitwise AND
|Bitwise OR
^Bitwise XOR
~Bitwise NOT (Complement)
<<Left shift
>>Right shift

Example Program (Demonstrating Multiple Operators)

#include <stdio.h>

int main() {
    int a = 10, b = 20;

    // Arithmetic
    printf("a + b = %d\n", a + b);

    // Relational
    printf("a > b = %d\n", a > b); // 0 (false)

    // Logical
    printf("(a > 0 && b > 0) = %d\n", (a > 0 && b > 0)); // 1 (true)

    // Assignment
    a += 5; // a is now 15
    printf("a after += 5: %d\n", a);

    // Conditional
    int max = (a > b) ? a : b; // a is 15, b is 20
    printf("Largest = %d\n", max); // max will be 20

    return 0;
}

Ad Space