Lecture 5
Lecture 5
Fundamentals
int main() {
int x = 5, y = -3, z = 10;
cout << "x > 0 AND y > 0: " << (x > 0 && y > 0)
<< endl; // False (0)
cout << "x > 0 OR y > 0: " << (x > 0 || y > 0) <<
endl; // True (1)
cout << "NOT (z < 0): " << !(z < 0) << endl; //
True (1)
return 0; }
Logical operators are commonly used in conditional
statements like if, while, and for.
Example:
// Post-increment
cout << "Post-increment: " << a++ << endl; // prints 6, then
a=7
cout << "After post-increment: " << a << endl; // a = 7
// Pre-decrement
cout << "Pre-decrement: " << --a << endl; // a =
6, prints 6
// Post-decrement
cout << "Post-decrement: " << a-- << endl; //
prints 6, then a = 5
cout << "After post-decrement: " << a << endl; //
a=5
return 0;
}
Use pre- when the updated value is needed
immediately.
Use post- when the current value is needed before
updating
4. Operator Precedence
Operator precedence decides the order of evaluation
in complex expressions. Operators with higher
precedence are evaluated first.
Example of Precedence
#include <iostream>
using namespace std;
int main() {
int a = 5, b = 10, c = 15;
// Without parentheses
int result1 = a + b * c; // Multiplication first: result1 = 5 + (10
* 15) = 155
// With parentheses
int result2 = (a + b) * c; // Parentheses first: result2 = (5 + 10)
* 15 = 225
cout << "Result1: " << result1 << endl; // 155
cout << "Result2: " << result2 << endl; // 225
return 0;
}
Use parentheses: Parentheses improve readability and
control the order of operations.
Remember precedence rules: For example, * is
evaluated before +.
Test increment/decrement carefully: Misunderstanding
pre- and post-increment can lead to unexpected
behavior.
Variables in C++
For example:
int age = 25;
Example:
#include <iostream>
using namespace std;
int main() {
int age;
cout << "Enter your age: ";
cin >> age; // User inputs a value
cout << "You are " << age << " years old."
<< endl;
return 0;
}
Output Example:
Enter your age: 25
You are 25 years old.