Operators & Expressions in C

Introduction

In C programming, operators are symbols that perform operations on variables and values. An expression is a combination of operators, constants, and variables that evaluates to a single value. Understanding operators and expressions is crucial for writing logical and effective programs.


Key Points

1. Types of Operators

  1. Arithmetic Operators
  • Perform basic mathematical operations: +, -, *, /, %
  • Example: int a = 10, b = 3; printf("%d", a % b); // Output: 1
  1. Relational Operators
  • Compare values and return true (1) or false (0)
  • Operators: ==, !=, >, <, >=, <=
  • Example: if(a > b) { /* code */ }
  1. Logical Operators
  • Combine multiple conditions: && (AND), || (OR), ! (NOT)
  • Example: if(a > 5 && b < 10) { /* code */ }
  1. Assignment Operators
  • Assign values to variables: =, +=, -=, *=, /=
  • Example: a += 5; // a = a + 5
  1. Increment & Decrement Operators
  • ++ → increment by 1
  • -- → decrement by 1
  • Can be prefix (++a) or postfix (a++)

2. Expressions

  • Definition: Combination of variables, constants, and operators that evaluates to a value
  • Examples: int x = 10 + 5; // 15 int y = x * 2; // 30
  • Importance:
    • Expressions form the logic of programs
    • Used in calculations, conditions, and loops

3. Operator Precedence

  • Determines the order in which operators are evaluated
  • Example: int x = 10 + 5 * 2;5*2 evaluated first → x = 20

Example Code

#include <stdio.h>
int main() {
    int a = 10, b = 5;
    int sum = a + b;
    int isEqual = (a == b);
    int result = (a > 5 && b < 10);
    printf("Sum: %d, Equal: %d, Result: %d", sum, isEqual, result);
    return 0;
}
Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *