Agenda

Today's plan:

  • Practice Exercises
    • Practice 1: Hello + Comments
    • Practice 2: Fix the Code
    • Practice 3: Declare and Print Variables
    • Practice 4: Read a Name and Age
    • Practice 5: Basic Arithmetic
    • Practice 6: for Loop Sum 1..N
    • Practice 7: while Loop Countdown
    • Practice 8: Functions and Prototypes
  • Performance Timing
    • Compare Execution Time: C++
    • Compare Execution Time: Python
  • Arrays and Strings in C++
  • Pointers and Memory in C++

Practice 1: Hello + Comments

  • Print "Hello, World!"
  • On a new line, print "C++ is fun!"
  • Include one single-line comment and one multi-line comment
#include <iostream>

  int main() {
      // TODO: print "Hello, World!"
      // TODO: print "C++ is fun!" on a new line
      /* TODO: add a multi-line comment */
      return 0;
  }

Practice 2: Fix the Code

The code below has errors. Fix it so it compiles and prints "Hi!".

int main() {
      cout << "Hi!"
      return 0
  }

Practice 3: Declare and Print Variables

Declare and initialize, then print on separate lines with labels:

  • int year = 2025;
  • double price = 19.99;
  • char grade = 'A';
  • bool isStudent = true;
  • std::string city = "Tokyo";
#include <iostream>
  #include <string>

  int main() {
      // TODO: declare variables as specified
      // TODO: print each with a label (e.g., "Year: 2025")
      return 0;
  }

Practice 4: Read a Name and Age

Read a first name (no spaces) and an integer age, then print:

Hello, <name>! You are <age> years old.

#include <iostream>
  #include <string>

  int main() {
      // TODO: read name and age using std::cin
      // TODO: print the greeting line
      return 0;
  }

Practice 5: Basic Arithmetic

Read two integers a and b. Compute and print:

  • Sum (a + b)
  • Difference (a - b)
  • Product (a * b)
  • Quotient (a / b)
  • Remainder (a % b)

Print clear labels for each result.

#include <iostream>

  int main() {
      // TODO: read a and b
      // TODO: compute and print all five results with labels
      return 0;
  }

Practice 6: for Loop Sum 1..N

Read N (assume N >= 1). Use a for loop to compute and print the sum from 1 to N.

#include <iostream>

  int main() {
      // TODO: read N
      // TODO: sum 1..N using a for loop and print the sum
      return 0;
  }

Practice 7: while Loop Countdown

Read N (assume N >= 1). Use a while loop to print a countdown from N to 1, separated by spaces. End with a newline.

#include <iostream>

  int main() {
      // TODO: read N
      // TODO: print N N-1 ... 1 using a while loop
      return 0;
  }

Practice 8: Functions and Prototypes

Write a function that returns the larger of two ints:

int max2(int a, int b)

  • Place a function prototype before main.
  • Define the function after main.
  • In main, read two ints, call max2, and print "Max is: <result>".
#include <iostream>

  // TODO: write prototype: int max2(int a, int b);

  int main() {
      // TODO: read two integers
      // TODO: call max2 and print the result
      return 0;
  }

  // TODO: write definition of max2 here

Compare Execution Time: C++

Minimal, runnable example that does simple work (sum in a for-loop) and prints elapsed time at the end. Adjust N to fit your demo time.

Compile and run (use optimizations to reflect real C++ performance):

g++ -O3 -std=c++17 main.cpp -o loop && ./loop

  • Keep all printing outside the timed region.
  • Use a reasonably large N (e.g., 10 million).
  • Results vary by hardware/settings; ensure you build with -O3.
#include <chrono>
  #include <iostream>
  int main() {
      const long long N = 10'000'000; // adjust as desired
      auto start = std::chrono::high_resolution_clock::now();
      long long s = 0;
      for (long long i = 0; i < N; ++i) {
          s += i; // simple work per iteration
      }
      auto end = std::chrono::high_resolution_clock::now();
      std::chrono::duration<double> elapsed = end - start;
      std::cout << "N=" << N << ", sum=" << s << ", time=" << elapsed.count() << " s\n";
      return 0;
  }

Compare Execution Time: Python

Same task as C++: simple sum in a for-loop with identical N.

Run: python loop.py

  • Keep all printing outside the timed region.
  • Use a reasonably large N (e.g., 10 million). In CPython this may take several seconds.
  • Results vary by hardware and settings.
import time
  N = 10_000_000  # adjust as desired
  start = time.perf_counter()
  s = 0
  for i in range(N):
      s += i  # same work per iteration
  elapsed = time.perf_counter() - start
  print(f"N={N}, sum={s}, time={elapsed:.6f} s")

Arrays and Strings in C++

Working with Collections of Data

What is an Array?

An array is a data structure that stores a fixed-size sequential collection of elements of the same type.

Declaring an Array

To declare an array, you specify the type of the elements and the number of elements the array will hold.

type arrayName[arraySize];

Array Declaration Example

This code declares an array of 5 integers.

int numbers[5];

Initializing an Array

You can initialize an array at the time of declaration.

Array Initialization Example

This code declares and initializes an array of 5 integers.

int numbers[5] = {10, 20, 30, 40, 50};

Accessing Array Elements

You can access individual elements of an array using their index. Array indices start at 0.

Accessing Elements Example

This code accesses the third element of the array.

int numbers[5] = {10, 20, 30, 40, 50};
  int thirdNumber = numbers[2]; // thirdNumber will be 30

Iterating Through an Array

You can use a for loop to iterate through the elements of an array.

Iterating Example

This code prints all the elements of an array.

#include <iostream>
  int main() {
      int numbers[5] = {10, 20, 30, 40, 50};
      for (int i = 0; i < 5; ++i) {
          std::cout << numbers[i] << " ";
      }
      return 0;
  }

Engineering Example: Applying a Function

In engineering, you often need to apply a mathematical function (like sin, log, sqrt) to a whole set of data points (e.g., sensor readings).

You can't do sin(my_array) directly. You must iterate through the array and apply the function to each element individually.

// Apply sin() to each element of an array
  #include <iostream>
  #include <cmath> // Required for sin()

  int main() {
      // Array of angles in radians
      double angles[] = {0.0, 0.52, 0.785, 1.57};
      const int num_elements = 4;
      double sin_values[num_elements];

      // Calculate sin for each element
      for (int i = 0; i < num_elements; ++i) {
          sin_values[i] = std::sin(angles[i]);
      }

      // Print the results
      for (int i = 0; i < num_elements; ++i) {
          std::cout << "sin(" << angles[i] << ") = " 
                    << sin_values[i] << std::endl;
      }
      return 0;
  }

Engineering Example: Element-wise Operations

Element-wise multiplication is common for tasks like applying calibration constants or scaling sensor data.

This involves creating a new array where each element is the product of the corresponding elements from two other arrays.

// Multiply two arrays element by element
  #include <iostream>

  int main() {
      const int SIZE = 5;
      // Raw sensor readings
      int readings[SIZE] = {101, 120, 95, 210, 150};
      // Calibration factors
      double factors[SIZE] = {0.5, 0.48, 0.51, 0.49, 0.5};
      // Calibrated results
      double calibrated[SIZE];

      for (int i = 0; i < SIZE; ++i) {
          calibrated[i] = readings[i] * factors[i];
      }
      
      std::cout << "Calibrated Values: ";
      for (int i = 0; i < SIZE; ++i) {
          std::cout << calibrated[i] << " ";
      }
      return 0;
  }

C-Style Strings

In C, strings are represented as arrays of characters, terminated by a null character (\0).

C-Style String Example

This code declares a C-style string.

char greeting[] = "Hello";

C++ `std::string`

C++ provides a more powerful and flexible std::string class for working with strings. It is generally recommended to use std::string over C-style strings.

`std::string` Example

This code uses the std::string class.

#include <iostream>
  #include <string>
  int main() {
      std::string greeting = "Hello, C++!";
      std::cout << greeting;
      return 0;
  }

Pointers and Memory in C++

Understanding Memory Addresses

What is a Pointer?

A pointer is a variable that stores the memory address of another variable. Pointers are a powerful feature of C++, but they must be used with care.

Declaring a Pointer

To declare a pointer, you use the * operator.

type *pointerName;

Pointer Declaration Example

This code declares a pointer to an integer.

int *p;

The Address-Of Operator (`&`)

The address-of operator (&) returns the memory address of a variable.

Getting an Address

This code gets the memory address of the myVar variable and stores it in the pointer p.

int myVar = 42;
  int *p = &myVar;

Visualizing Pointers and Memory

It helps to think of memory as a series of mailboxes. Each has a unique address.

  • myVar is a "mailbox" at address 0x7ffee.... Its content is the integer 42.
  • p is another "mailbox" at a different address. Its content is the address of myVar, not its value.

Variable Address Value
myVar 0x7ffee1db458c 42
p 0x7ffee1db4580 0x7ffee1db458c

The Dereference Operator (`*`)

The dereference operator (*) is used to access the value stored at the memory address held by a pointer.

You can think of it as "following the pointer" to its target.

Dereferencing a Pointer

This code prints the value of myVar by dereferencing the pointer p.

#include <iostream>
  int main() {
      int myVar = 42;
      int *p = &myVar;
      std::cout << *p; // Prints 42
      return 0;
  }

Modifying Data via Pointer

Dereferencing also allows you to change the value at the pointer's address. This is a key feature.

#include <iostream>
  int main() {
      int myVar = 42;
      int *p = &myVar;

      std::cout << "Original value: " << myVar << std::endl; // 42

      *p = 99; // "Go to the address p is pointing to, and set its value to 99"

      std::cout << "New value: " << myVar << std::endl; // 99!
      return 0;
  }

Null Pointers

A null pointer is a pointer that does not point to any memory address. It's good practice to initialize pointers to nullptr if you don't have a valid address for them yet.

Null Pointer Example

This code declares a null pointer. Dereferencing a null pointer will cause a crash!

int *p = nullptr;

  if (p != nullptr) {
      // It is safe to dereference p here
      std::cout << *p; 
  }

Pointers and Arrays

The name of an array is actually a pointer to the first element of the array.

Pointers and Arrays Example

This code shows how an array name can be used as a pointer.

#include <iostream>
  int main() {
      int numbers[5] = {10, 20, 30, 40, 50};
      int *p = numbers; // p points to numbers[0]
      std::cout << *p; // Prints 10
      return 0;
  }

Pointer Arithmetic

You can use arithmetic operators (like + and ++) to move a pointer. The compiler is smart: p++ moves the pointer forward by `sizeof(type)` bytes, not just one byte.

int numbers[5] = {10, 20, 30, 40, 50};
  int *p = numbers; // p points to 10

  p++; // p now points to 20
  std::cout << *p << std::endl; // Prints 20

  p = p + 2; // p now points to 40
  std::cout << *p << std::endl; // Prints 40

  // Accessing elements:
  std::cout << *(numbers + 3); // Prints 40. Same as numbers[3]