Menu

System Programming Topic

C++ Operators

1. Arithmetic Operators

Perform mathematical operations.

Operator Name Example Result
+ Addition 5 + 3 8
- Subtraction 5 - 3 2
* Multiplication 5 * 3 15
/ Division 10 / 3 3 (int)
/ Division 10.0 / 3.0 3.333 (float)
% Modulus 10 % 3 1
++ Increment x++ or ++x x + 1
-- Decrement x-- or --x x - 1

Increment/Decrement:

cpp

int x = 5;
int y = ++x;  // Pre-increment: x=6, y=6
int z = x++;  // Post-increment: z=6, x=7

int a = 10;
int b = --a;  // Pre-decrement: a=9, b=9
int c = a--;  // Post-decrement: c=9, a=8

2. Relational Operators

Compare values, return bool (true/false).

Operator Name Example Result
== Equal to 5 == 3 false
!= Not equal 5 != 3 true
> Greater than 5 > 3 true
< Less than 5 < 3 false
>= Greater than or equal 5 >= 5 true
<= Less than or equal 5 <= 3 false

cpp

int a = 10, b = 20;
cout << (a == b) << endl;  // 0 (false)
cout << (a != b) << endl;  // 1 (true)
cout << (a < b) << endl;   // 1 (true)
cout << (a >= 10) << endl; // 1 (true)

3. Logical Operators

Combine boolean expressions.

Operator Name Description Example
&& AND True if both are true (5>3 && 5<10) → true
|| OR True if at least one is true (5<3 || 5>10) → false
! NOT Reverse the result !(5==3) → true

cpp

int age = 25;
bool hasLicense = true;

// AND operator
if(age >= 18 && hasLicense) {
    cout << "Can drive" << endl;
}

// OR operator
if(age < 13 || age > 65) {
    cout << "Eligible for discount" << endl;
}

// NOT operator
bool isWeekend = false;
if(!isWeekend) {
    cout << "It's a weekday" << endl;
}

// Short-circuit evaluation
int x = 0;
if(x != 0 && 10/x > 2) {  // Second part not evaluated if first is false
    // Safe from division by zero
}

4. Bitwise Operators

Operate on individual bits.

Operator Name Description Example (a=5, b=3)
& AND 1 if both bits are 1 5 & 3 → 1 (0101 & 0011 = 0001)
| OR 1 if any bit is 1 5 | 3 → 7 (0101 | 0011 = 0111)
^ XOR 1 if bits are different 5 ^ 3 → 6 (0101 ^ 0011 = 0110)
~ NOT Flip all bits ~5 → -6 (in 2's complement)
<< Left shift Shift bits left 5 << 1 → 10 (0101 → 1010)
>> Right shift Shift bits right 5 >> 1 → 2 (0101 → 0010)

cpp

unsigned int a = 5;  // 0101 in binary
unsigned int b = 3;  // 0011 in binary

cout << "a & b = " << (a & b) << endl;   // 0001 = 1
cout << "a | b = " << (a | b) << endl;   // 0111 = 7
cout << "a ^ b = " << (a ^ b) << endl;   // 0110 = 6
cout << "~a = " << (~a) << endl;         // 1111 1010 = 250 (unsigned)
cout << "a << 1 = " << (a << 1) << endl; // 1010 = 10
cout << "a >> 1 = " << (a >> 1) << endl; // 0010 = 2

// Practical uses:
// Check if number is even/odd
if(x & 1) {
    cout << x << " is odd" << endl;  // Last bit is 1
} else {
    cout << x << " is even" << endl; // Last bit is 0
}

// Multiply/divide by powers of 2
int num = 10;
int doubled = num << 1;  // 20 (10*2)
int halved = num >> 1;   // 5 (10/2)

// Set bit at position
int setBit(int num, int pos) {
    return num | (1 << pos);
}

// Clear bit at position
int clearBit(int num, int pos) {
    return num & ~(1 << pos);
}

5. Assignment Operators

Assign values to variables.

Operator Example Equivalent to
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
<<= x <<= 3 x = x << 3
>>= x >>= 3 x = x >> 3

cpp

int x = 10;
x += 5;   // x = 15
x -= 3;   // x = 12
x *= 2;   // x = 24
x /= 4;   // x = 6
x %= 4;   // x = 2

// Chaining assignment
int a, b, c;
a = b = c = 10;  // All set to 10

// Compound assignment with expressions
int y = 5;
y += 3 * 2;  // y = y + (3*2) = 11

6. Operator Precedence

Order in which operators are evaluated.

Precedence Operator Description Associativity
1 :: Scope resolution Left to right
2 ++ -- Suffix increment/decrement Left to right
2 () [] . -> Function call, array subscript, member access Left to right
3 ++ -- Prefix increment/decrement Right to left
3 + - Unary plus/minus Right to left
3 ! ~ Logical NOT, bitwise NOT Right to left
3 * & Dereference, address-of Right to left
3 (type) Type cast Right to left
3 sizeof Size of Right to left
4 .* ->* Pointer-to-member Left to right
5 * / % Multiplication, division, modulus Left to right
6 + - Addition, subtraction Left to right
7 << >> Bitwise left/right shift Left to right
8 < <= > >= Relational operators Left to right
9 == != Equality operators Left to right
10 & Bitwise AND Left to right
11 ^ Bitwise XOR Left to right
12 | Bitwise OR Left to right
13 && Logical AND Left to right
14 || Logical OR Left to right
15 ?: Ternary conditional Right to left
16 = += -= etc. Assignment operators Right to left
17 , Comma operator Left to right

Examples:

cpp

int result = 5 + 3 * 2;      // 11 (multiplication first)
int result2 = (5 + 3) * 2;   // 16 (parentheses change order)

bool logical = 5 > 3 && 10 < 20;  // true (&& after comparisons)

int a = 5, b = 3, c = 2;
int expr = a + b * c;        // 11 (b*c = 6, +5)
int expr2 = (a + b) * c;     // 16

// Tricky precedence
int x = 5, y = 10, z = 15;
bool test = x + 5 > y && y < z;  // (x+5)>y && (y<z) = true

// Use parentheses for clarity
int unclear = a & b == 2;     // Wrong: b==2 evaluated first
int clear = (a & b) == 2;     // Correct

Conditional Statements

1. if Statement

cpp

if(condition) {
    // code executes if condition is true
}

Simple Example:

cpp

int age = 20;
if(age >= 18) {
    cout << "You are an adult" << endl;
}

2. if-else Statement

cpp

if(condition) {
    // code if condition is true
} else {
    // code if condition is false
}

Example:

cpp

int score = 75;
if(score >= 50) {
    cout << "Pass" << endl;
} else {
    cout << "Fail" << endl;
}

3. else-if Ladder

cpp

if(condition1) {
    // code if condition1 is true
} else if(condition2) {
    // code if condition2 is true
} else if(condition3) {
    // code if condition3 is true
} else {
    // code if all conditions are false
}

Example:

cpp

int marks = 85;
char grade;

if(marks >= 90) {
    grade = 'A';
} else if(marks >= 80) {
    grade = 'B';
} else if(marks >= 70) {
    grade = 'C';
} else if(marks >= 60) {
    grade = 'D';
} else {
    grade = 'F';
}
cout << "Grade: " << grade << endl;

4. Nested Conditions

cpp

if(condition1) {
    if(condition2) {
        // code if both conditions are true
    }
}

Example:

cpp

int age = 25;
bool hasLicense = true;

if(age >= 18) {
    if(hasLicense) {
        cout << "Can drive a car" << endl;
    } else {
        cout << "Need to get a license first" << endl;
    }
} else {
    cout << "Too young to drive" << endl;
}

// Alternative with logical operators
if(age >= 18 && hasLicense) {
    cout << "Can drive a car" << endl;
}

5. switch Statement

Used for multiple choices based on a single value.

cpp

switch(expression) {
    case constant1:
        // code
        break;
    case constant2:
        // code
        break;
    default:
        // code if no case matches
}

Example:

cpp

int day = 3;
switch(day) {
    case 1:
        cout << "Monday" << endl;
        break;
    case 2:
        cout << "Tuesday" << endl;
        break;
    case 3:
        cout << "Wednesday" << endl;
        break;
    case 4:
        cout << "Thursday" << endl;
        break;
    case 5:
        cout << "Friday" << endl;
        break;
    case 6:
        cout << "Saturday" << endl;
        break;
    case 7:
        cout << "Sunday" << endl;
        break;
    default:
        cout << "Invalid day" << endl;
}

Important Notes:

  • Expression must be integral or enum type

  • break is needed to exit switch

  • Cases can be combined

  • default is optional

Combined Cases:

cpp

char grade = 'B';
switch(grade) {
    case 'A':
    case 'B':
    case 'C':
        cout << "Pass" << endl;
        break;
    case 'D':
    case 'F':
        cout << "Fail" << endl;
        break;
    default:
        cout << "Invalid grade" << endl;
}

switch vs if-else:

cpp

// Equivalent if-else for switch example
if(day == 1) {
    cout << "Monday" << endl;
} else if(day == 2) {
    cout << "Tuesday" << endl;
} // ... and so on

Modern C++17 if with initializer:

cpp

if(int result = calculate(); result > 100) {
    cout << "Large result: " << result << endl;
}
// result is out of scope here

Conditional Operator (Ternary):

cpp

// Syntax: condition ? expression1 : expression2
int a = 10, b = 20;
int max = (a > b) ? a : b;  // Returns larger value

// Equivalent to:
if(a > b) {
    max = a;
} else {
    max = b;
}

// Can be nested (avoid for clarity)
int score = 75;
string result = (score >= 50) ? 
                ((score >= 80) ? "Distinction" : "Pass") : 
                "Fail";

Loops

1. for Loop

cpp

for(initialization; condition; update) {
    // code to repeat
}

Examples:

cpp

// Basic for loop
for(int i = 0; i < 5; i++) {
    cout << i << " ";  // Output: 0 1 2 3 4
}

// Multiple variables
for(int i = 0, j = 10; i < j; i++, j--) {
    cout << i << "-" << j << " ";  // 0-10 1-9 2-8 3-7 4-6
}

// Reverse loop
for(int i = 10; i > 0; i--) {
    cout << i << " ";
}

// Infinite loop (avoid!)
// for(;;) {
//     // infinite loop
// }

// Range-based for loop (C++11)
vector<int> numbers = {1, 2, 3, 4, 5};
for(int num : numbers) {
    cout << num << " ";
}

// With auto
for(auto num : numbers) {
    cout << num << " ";
}

// Reference to modify
for(int& num : numbers) {
    num *= 2;  // Double each element
}

2. while Loop

cpp

while(condition) {
    // code to repeat while condition is true
}

Examples:

cpp

// Basic while loop
int i = 0;
while(i < 5) {
    cout << i << " ";
    i++;
}

// User input validation
int number;
cout << "Enter positive number: ";
cin >> number;
while(number <= 0) {
    cout << "Invalid! Enter positive number: ";
    cin >> number;
}

// Infinite loop with break
while(true) {
    // do something
    if(exitCondition) {
        break;
    }
}

3. do-while Loop

cpp

do {
    // code executes at least once
} while(condition);

Examples:

cpp

// Basic do-while
int i = 0;
do {
    cout << i << " ";
    i++;
} while(i < 5);

// Menu system
int choice;
do {
    cout << "\n1. Add\n2. Subtract\n3. Exit\nChoice: ";
    cin >> choice;
    
    switch(choice) {
        case 1: /* add */ break;
        case 2: /* subtract */ break;
        case 3: cout << "Exiting..." << endl; break;
        default: cout << "Invalid choice" << endl;
    }
} while(choice != 3);

// Guaranteed execution at least once
char answer;
do {
    cout << "Do you want to continue? (y/n): ";
    cin >> answer;
} while(answer != 'y' && answer != 'n');

while vs do-while:

cpp

int x = 10;

// while - condition checked first
while(x < 5) {
    cout << "This won't execute";
}

// do-while - executes once before checking
do {
    cout << "This executes once";  // Executes even though x=10
} while(x < 5);

4. Nested Loops

Loop inside another loop.

cpp

for(int i = 0; i < 3; i++) {
    for(int j = 0; j < 3; j++) {
        cout << "(" << i << "," << j << ") ";
    }
    cout << endl;
}
// Output:
// (0,0) (0,1) (0,2)
// (1,0) (1,1) (1,2)
// (2,0) (2,1) (2,2)

Examples:

cpp

// Multiplication table
for(int i = 1; i <= 10; i++) {
    for(int j = 1; j <= 10; j++) {
        cout << i * j << "\t";
    }
    cout << endl;
}

// Pattern printing
int rows = 5;
for(int i = 1; i <= rows; i++) {
    for(int j = 1; j <= i; j++) {
        cout << "* ";
    }
    cout << endl;
}
// Output:
// *
// * *
// * * *
// * * * *
// * * * * *

// 2D array traversal
int matrix[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
for(int i = 0; i < 3; i++) {
    for(int j = 0; j < 3; j++) {
        cout << matrix[i][j] << " ";
    }
    cout << endl;
}

5. break & continue

break Statement:

Exits the current loop immediately.

cpp

// Search for number
int numbers[] = {1, 3, 5, 7, 9, 2, 4, 6, 8};
int target = 7;

for(int i = 0; i < 9; i++) {
    if(numbers[i] == target) {
        cout << "Found at position " << i << endl;
        break;  // Exit loop early
    }
}

// In switch
int day = 2;
switch(day) {
    case 1: cout << "Mon"; break;
    case 2: cout << "Tue"; break;  // Exit switch
}

// Breaking nested loops
for(int i = 0; i < 3; i++) {
    for(int j = 0; j < 3; j++) {
        if(i * j == 4) {
            cout << "Found at " << i << "," << j << endl;
            break;  // Only breaks inner loop
        }
    }
}

continue Statement:

Skips to the next iteration of the loop.

cpp

// Print odd numbers only
for(int i = 1; i <= 10; i++) {
    if(i % 2 == 0) {
        continue;  // Skip even numbers
    }
    cout << i << " ";  // Output: 1 3 5 7 9
}

// Skip invalid input
for(int i = 0; i < 5; i++) {
    int num;
    cout << "Enter positive number: ";
    cin >> num;
    
    if(num <= 0) {
        cout << "Invalid, skipping..." << endl;
        continue;  // Skip this iteration
    }
    
    cout << "Processing " << num << endl;
}

// In while loop
int i = 0;
while(i < 10) {
    i++;
    if(i % 3 == 0) {
        continue;  // Skip multiples of 3
    }
    cout << i << " ";
}
// Output: 1 2 4 5 7 8 10

Loop Control Examples:

Prime Number Check:

cpp

int num = 17;
bool isPrime = true;

if(num <= 1) {
    isPrime = false;
} else {
    for(int i = 2; i <= num/2; i++) {
        if(num % i == 0) {
            isPrime = false;
            break;  // No need to check further
        }
    }
}

cout << num << " is " << (isPrime ? "prime" : "not prime") << endl;

Fibonacci Series:

cpp

int n = 10;
int a = 0, b = 1;

cout << "Fibonacci: " << a << " " << b << " ";
for(int i = 2; i < n; i++) {
    int next = a + b;
    cout << next << " ";
    a = b;
    b = next;
}

Menu System with Loop:

cpp

#include <iostream>
using namespace std;

int main() {
    int choice;
    
    do {
        cout << "\n=== Calculator ===" << endl;
        cout << "1. Add" << endl;
        cout << "2. Subtract" << endl;
        cout << "3. Multiply" << endl;
        cout << "4. Divide" << endl;
        cout << "5. Exit" << endl;
        cout << "Enter choice: ";
        cin >> choice;
        
        if(choice >= 1 && choice <= 4) {
            double num1, num2;
            cout << "Enter two numbers: ";
            cin >> num1 >> num2;
            
            switch(choice) {
                case 1:
                    cout << "Result: " << num1 + num2 << endl;
                    break;
                case 2:
                    cout << "Result: " << num1 - num2 << endl;
                    break;
                case 3:
                    cout << "Result: " << num1 * num2 << endl;
                    break;
                case 4:
                    if(num2 != 0) {
                        cout << "Result: " << num1 / num2 << endl;
                    } else {
                        cout << "Error: Division by zero!" << endl;
                    }
                    break;
            }
        } else if(choice != 5) {
            cout << "Invalid choice!" << endl;
        }
        
    } while(choice != 5);
    
    cout << "Goodbye!" << endl;
    return 0;
}

Modern Loop Features:

Structured Bindings (C++17):

cpp

#include <map>
#include <iostream>

int main() {
    std::map<std::string, int> scores = {{"Alice", 95}, {"Bob", 87}, {"Charlie", 92}};
    
    for(const auto& [name, score] : scores) {
        std::cout << name << ": " << score << std::endl;
    }
    
    return 0;
}

Initializer in if/switch (C++17):

cpp

if(auto it = myMap.find(key); it != myMap.end()) {
    // Use it here
} // it is destroyed here

switch(int value = getValue(); value) {
    case 1: /* ... */ break;
    case 2: /* ... */ break;
}

Common Patterns:

Reading until sentinel:

cpp

int value;
while(cin >> value && value != -1) {
    // Process value
}

Input validation:

cpp

int age;
do {
    cout << "Enter age (0-120): ";
    cin >> age;
} while(age < 0 || age > 120);

Pattern printing:

cpp

// Pyramid pattern
int rows = 5;
for(int i = 1; i <= rows; i++) {
    // Print spaces
    for(int j = 1; j <= rows - i; j++) {
        cout << " ";
    }
    // Print stars
    for(int k = 1; k <= (2*i - 1); k++) {
        cout << "*";
    }
    cout << endl;
}

This extensive guide covers all essential operators and control flow constructs in C++. Practice these concepts with coding exercises to build strong fundamentals!

Comments (0)

No comments yet. Be the first to comment!

LecturreAI Assistant

Hello! I'm LecturreAI

What would you like to learn today?