โš™๏ธ
Chapter 4

Basics of C++

Get started with C++ syntax, variables, operators, and control structures.

4.1 Tokens and Identifiers

The smallest individual units that make up a C++ program.

Aspect Definition Example
Tokens Smallest individual unit in a program. Keywords, Identifiers, Operators
Keywords Reserved words in C++. int, float, if, else, class
Identifiers Names given to variables, functions, etc. myVar, calculateSum()
Literals Constant values used in a program. 123, "Hello", 3.14
Punctuators Symbols for structure. ;, {}, ()
โ–ถ Tokens and Identifiers Example
#include <iostream>
using namespace std;

int main() {
    // Keywords: int, return
    // Identifiers: main, number, result
    // Literals: 369, "Value is: "
    // Operators: =, +
    // Punctuators: ;, {}, ()
    
    int number = 369;  // integer literal
    float pi = 3.14f;  // float literal
    char grade = 'A'; // character literal
    string name = "Tesla"; // string literal
    bool isActive = true; // boolean literal
    
    cout << "Integer: " << number << endl;
    cout << "Float: " << pi << endl;
    cout << "Character: " << grade << endl;
    cout << "String: " << name << endl;
    cout << "Boolean: " << isActive << endl;
    
    return 0;
}
Click "Run Code" to execute

4.2 Variables and Constants

Named storage locations for data in your programs.

Aspect Definition Example
Variable Named storage for data. int myVar = 369;
Scope Defines where a variable is accessible. Local, Global, Static
Constant Immutable data value. const int Tesla = 369;
Initialization Assigning a value to a variable. int x = 10;
Dynamic Initialization Assigning value at runtime. int sum = a + b;
โ–ถ Variables and Constants Example
#include <iostream>
using namespace std;

// Global variable
int globalVar = 100;

int main() {
    // Local variables
    int localVar = 50;
    
    // Constants
    const int MAX_VALUE = 1000;
    const float PI = 3.14159;
    
    // Variable initialization
    int a = 10, b = 20;
    int sum = a + b;  // Dynamic initialization
    
    cout << "Global variable: " << globalVar << endl;
    cout << "Local variable: " << localVar << endl;
    cout << "Constant MAX_VALUE: " << MAX_VALUE << endl;
    cout << "Sum: " << sum << endl;
    
    // Scope demonstration
    {
        int blockVar = 75;
        cout << "Block variable: " << blockVar << endl;
    }
    // blockVar is not accessible here
    
    // MAX_VALUE = 2000; // Error: cannot modify const
    
    return 0;
}
Click "Run Code" to execute

4.3 Data Types and Operators

Different types of data and operations you can perform on them.

Aspect Definition Example
Data Types Define the type of data a variable holds. int, float, char, bool
Arithmetic Operators Perform mathematical operations. +, -, *, /, %
Relational Operators Compare values. >, <, ==, !=
Logical Operators Combine conditions. &&, ||, !
Assignment Operators Assign values. =, +=, -=, *=, /=
โ–ถ Operators Example
#include <iostream>
using namespace std;

int main() {
    int a = 10, b = 3;
    
    // Arithmetic operators
    cout << "Arithmetic Operators:" << endl;
    cout << "a + b = " << (a + b) << endl;
    cout << "a - b = " << (a - b) << endl;
    cout << "a * b = " << (a * b) << endl;
    cout << "a / b = " << (a / b) << endl;
    cout << "a % b = " << (a % b) << endl;
    
    // Relational operators
    cout << endl << "Relational Operators:" << endl;
    cout << "a > b: " << (a > b) << endl;
    cout << "a < b: " << (a < b) << endl;
    cout << "a == b: " << (a == b) << endl;
    cout << "a != b: " << (a != b) << endl;
    
    // Logical operators
    bool x = true, y = false;
    cout << endl << "Logical Operators:" << endl;
    cout << "x && y: " << (x && y) << endl;
    cout << "x || y: " << (x || y) << endl;
    cout << "!x: " << (!x) << endl;
    
    // Assignment operators
    int c = 5;
    cout << endl << "Assignment Operators:" << endl;
    cout << "c = " << c << endl;
    c += 3;
    cout << "After c += 3: " << c << endl;
    c *= 2;
    cout << "After c *= 2: " << c << endl;
    
    // Increment/Decrement
    cout << endl << "Increment/Decrement:" << endl;
    cout << "c++: " << c++ << endl;
    cout << "After c++: " << c << endl;
    cout << "++c: " << ++c << endl;
    
    return 0;
}
Click "Run Code" to execute

4.4 Control Statements (If, Else, Loops, Switch)

Control the flow of program execution based on conditions.

Aspect Definition Example
If Statement Executes code block if condition is true. if (x > 0) { cout << "Positive"; }
Else Statement Executes code block if condition is false. else { cout << "Negative"; }
Loops Repeats code while a condition is true. for, while, do-while
Switch Statement Executes code based on matching cases. switch(choice) { case 1: ... }
Break and Continue break exits loop; continue skips iteration. break; continue;
โ–ถ If-Else Statement Example
#include <iostream>
using namespace std;

int main() {
    int number = 369;
    
    // If-else statement
    if (number > 0) {
        cout << number << " is positive" << endl;
    } else if (number < 0) {
        cout << number << " is negative" << endl;
    } else {
        cout << number << " is zero" << endl;
    }
    
    // Nested if
    int age = 25;
    if (age >= 18) {
        if (age >= 65) {
            cout << "Senior citizen" << endl;
        } else {
            cout << "Adult" << endl;
        }
    } else {
        cout << "Minor" << endl;
    }
    
    // Ternary operator
    int max = (10 > 5) ? 10 : 5;
    cout << "Maximum: " << max << endl;
    
    return 0;
}
Click "Run Code" to execute
โ–ถ Loops Example
#include <iostream>
using namespace std;

int main() {
    // For loop
    cout << "For loop:" << endl;
    for (int i = 1; i <= 5; i++) {
        cout << i << " ";
    }
    cout << endl;
    
    // While loop
    cout << endl << "While loop:" << endl;
    int j = 1;
    while (j <= 5) {
        cout << j << " ";
        j++;
    }
    cout << endl;
    
    // Do-while loop
    cout << endl << "Do-while loop:" << endl;
    int k = 1;
    do {
        cout << k << " ";
        k++;
    } while (k <= 5);
    cout << endl;
    
    // Nested loop
    cout << endl << "Nested loop (multiplication table):" << endl;
    for (int i = 1; i <= 3; i++) {
        for (int j = 1; j <= 3; j++) {
            cout << i * j << " ";
        }
        cout << endl;
    }
    
    // Break and continue
    cout << endl << "Break example:" << endl;
    for (int i = 1; i <= 10; i++) {
        if (i == 6) break;
        cout << i << " ";
    }
    
    cout << endl << endl << "Continue example:" << endl;
    for (int i = 1; i <= 10; i++) {
        if (i % 2 == 0) continue;  // Skip even numbers
        cout << i << " ";
    }
    cout << endl;
    
    return 0;
}
Click "Run Code" to execute
โ–ถ Switch Statement Example
#include <iostream>
using namespace std;

int main() {
    int choice = 2;
    
    cout << "Menu:" << endl;
    cout << "1. Tesla Model S" << endl;
    cout << "2. Tesla Model 3" << endl;
    cout << "3. Tesla Model X" << endl;
    cout << "4. Tesla Model Y" << endl;
    
    cout << endl << "Your choice: " << choice << endl;
    
    switch (choice) {
        case 1:
            cout << "You selected Model S - Luxury sedan" << endl;
            break;
        case 2:
            cout << "You selected Model 3 - Affordable sedan" << endl;
            break;
        case 3:
            cout << "You selected Model X - SUV with falcon doors" << endl;
            break;
        case 4:
            cout << "You selected Model Y - Compact SUV" << endl;
            break;
        default:
            cout << "Invalid choice!" << endl;
    }
    
    // Switch with char
    char grade = 'A';
    switch (grade) {
        case 'A':
            cout << endl << "Excellent!" << endl;
            break;
        case 'B':
            cout << "Good!" << endl;
            break;
        case 'C':
            cout << "Average" << endl;
            break;
        default:
            cout << "Keep trying!" << endl;
    }
    
    return 0;
}
Click "Run Code" to execute

๐Ÿ’ก Practice Exercise

Practice C++ basics with these exercises:

  • Write a program to check if a number is even or odd
  • Create a calculator using switch statement
  • Print the Fibonacci series using loops
  • Find the largest of three numbers using if-else
  • Create a pattern using nested loops