Lesson 04-C++ Control Structures

Simple Statements and Compound Statements

Simple Statements

Simple statements typically contain only one operation, such as assignment, declaration, input/output, etc.

  • Declaration Statement: Used to declare variables or functions.
int a;  // Declare an integer variable
  • Assignment Statement: Assign a value to a variable.
a = 10;  // Assign the value 10 to variable a
  • Expression Statement: Execute an expression.
a++;  // Expression statement, increment a by 1
  • Input/Output Statements: Read or output data.
std::cout << "Hello, world!" << std::endl;  // Output statement
  • Control Statements: Such as if statement, for loop, etc.
if (a > 0) {
    std::cout << "a is positive." << std::endl;
}
#include <iostream>

int main() {
    // Declaration statement
    int a = 10;

    // Assignment statement
    a = 20;

    // Output statement
    std::cout << "a = " << a << std::endl;

    return 0;
}

Compound Statements

A compound statement is a block of multiple simple statements, usually enclosed in curly braces {}.

Syntax:

{
    // List of simple statements
}

Purpose:

  • Combine multiple simple statements into a single unit.
  • Create a local scope where variables defined are only valid within the compound statement.
  • Control statements such as if, for, while, etc., can be used inside compound statements.
#include <iostream>

int main() {
    // Compound statement
    {
        int x = 5;
        int y = 10;
        int sum = x + y;
        std::cout << "Sum = " << sum << std::endl;
    }

    return 0;
}

Declaration Statements

Declaration statements are used to define variables or function prototypes. Here we focus only on variable declarations.

Syntax:

type identifier;

or

type identifier = value;

Examples:

int number;      // Declare an integer variable
double price = 9.99;  // Declare a floating-point variable and initialize it
#include <iostream>

int main() {
    // Declare an integer variable
    int age = 25;
    
    // Declare a floating-point variable
    double pi = 3.14159;

    // Output the values of the variables
    std::cout << "Age: " << age << ", PI: " << pi << std::endl;

    return 0;
}

if Statement

The if statement is used to execute different code paths based on a condition.

Syntax:

if (condition) {
    // Statements to execute
} else if (another_condition) {
    // Statements to execute
} else {
    // Statements to execute
}

Explanation:

  • condition is a boolean expression; the corresponding code block is executed when it evaluates to true.
  • else if and else are optional.
#include <iostream>

int main() {
    int score = 85;

    if (score >= 90) {
        std::cout << "Excellent" << std::endl;
    } else if (score >= 70) {
        std::cout << "Good" << std::endl;
    } else {
        std::cout << "Fail" << std::endl;
    }

    return 0;
}

In an if statement, the else and else if branches can be omitted.

switch Statement

The switch statement is used to execute different code blocks based on the value of an expression.

#include <iostream>

int main() {
    char grade = 'B';

    switch (grade) {
        case 'A':
            std::cout << "Excellent" << std::endl;
            break;
        case 'B':
            std::cout << "Good" << std::endl;
            break;
        case 'C':
            std::cout << "Pass" << std::endl;
            break;
        default:
            std::cout << "Fail" << std::endl;
    }

    return 0;
}

Info

In a switch statement, if there is no break statement, execution will continue to the next case block until a break is encountered or the switch statement ends. The default branch in a switch statement is optional; if no case matches, the default branch is executed.

for Statement

The for statement is one of the most commonly used loop structures. It allows you to initialize a variable before the loop, update it after each iteration, and check a condition before each iteration.

#include <iostream>

int main() {
    for (int i = 0; i < 5; ++i) {
        std::cout << "Count: " << i << std::endl;
    }

    return 0;
}

while Statement

The while statement checks a condition before each iteration and executes the loop body only if the condition is true.

#include <iostream>

int main() {
    int count = 0;
    while (count < 5) {
        std::cout << "Count: " << count << std::endl;
        ++count;
    }

    return 0;
}

do while Statement

The do-while statement executes the loop body at least once, then checks the condition after each iteration.

#include <iostream>

int main() {
    int count = 0;
    do {
        std::cout << "Count: " << count << std::endl;
        ++count;
    } while (count < 5);

    return 0;
}

break Statement

The break statement is used to immediately exit a loop or switch statement.

#include <iostream>

int main() {
    for (int i = 0; i < 10; ++i) {
        if (i == 5) {
            break;
        }
        std::cout << "Count: " << i << std::endl;
    }

    return 0;
}

continue Statement

The continue statement is used to skip the rest of the current loop iteration and proceed to the next iteration.

#include <iostream>

int main() {
    for (int i = 0; i < 10; ++i) {
        if (i % 2 == 0) {
            continue;
        }
        std::cout << "Odd number: " << i << std::endl;
    }

    return 0;
}

goto Statement

The goto statement allows unconditional jumping to another labeled location in the program. Although it can be useful in some cases, it is generally avoided in modern programming practice because it can make code difficult to understand and maintain.

#include <iostream>

int main() {
    int i = 0;
start:
    std::cout << "Count: " << i << std::endl;
    ++i;
    if (i < 5) {
        goto start;
    }

    return 0;
}

Linked List

A linked list is a common data structure consisting of a series of nodes, where each node contains data and a pointer to the next node.

Node Definition

First, define a node class that includes a data member and a pointer to the next node.

template<typename T>
class ListNode {
public:
    T data;
    ListNode<T>* next;

    ListNode(const T& value) : data(value), next(nullptr) {}
};

Linked List Class Definition

Next, define a linked list class that includes a head node pointer and provides some basic operations.

Example Code

template<typename T>
class LinkedList {
private:
    ListNode<T>* head;

public:
    LinkedList() : head(nullptr) {}

    ~LinkedList() {
        clear();
    }

    void insertFront(const T& value);
    void insertBack(const T& value);
    bool remove(const T& value);
    void clear();
    void printList() const;
};

template<typename T>
void LinkedList<T>::insertFront(const T& value) {
    ListNode<T>* newNode = new ListNode<T>(value);
    newNode->next = head;
    head = newNode;
}

template<typename T>
void LinkedList<T>::insertBack(const T& value) {
    ListNode<T>* newNode = new ListNode<T>(value);
    if (!head) {
        head = newNode;
    } else {
        ListNode<T>* current = head;
        while (current->next) {
            current = current->next;
        }
        current->next = newNode;
    }
}

template<typename T>
bool LinkedList<T>::remove(const T& value) {
    ListNode<T>* current = head;
    ListNode<T>* previous = nullptr;

    while (current && current->data != value) {
        previous = current;
        current = current->next;
    }

    if (!current) {
        return false;
    }

    if (previous) {
        previous->next = current->next;
    } else {
        head = current->next;
    }

    delete current;
    return true;
}

template<typename T>
void LinkedList<T>::clear() {
    ListNode<T>* current = head;
    while (current) {
        ListNode<T>* next = current->next;
        delete current;
        current = next;
    }
    head = nullptr;
}

template<typename T>
void LinkedList<T>::printList() const {
    ListNode<T>* current = head;
    while (current) {
        std::cout << current->data << " ";
        current = current->next;
    }
    std::cout << std::endl;
}

Using the Linked List

Now we can create an instance of the linked list and use the methods defined above to manipulate it.

#include <iostream>

int main() {
    LinkedList<int> list;

    list.insertFront(10);
    list.insertFront(20);
    list.insertBack(30);
    list.insertBack(40);

    std::cout << "Original list: ";
    list.printList();

    list.remove(20);
    std::cout << "After removing 20: ";
    list.printList();

    list.clear();
    std::cout << "After clearing the list: ";
    list.printList();

    return 0;
}

Share your love