Welcome to the exciting world of C Programming! In this lesson, we'll explore various types of operators that are essential for writing and understanding C programs.
In simple terms, operators are symbols that tell the compiler to perform specific mathematical or logical operations on values or variables. They help in creating complex expressions and decision-making structures in your programs.
C Programming supports several types of operators, which we'll explore below:
Arithmetic operators are used to perform mathematical operations. Here are some common arithmetic operators:
+)-)*)/)%)++)--)Let's look at a simple example using these operators:
#include <stdio.h>
int main() {
int a = 5;
int b = 3;
// Addition
int sum = a + b;
printf("Sum: %d\n", sum);
// Subtraction
int difference = a - b;
printf("Difference: %d\n", difference);
// Multiplication
int product = a * b;
printf("Product: %d\n", product);
// Division
float quotient = (float)a / b;
printf("Quotient: %.2f\n", quotient);
// Modulus
int remainder = a % b;
printf("Remainder: %d\n", remainder);
// Increment
a++;
printf("Incremented a: %d\n", a);
// Decrement
b--;
printf("Decremented b: %d\n", b);
return 0;
}Assignment operators are used to assign values to variables. Here are some examples:
=)+=)-=)*=)/=)%=)&=)|=)^=)^=)<<=)>>=)Here's an example demonstrating the use of assignment operators:
#include <stdio.h>
int main() {
int x = 5;
// Assignment
int y = 3;
printf("Assignment: x = %d, y = %d\n", x, y);
// Addition assignment
x += y;
printf("Addition Assignment: x = %d, y = %d\n", x, y);
// Subtraction assignment
y -= x;
printf("Subtraction Assignment: x = %d, y = %d\n", x, y);
return 0;
}Comparison operators are used to compare two operands and return a boolean value (true or false). Here are some common comparison operators:
==)!=)>)<)>=)<=)Let's look at a simple example using comparison operators:
#include <stdio.h>
int main() {
int x = 5;
int y = 3;
// Equal to
if (x == y) {
printf("x is equal to y\n");
} else {
printf("x is not equal to y\n");
}
// Not equal to
if (x != y) {
printf("x is not equal to y\n");
} else {
printf("x is equal to y\n");
}
// Greater than
if (x > y) {
printf("x is greater than y\n");
} else {
printf("x is not greater than y\n");
}
// Less than
if (x < y) {
printf("x is less than y\n");
} else {
printf("x is not less than y\n");
}
// Greater than or equal to
if (x >= y) {
printf("x is greater than or equal to y\n");
} else {
printf("x is not greater than or equal to y\n");
}
// Less than or equal to
if (x <= y) {
printf("x is less than or equal to y\n");
} else {
printf("x is not less than or equal to y\n");
}
return 0;
}What is the result of the following expression: 5 + 3 * 2?
In the following code snippet, what will be the output of the program?