Object-oriented scientific programming with C++¶

Matthias Möller, Jonas Thies (Numerical Analysis, DIAM)

Lecture 1 - 11 November 2026

Who of you is using AI?

Who of you is using AI for programming?

How do you use AI for programming?

This course is about programming; with and without AI.

What you will learn in this course¶

  1. How to write (simple) programs in modern C++
  2. How to use AI agents to generate more complex C++ codes
  3. How to assess code quality and debug code written by humans and AI agents
  4. How to refactor code for human readability and maintainability

What this means and what it does not mean¶

You are in the lead and fully responsible for the result.

You use AI as a tool like a debugger or profiler to develop C++ codes (hopefully faster).

You still understand what you are doing (= deep knowledge of C++ concepts).

Example¶

Problem statement: We want to calculate the L2-norm of a vector

Prompt: Write a C++ program that computes the L2-norm of a vector

Result from Gemini Pro 3.1¶

Gemini explanation: Here is a clean, modern C++ implementation using std::valarray / std::vector and std::hypot (or std::inner_product) from standard headers. Using std::hypot is the most numerically stable method because it avoids unwanted underflow or overflow when squaring very small or very large numbers.

#include <iostream>
#include <vector>
#include <numeric>
#include <cmath>

// Computes the L2-norm (Euclidean norm) of a vector using std::hypot
template <typename T>
double compute_l2_norm(const std::vector<T>& vec) {
    // std::hypot with std::accumulate ensures numerical stability
    return std::accumulate(vec.begin(), vec.end(), 0.0, [](double acc, T val) {
        return std::hypot(acc, val);
    });
}

int main() {
    std::vector<double> vec = {3.0, 4.0, 12.0};

    double norm = compute_l2_norm(vec);

    std::cout << "Vector: [3.0, 4.0, 12.0]\n";
    std::cout << "L2-norm: " << norm << std::endl; // Output: 13

    return 0;
}

Result from Gemini Pro 3.1 - alternative¶

Gemini explanation: If performance is a higher priority than extreme numerical stability, you can use std::inner_product with std::sqrt.

#include <iostream>
#include <vector>
#include <numeric>
#include <cmath>

template <typename T>
double compute_l2_norm_fast(const std::vector<T>& vec) {
    double sum_of_squares = std::inner_product(vec.begin(), vec.end(), vec.begin(), 0.0);
    return std::sqrt(sum_of_squares);
}

int main() {
    std::vector<double> vec = {3.0, 4.0, 12.0};

    double norm = compute_l2_norm(vec);

    std::cout << "Vector: [3.0, 4.0, 12.0]\n";
    std::cout << "L2-norm: " << norm << std::endl; // Output: 13

    return 0;
}

Prompt: How can I optimize the C++ L2-norm computation using SIMD or C++20 parallel algorithms?

Result from Gemini Pro 3.1 - performance optimized¶

Gemini explanation: Standard C++ provides built-in parallel algorithms via standard execution policies (std::execution::par or std::execution::par_unseq). This automatically distributes the work across available CPU threads without requiring third-party libraries.

#include <iostream>
#include <vector>
#include <numeric>
#include <cmath>
#include <execution> // Required for execution policies

double l2_norm_parallel(const std::vector<double>& vec) {
    // std::transform_reduce scales across threads and auto-vectorizes
    double sum_of_squares = std::transform_reduce(
        std::execution::par_unseq, // Enables parallel execution and SIMD vectorization
        vec.begin(), vec.end(),
        0.0,
        std::plus<double>{},
        [](double x) { return x * x; }
    );

    return std::sqrt(sum_of_squares);
}

int main() {
    std::vector<double> data(100'000'000, 2.5); // 100M elements
    
    double norm = l2_norm_parallel(data);
    std::cout << "L2-Norm: " << norm << "\n";
    
    return 0;
}

Remark: With Clang++ this code requires the -fexperimental-library flag.

What we can learn from this first example¶

  1. With a generic prompt, AI generates rather random solutions
    • Did you expect to use std::accumulate and std::hypot in your first C++ code?
  2. AI can propose quite advanced solutions.
    • Do you really understand every detail of the AI generated codes?
    • Are you still in the lead and can take full responsibility?
  3. AI solutions can be wrong.
    • Do you know how to check this?
  4. AI solutions might be overkill.
    • Do you understand what 'parallel execution and SIMD vectorization' means?

Key message: Write detailed prompts that very clearly express what you want. But for this you first need to know what you want.

Educational approach of this course¶

  1. Start from a concrete problem.
  2. Write a meaningful prompt to instruct your AI agent to generate C++ code the way you want it to be.
  3. Understand the code in all details. Use AI as your personal tutor to explain unknown concepts.
  4. Iterate with your AI agent to generate the code in exactly the way you want it to be.

This way, you will learn C++ concepts (knowledge) and develop experience in using AI for software development (practical skills).

Generative AI & Coding agents¶

Large language models (LLMs) are trained on natural language, source code, documentation, and other text.

Code is treated much like a language: the model learns syntax, programming idioms, APIs, algorithms, and relationships between code and natural-language descriptions.

Given a prompt and context, the model predicts the next token (word or code fragment) repeatedly to construct an answer.

Generation is probabilistic: the model produces plausible code, not necessarily correct code.

Modern coding agents go beyond generation: they can inspect existing code, generate and modify files, compile/run programs, interpret errors, test, and iteratively improve their solution.

Key message: AI-generated code should be treated as a proposed solution that must be understood, tested, and validated.

Primers¶

We provide primers (= the first prompt that you provide to your AI agent at the start of a new session/new chat) for each lecture.

These primers define the capabilities of the AI agent and tell it what type of solutions it should propose.

The capabilities of the AI agent will increase over time, i.e., the proposed solutions will become more and more advanced aligned with your learning progress.

We cannot control whether you use the primers or not. However, the primers are there for good reasons. This course is not about producing the best code with minimal effort. It is about learning C++ in a modern didactic way.

Course information¶

  • Lectures (nonobligatory)

    • weeks 2.1-2.8, Wed 13:45-15:45 in lecture hall Boole (36.HB.T0.610)
  • Lab sessions (nonobligatory)

    • weeks 2.2-2.8, Tue 8:45-12:45 in IDE Ctrl and Enter (32.D-0-040/120)
    • this is the time and place to ask your questions (no office hours! no reply to emails! no reply to discussion forums!)
  • WebLab (https://weblab.tudelft.nl/tw3720tu-wi4771tu/2026-2027)
    • weekly demos and self-study exercises become available on Monday morning
    • computer exams on 15 December 2026 and 19 January 2027 (both mandatory)
  • Assessment (3 ECTS)
    • Weekly self-study exercises (formative feedback, no grade)
    • Two 3h closed-book computer exams on 15 Dec 2026 (50% of the grade) and 27 Jan 2027 (50% of the grade)
    • Final grade = 0.5 * computer exam 1 + 0.5 * computer exam 2
    • A passing final grade for the course can only be earned when for all components at least a 5.0 is earned, and the weighted final grade is at least a 5.8.
    • Computer exams will consist of programming tasks, open questions and multiple choice questions
      • programming tasks are checked against unit tests; you can submit at any time and as often as you wish and receive immediate feedback
      • open questions are checked by examinors based on answer models after the exam
    • Closed-book exam means that you have no access to AI or the internet; we test your knowledge

Let's get started¶

You can use Gemini Pro 3.1 through TU Delft.

Go to: https://gemini.google.com/

Login with NetID@g-tudelft.nl

For each lecture we have lecture notes which cover the material discussed during the lecture plus additional exercises for self study.

Block A: Estimating $\pi$ with the Leibniz series¶

The Leibniz formula is the alternating series

$$ \frac{\pi}{4} = \sum_{k=0}^{\infty} \frac{(-1)^k}{2k+1} = 1-\frac{1}{3}+\frac{1}{5}-\frac{1}{7}+\frac{1}{9}-\dots $$

Task: Develop a C++ program that estimates $\pi$ with the Leibniz series and, on the way, learn the basic concepts of C++

Your turn during the first lab session¶

  1. Download the primer for lecture 1 and provide it to your AI agent
  2. Think about a meaningful prompt ...

Step A.1: Get the program to run and announce itself¶

Prompt: Build a small command-line tool that estimates $\pi$ using the Leibniz series. For now, just write the program so that it prints a header line: "Leibniz pi estimator — v0.1". It should compile and run as a complete C++ program.

#include <iostream>

int main() { 
    std::cout << "Leibniz pi estimator -- v0.1" << std::endl; 
    return 0; 
}

Header files¶

Extra functionality provided by the standard C++ library is defined in so-called header files which need to be included via

#include <headerfile>

Some useful header files are

  • <iostream> : input/output
  • <string> : string types
  • <complex> : complex numbers
  • Good overview: http://www.cplusplus.com

We will develop our own header files later in this course as well.

THE main function¶

Now let's only focus on the main function

Each C++ program must provide one (and only one!) main function which is the designated start of the program.

Syntax:

int main() { body }

or

int main(int argc, char* argv[]) { body }
  • Scope of the main function is { body }
  • Return type of the main function is int (=integer), e.g., return 0;
  • The main function cannot be called recursively

Standard output¶

Stream-based output system

#include <iostream>

std::cout << "Leibniz pi estimator -- v0.1" << std::endl;

Streams can be easily concatenated

In [2]:
#include <iostream>

std::cout << "Leibniz pi estimator" << " -- " << "v0.1" << std::endl;
Leibniz pi estimator -- v0.1

Streams are part of the standard C++ library and therefore encapsulated in the namespace std.

Instead of using std:: one can also import all functionality from the namespace std by

In [3]:
using namespace std;
cout << "Leibniz pi estimator -- v0.1" << endl;
Leibniz pi estimator -- v0.1

Predefined output streams

  • std::cout : standard output stream
  • std::cerr : standard output stream for errors
  • std::clog : standard output stream for logging

Step A.2: Output a first, crude estimate¶

Prompt: Extend the tool so that after the header it prints a first-order estimate of $\pi$, obtained by keeping only the first term of the Leibniz series (so $4 \times 1 = 4$). Store the value in a variable so we can build on it later

#include <iostream> 

int main() { 
    std::cout << "Leibniz pi estimator -- v0.1" << std::endl; 

    double estimate = 4.0 * 1.0; 
    std::cout << "Estimate (1 term): " << estimate << std::endl; 

    return 0; 
}

Variables¶

C++ is case sensitive and typed, that is, variables and constants have a value and a concrete type

In [4]:
double estimate = 4.0 * 1.0; // create double-valued variable and initialize it to 4.0 * 1.0
estimate = 15.0;             // update the value of the variable to 15.0
Out[4]:
15.000000

Initialization of variables¶

Variables can be initialized during their definition and at any location later in the code

In [5]:
int var1 = 10;   // copy initialization
int var2(20);    // direct initialization
int var3 = {20}; // list initialization
int var4{20};    // list initialization (preferred modern style)
int var5;        // only definition (arbitrary value!)
var5 = 20;       // assignment of value
Out[5]:
20

Intermezzo: Terminology¶

A declaration introduces the name of the variable or constant, and describes its type but does not create it

extern int var;

A definition instantiates it (=creates it)

int var;

An initialization initializes it (=assigns a value to it)

c+
var = 10;

All three steps can be combined, e.g., int var{10} or split across different source/header files (later in this course)

Scope of variables¶

Variables are only visible in their scope

int main() {
    int a = 10;  // variable a is visible here
    
    {
      int b = a; // variables a and b are visible here
    }
    
    {
      int c = b; // variables a and c are visible here, b is not(!) visible here -> error
    }            
}

Another example

int main() {
    int a = 10;   // variable a is visible here
    
    {
      int a = 20; // new variable a only visible in inner
                  // scope, interrupts scope of outer-scope a
      std::cout << a << std::endl; // is 20
    }
    
    std::cout << a << std::endl;   // is 10
}

C++ standard types¶

Group Type name Notes on size / precision
Character types char Exactly one byte in size. At least 8 bits.
char16_t Not smaller than char. At least 16 bits.
char32_t Not smaller than char16_t. At least 32 bits.
Integer types (signed and unsigned) (un)signed char Same size as char. At least 8 bits.
(un)signed short int Not smaller than char. At least 16 bits.
(un)signed int Not smaller than short. At least 16 bits.
(un)signed long int Not smaller than int. At least 32 bits.
(un)signed long long int Not smaller than long. At least 64 bits.
Floating-point type float Precision not less than float
double Precision not less than float
long double Precision not less than double
Boolean type bool

Step A.3: Add the second term¶

Prompt: Now refine the estimate by including the second term of the series: $\pi \approx 4 \times (1 - \frac13)$. Compute it using two separate variables for the two terms, then print the new estimate next to the previous one so we can see the improvement. Use integer variables for the two terms, since the indices of the series are integers.

#include <iostream> 

int main() { 
    std::cout << "Leibniz pi estimator -- v0.1" << std::endl; 

    int t1 = 1; 
    int t2 = 1 / 3; 
    double estimate = 4.0 * (t1 - t2); 

    std::cout << "Estimate (1 term):  " << 4.0 << std::endl; 
    std::cout << "Estimate (2 terms): " << estimate << std::endl; 
    
    return 0; 
}

Prompt: Replace the integers used to calculate the second term with doubles.

#include <iostream> 

int main() { 
    std::cout << "Leibniz pi estimator -- v0.1" << std::endl; 

    int t1 = 1; 
    double t2 = 1.0 / 3.0; 
    double estimate = 4.0 * (t1 - t2); 

    std::cout << "Estimate (1 term):  " << 4.0      << std::endl; 
    std::cout << "Estimate (2 terms): " << estimate << std::endl; 
  
    return 0; 
}

Step A.4: Report the error against a known value of $\pi$¶

Prompt: Add a high-precision reference value of $\pi$ (3.14159265358979) to the program and print the absolute error of each estimate against this reference. The reference value must not be modifiable anywhere in the code.

#include <iostream> 
  
int main() { 
    std::cout << "Leibniz pi estimator -- v0.1" << std::endl; 
  
    const double pi_ref = 3.14159265358979; 
  
    double t1 = 1.0; 
    double t2 = 1.0 / 3.0; 
  
    double est_1 = 4.0; 
    double est_2 = 4.0 * (t1 - t2); 
  
    std::cout << "Reference pi:       " << pi_ref << std::endl; 
    std::cout << "Estimate (1 term):  " << est_1 
              << "   error: " << pi_ref - est_1 << std::endl; 
    std::cout << "Estimate (2 terms): " << est_2 
              << "   error: " << pi_ref - est_2 << std::endl; 
  
    return 0; 
}

Initialization of constants¶

Constants must be initialized during their definition

In [6]:
const int con1 = 20;   // copy initialization
const int con2(20);    // direct initialization
const int con3 = {20}; // list initialization
const int con4{20};    // list initialization (preferred modern style)
In [7]:
const double constant = 20.0; // create double-valued constant and initialize it to 20.0

estimate = constant;
constant = estimate;
input_line_18:4:10: error: cannot assign to variable 'constant' with const-qualified type 'const double'
constant = estimate;
~~~~~~~~ ^
input_line_18:2:15: note: variable 'constant' declared const here
 const double constant = 20.0; // create double-valued constant and initialize it to 20.0
 ~~~~~~~~~~~~~^~~~~~~~~~~~~~~
Interpreter Error: 

Step A.5: Replace the hard-coded sum with a loop¶

Prompt: Rewrite the program so that the estimate is computed by a for loop that runs from k = 0 to k = N - 1 and adds each term (-1)^k / (2k + 1) to a running sum, which is then multiplied by 4. Use an int for the loop index k. Be careful that the division inside the term is done in floating-point arithmetic, not integer arithmetic. Set N to 1000 so we can see the estimate get closer to the reference.

#include <iostream> 
  
int main() { 
    std::cout << "Leibniz pi estimator -- v0.1" << std::endl; 
  
    const double pi_ref = 3.14159265358979; 
    const int    N      = 1000;     // number of terms used in the estimate 
  
    double sum = 0.0; 
    for (int k = 0; k < N; ++k) { 
        const double sign = (k % 2 == 0) ? 1.0 : -1.0; 
        const double term = sign / (2.0 * k + 1.0); 
        sum += term; 
    } 
    const double estimate = 4.0 * sum; 
  
    std::cout << "Using N = " << N << " terms" << std::endl; 
    std::cout << "Estimate: " << estimate 
              << "   error: " << pi_ref - estimate << std::endl; 
  
    return 0; 
}

For-loops¶

Syntax:

for (initialization; condition; iteration)
{
    statement(s);
}

If the iteration variable is defined during initialization, it is only visible inside the for-loop's body.

Example:

for (int k = 0; k < N; ++k) { 
        const double sign = (k % 2 == 0) ? 1.0 : -1.0; 
        const double term = sign / (2.0 * k + 1.0); 
        sum += term; 
    }

Conditional operator (ternary operators)¶

Syntax:

condition ? expression_if_true : expression_if_false

The conditional operator can be used inline to select between two cases based on a condition.

Example:

const double sign = (k % 2 == 0) ? 1.0 : -1.0;

Compound assignment operators¶

Syntax:

destination += source;

adds source to destination and stores the result in destination.

Example:

sum += term;

Step A.6: Refuse bad input by throwing an exception¶

Prompt: Before the loop starts, check whether N is at least 1. If it is not, signal an error using the C++ exception mechanism: throw a std::invalid_argument with a message that explains what went wrong. Include the <stdexcept> header. Do not catch it yet — we will do that in the next step. For now we just want the program to refuse to compute an estimate when N is not positive.

#include <iostream> 
#include <stdexcept> 
  
int main() { 
    std::cout << "Leibniz pi estimator -- v0.1" << std::endl; 
  
    const double pi_ref = 3.14159265358979; 
    const int    N      = 0;       
  
    if (N < 1) { 
        throw std::invalid_argument( 
            "N must be at least 1 (got a non-positive value)."); 
    }
  
    double sum = 0.0; 
    for (int k = 0; k < N; ++k) { 
        const double sign = (k % 2 == 0) ? 1.0 : -1.0; 
        const double term = sign / (2.0 * k + 1.0); 
        sum += term; 
    } 
    const double estimate = 4.0 * sum; 
  
    std::cout << "Using N = " << N << " terms" << std::endl; 
    std::cout << "Estimate: " << estimate 
              << "   error: " << pi_ref - estimate << std::endl; 
  
    return 0; 
}

Exceptions¶

Syntax:

throw exception_type("message")

throws (=sends) "message" in the form of an exception to the calling function.

Example:

throw std::invalid_argument( 
            "N must be at least 1 (got a non-positive value)."); 

If the exception is not caught by the calling function the program terminates immediately.

Step A.7: Catch the exception and fail gracefully¶

Prompt: Put the calculation inside a try block and add a catch (const std::exception& e) block that prints the error message returned by e.what() to std::cerr and makes main return a non-zero exit code. Catch by const reference, not by value, and catch std::exception (the common base class), not std::invalid_argument specifically — that way the same handler will work if we later throw a different exception type for a different kind of problem.

#include <iostream> 
#include <stdexcept> 
  
int main() { 
    std::cout << "Leibniz pi estimator -- v0.1" << std::endl; 
  
    const double pi_ref = 3.14159265358979; 
    const int    N      = 0;
  
    try { 
        if (N < 1) { 
            throw std::invalid_argument( 
                "N must be at least 1 (got a non-positive value)."); 
            } 
  
        double sum = 0.0; 
        for (int k = 0; k < N; ++k) { 
            const double sign = (k % 2 == 0) ? 1.0 : -1.0; 
            const double term = sign / (2.0 * k + 1.0); 
            sum += term; 
            } 
        const double estimate = 4.0 * sum; 
  
        std::cout << "Using N = " << N << " terms" << std::endl; 
        std::cout << "Estimate: " << estimate 
                  << "   error: " << pi_ref - estimate << std::endl; 
        } 
    catch (const std::exception& e) { 
        std::cerr << "Error: " << e.what() << std::endl; 
        return 1; 
    } 
  
    return 0; 
} 

Exception handling¶

Syntax:

try {
    call code that may throw an exception
}
catch (exception) {
    handle the situation when the exception has been thrown
}

Exception handling can range from simply stating to the user that an exception has been thrown to calling additional functions.

The message of the exception object e can be retrieved via e.what().

Block B: Refactoring the estimator into functions and namespaces¶

In this block we will stick to the same problem, but refactor the code into a separate function that is called from the main function.

Step B.1: Extract the sum into a function¶

Prompt: Define a function called leibniz_estimate that takes one integer parameter (the number of terms N) and returns a double - the estimated value of $\pi$. Move the loop and the input check from main into this function. Keep main responsible only for setting up N, calling the function inside a try block, printing the result, and handling exceptions. The function should be defined before main so we don't need a separate declaration.

#include <iostream> 
#include <stdexcept> 
  
double leibniz_estimate(int N) { 
    if (N < 1) { 
        throw std::invalid_argument( 
            "N must be at least 1 (got a non-positive value)."); 
    } 
  
    double sum = 0.0; 
    for (int k = 0; k < N; ++k) { 
        const double sign = (k % 2 == 0) ? 1.0 : -1.0; 
        sum += sign / (2.0 * k + 1.0); 
    } 
    return 4.0 * sum; 
} 
  
int main() { 
    std::cout << "Leibniz pi estimator -- v0.2" << std::endl; 
  
    const int N = 1000; 
  
    try { 
        const double estimate = leibniz_estimate(N); 
        std::cout << "Using N = " << N << " terms" << std::endl; 
        std::cout << "Estimate: " << estimate      << std::endl; 
    } 
    catch (const std::exception& e) { 
        std::cerr << "Error: " << e.what() << std::endl; 
        return 1; 
    } 
  
    return 0; 
}

Step B.2: Report the error through a reference parameter¶

Prompt: Extend leibniz_estimate so that it also reports the absolute error of its estimate against the reference value of $\pi$. The reference value of $\pi$ should live as a const double inside the function (3.14159265358979). Add a second parameter, double& error, that the function fills in with the absolute difference between the estimate and the reference. Include <cmath> for std::abs. In main, declare a double err; before the call and print it after.

#include <iostream> 
#include <stdexcept> 
#include <cmath> 
  
double leibniz_estimate(int N, double& error) { 
    if (N < 1) { 
        throw std::invalid_argument( 
            "N must be at least 1 (got a non-positive value)."); 
    } 
  
    const double pi_ref = 3.14159265358979; 
  
    double sum = 0.0; 
    for (int k = 0; k < N; ++k) { 
        const double sign = (k % 2 == 0) ? 1.0 : -1.0; 
        sum += sign / (2.0 * k + 1.0); 
    } 
    const double estimate = 4.0 * sum; 
  
    error = std::abs(pi_ref - estimate); 
    return estimate; 
} 
  
int main() { 
    std::cout << "Leibniz pi estimator -- v0.2" << std::endl; 
  
    const int N = 1000; 
  
    try { 
        double err; 
        const double estimate = leibniz_estimate(N, err); 
        std::cout << "Using N = " << N << " terms" << std::endl; 
        std::cout << "Estimate: " << estimate      << std::endl; 
        std::cout << "Error:    " << err           << std::endl; 
    } 
    catch (const std::exception& e) { 
        std::cerr << "Error: " << e.what() << std::endl; 
        return 1; 
    } 
  
    return 0; 
}

Quiz: What's the difference?¶

const int N = 1000;
double err; 

double leibniz_estimate(int N, double& error) { ... }

N is passed by value, i.e., function leibniz_estimate gets its own copy. Whatever the function does internally will not change the value in the calling scope.

err is passed by reference, i.e., function leibniz_estimate accesses the original memory location of the variable err defined in the calling scope. Changes made to variable error inside the function immediately affect the value of err. This feature can be used to "return" information from a function.

Think about:

  • What are advantage/disadvanatges of passing by value/by reference?
  • Can we combine the advantages of both? How?

Step B.3: Add a read-only printer with constant reference¶

Prompt: Add a function print_report that prints the value of N, the estimate, and the error to std::cout, with one labelled line each. It returns nothing (use void as the return type). Pass all three parameters by const reference: const int& N, const double& estimate, const double& error.

#include <iostream> 
#include <stdexcept> 
#include <cmath> 
  
double leibniz_estimate(int N, double& error) { 
    if (N < 1) { 
        throw std::invalid_argument( 
            "N must be at least 1 (got a non-positive value)."); 
    } 
  
    const double pi_ref = 3.14159265358979; 
  
    double sum = 0.0; 
    for (int k = 0; k < N; ++k) { 
        const double sign = (k % 2 == 0) ? 1.0 : -1.0; 
        sum += sign / (2.0 * k + 1.0); 
    } 
    const double estimate = 4.0 * sum; 
  
    error = std::abs(pi_ref - estimate); 
    return estimate; 
} 
  
void print_report(const int& N, 
                  const double& estimate, 
                  const double& error) { 
    std::cout << "Using N = " << N << " terms" << std::endl; 
    std::cout << "Estimate: " << estimate      << std::endl; 
    std::cout << "Error:    " << error         << std::endl; 
} 
  
int main() { 
    std::cout << "Leibniz pi estimator -- v0.2" << std::endl; 
  
    const int N = 1000; 
  
    try { 
        double err; 
        const double estimate = leibniz_estimate(N, err); 
        print_report(N, estimate, err); 
    } 
    catch (const std::exception& e) { 
        std::cerr << "Error: " << e.what() << std::endl; 
        return 1; 
    } 
  
    return 0; 
}

Argument passing¶

By value: functions works on a local copy of the variable from the calling scope

By reference: functions has full access to the variable from the calling scope

By constant reference: functions has read access to the variable from the calling scope

Step B.4: Group the functions in a namespace¶

Prompt: Wrap both leibniz_estimate and print_report in a namespace called leibniz. Inside the namespace, rename leibniz_estimate to just estimate. Update main to call leibniz::estimate(N, err} and leibniz::print_report(N, estimate, err). Do not use a using directive --- keep the leibniz:: prefix at every call site so the reader can see where each name comes from.

#include <iostream> 
#include <stdexcept> 
#include <cmath> 
  
namespace leibniz { 
  
    double estimate(int N, double& error) { 
        if (N < 1) { 
            throw std::invalid_argument( 
                "N must be at least 1 (got a non-positive value)."); 
        } 
  
        const double pi_ref = 3.14159265358979; 
  
        double sum = 0.0; 
        for (int k = 0; k < N; ++k) { 
            const double sign = (k % 2 == 0) ? 1.0 : -1.0; 
            sum += sign / (2.0 * k + 1.0); 
        } 
        const double est = 4.0 * sum; 
  
        error = std::abs(pi_ref - est); 
        return est; 
    } 
  
    void print_report(const int& N, 
                      const double& estimate, 
                      const double& error) { 
        std::cout << "Using N = " << N << " terms" << std::endl; 
        std::cout << "Estimate: " << estimate     << std::endl; 
        std::cout << "Error:    " << error        << std::endl; 
    } 
  
}  // namespace leibniz 
  
int main() { 
    std::cout << "Leibniz pi estimator -- v0.2" << std::endl; 
  
    const int N = 1000; 
  
    try { 
        double err; 
        const double est = leibniz::estimate(N, err); 
        leibniz::print_report(N, est, err); 
    } 
    catch (const std::exception& e) { 
        std::cerr << "Error: " << e.what() << std::endl; 
        return 1; 
    } 
  
    return 0; 
}

Namespaces¶

Syntax:

namespace name { ... }

Namespaces group related names into logical units and help avoid naming conflicts.

Example:

namespace leibniz {
    double estimate(int N, double& error) { ... }
}

namespace another_namespace {
        double estimate(int N, double& error) { ... }
}

leibniz::estimate(...);
another_namespace::estimate(...);

Using directive¶

Syntax:

using namespace name;

makes all names from the namespace name available for unqualified name lookup in the current scope.

Example:

using namespace leibniz;

estimate(...);                      // lookup includes leibniz
::another_namespace::estimate(...); // lookup starts in global namespace

Leading :: explicitly starts name lookup in the global namespace.

Step B.5: Tighten the contracts with assertions¶

Prompt: Inside the estimate function, after the loop has finished and before the error is computed, add an assert that the running sum is a finite number (use std::isfinite from <cmath>, which is true for normal floating-point values and false for NaN and infinity). Also add an assert at the top of print_report that N is at least 1 --- a sanity check that we are not being called with garbage. Keep the existing throw for N < 1 in estimate; the assert is a developer check, not a replacement for the runtime check.

#include <iostream>
#include <stdexcept> 
#include <cmath> 
#include <cassert> 
  
namespace leibniz { 
  
    double estimate(int N, double& error) { 
        if (N < 1) { 
            throw std::invalid_argument( 
                "N must be at least 1 (got a non-positive value)."); 
        } 
  
        const double pi_ref = 3.14159265358979; 
  
        double sum = 0.0; 
        for (int k = 0; k < N; ++k) { 
            const double sign = (k % 2 == 0) ? 1.0 : -1.0; 
            sum += sign / (2.0 * k + 1.0); 
        } 
        assert(std::isfinite(sum));         
        const double est = 4.0 * sum; 
  
        error = std::abs(pi_ref - est); 
        return est; 
    } 
  
    void print_report(const int& N, 
                      const double& estimate, 
                      const double& error) { 
        assert(N >= 1);                    // developer check 
        std::cout << "Using N = " << N << " terms" << std::endl; 
        std::cout << "Estimate: " << estimate     << std::endl; 
        std::cout << "Error:    " << error        << std::endl; 
    } 
  
}  // namespace leibniz 
  
int main() { 
    std::cout << "Leibniz pi estimator -- v0.2" << std::endl; 
    const int N = 1000; 
  
    try { 
        double err; 
        const double est = leibniz::estimate(N, err); 
        leibniz::print_report(N, est, err); 
    } 
    catch (const std::exception& e) { 
        std::cerr << "Error: " << e.what() << std::endl; 
        return 1; 
    } 
  
    return 0; 
}

Assertions¶

Syntax:

#include <cassert>

assert(condition);

checks that condition is true; otherwise, the program is terminated.

Assertions are intended for detecting programming errors and can be disabled in release builds (NDEBUG).

Example:

assert(N >= 1);

Block C: Arrays, initiatlisation, and pointers¶

In this block you will build a small statistics tool.

Given a sample of $N$ measurements $$ \left[ x_0, x_1, \dots, x_{N-1} \right] $$ we want to compute the sample mean $\overline{x}$ and the sample variance $\sigma^2$ $$ \overline{x} = \frac{1}{N} \sum_i x_i,\qquad \sigma^2 = \frac{1}{N-1} = \sum_i (x_i - \overline{x})^2 $$

From the variance we get the standard deviation $\sigma$ as its square root.

Step C.1: Store the sample in a fixed-size array¶

Prompt: Write a C++ program that declares an array of 5 doubles called data, initialized in place with the values 2.1, 2.3, 1.9, 2.2, 2.0 using brace-list initialization. Then loop over the array with a for loop and print each element to std::cout, one per line, prefixed with its index (e.g. data[0] = 2.1). Use plain int for the loop index. The array length should be a const int n = 5; declared just above the array.

#include <iostream> 
  
int main() { 
    std::cout << "Sample statistics tool -- v0.1" << std::endl; 
  
    const int n = 5; 
    double data[n] = {2.1, 2.3, 1.9, 2.2, 2.0}; 
  
    for (int i = 0; i < n; ++i) { 
        std::cout << "data[" << i << "] = " << data[i] << std::endl; 
    } 
  
    return 0; 
}

Built-in fixed-size arrays¶

Syntax:

type name[size] = { ... } ;

defines and initializes an array of size size and type type.

Example:

const int n = 5; 
double data1[n] = {2.1, 2.3, 1.9, 2.2, 2.0}; // copy-list initialization
double data2[n]{2.1, 2.3, 1.9, 2.2, 2.0};    // direct-list initialization (preferred modern style)

Step C.2: Compute the mean and meet the four initialisation forms¶

Prompt: Extend the program to compute and print the mean of the array. Inside main, deliberately use four different initialization forms for the local variables: declare sum with copy-style "double sum = 0.0;", declare count with constructor-style "int count(n);", declare the result mean with empty-brace value-initialization "double mean{};" and declare a loop index i with no initializer at all "int i;". Then loop, add up the values, and compute the mean = sum / count. Print the mean on its own labeled line. Add a code comment next to each declaration explaining which initialization form it is.

#include <iostream> 
  
int main() { 
    std::cout << "Sample statistics tool -- v0.1" << std::endl; 
  
    const int n = 5; 
    double data[n] = {2.1, 2.3, 1.9, 2.2, 2.0}; 
  
    double sum   = 0.0;    // copy initialisation 
    int    count(n);       // direct (constructor) initialisation 
    double mean{};         // value initialisation (zero for built-in types) 
    int    i;              // no initialiser -- holds an arbitrary value! 
  
    for (i = 0; i < count; ++i) { 
        sum += data[i]; 
    } 
    mean = sum / count; 
  
    std::cout << "Mean = " << mean << std::endl; 
  
    return 0; 
}

Step C.3: Extract the mean into a function and meet pointers¶

Prompt: Extract the mean calculation into a function called mean that takes two parameters: a pointer to a double (double* data) and the length of the array (int n). The function returns the mean as a double. Place the function above main. Inside the function, use the subscript form data[i] in the loop.

#include <iostream> 
  
double mean(double* data, int n) { 
    double sum{}; 
    for (int i = 0; i < n; ++i) { 
        sum += data[i];          // equivalent to *(data + i) 
    } 
    return sum / n; 
} 
  
int main() { 
    std::cout << "Sample statistics tool -- v0.2" << std::endl; 
  
    const int n = 5; 
    double data[n] = {2.1, 2.3, 1.9, 2.2, 2.0}; 
  
    const double m = mean(data, n); 
    std::cout << "Mean = " << m << std::endl; 
  
    return 0; 
}

Pointers¶

An array is a sequence of values stored contiguously in memory. In many expressions, an array decays to a pointer to its first element. When passing a built-in array to a function, the function therefore typically receives a pointer to its first element; its size must be passed separately.

Example:

double mean(double* data, int n) { ... }

Think about:

  • What is the purpose of function mean?
  • Is it safe to pass data as a pointer?
  • How can we pass data in a safer way?

Step C.4: Add the variance and the standard deviation¶

Prompt: Add a function called variance that takes the same double* data and int n as mean, plus a third parameter double mean_value (the precomputed mean). The function returns the sample variance as a double. In main, after computing the mean, call variance(data, n, mean_value) to get the variance, then compute the standard deviation as std::sqrt(variance_value) using <cmath>. Print all three numbers on their own labeled lines.

#include <iostream> 
#include <cmath> 
  
double mean(double* data, int n) { 
    double sum{}; 
    for (int i = 0; i < n; ++i) { 
        sum += data[i]; 
    } 
    return sum / n; 
} 
  
double variance(double* data, int n, double mean_value) { 
    double sum_sq{}; 
    for (int i = 0; i < n; ++i) { 
        double diff = data[i] - mean_value; 
        sum_sq += diff * diff; 
    } 
    return sum_sq / (n-1); 
} 
  
int main() { 
    std::cout << "Sample statistics tool -- v0.2" << std::endl; 
  
    const int n = 5; 
    double data[n] = {2.1, 2.3, 1.9, 2.2, 2.0}; 
  
    const double mean_value   = mean(data, n); 
    const double var = variance(data, n, mean_value); 
    const double sd  = std::sqrt(var); 
  
    std::cout << "Mean   = " << mean_value   << std::endl; 
    std::cout << "Var    = " << var << std::endl; 
    std::cout << "StdDev = " << sd  << std::endl; 
  
    return 0; 
}

Step C.5: Guard the functions against pointer hazards¶

Prompt: Add an input check at the top of both mean and variance: if the data pointer is nullptr, or if n is less than 1, throw std::invalid_argument with a clear message. In main, wrap the three function calls in a try block and add a matching catch (const std::exception& e) that prints the message to std::cerr and returns 1. Use the keyword nullptr explicitly (not NULL, not 0) when comparing the pointer.

#include <iostream> 
#include <cmath> 
#include <stdexcept> 
  
double mean(double* data, int n) { 
    if (data == nullptr) { 
        throw std::invalid_argument("mean: data pointer is null."); 
    } 
    if (n < 1) { 
        throw std::invalid_argument("mean: n must be at least 1."); 
    } 
  
    double sum{}; 
    for (int i = 0; i < n; ++i) { 
        sum += data[i]; 
    } 
    return sum / n; 
} 
  
double variance(double* data, int n, double mean_value) { 
    if (data == nullptr) { 
        throw std::invalid_argument("variance: data pointer is null."); 
    } 
    if (n < 1) { 
        throw std::invalid_argument("variance: n must be at least 1."); 
    } 
  
    double sum_sq{}; 
    for (int i = 0; i < n; ++i) { 
        const double diff = data[i] - mean_value; 
        sum_sq += diff * diff; 
    } 
    return sum_sq / (n-1); 
} 
  
int main() { 
    std::cout << "Sample statistics tool -- v0.3" << std::endl; 
  
    const int n = 5; 
    double data[n] = {2.1, 2.3, 1.9, 2.2, 2.0}; 
  
    try { 
        const double m   = mean(data, n); 
        const double var = variance(data, n, m); 
        const double sd  = std::sqrt(var); 
  
        std::cout << "Mean   = " << m   << std::endl; 
        std::cout << "Var    = " << var << std::endl; 
        std::cout << "StdDev = " << sd  << std::endl; 
    } 
    catch (const std::exception& e) { 
        std::cerr << "Error: " << e.what() << std::endl; 
        return 1; 
    } 
  
    return 0; 
}

Pointer hazards¶

Pointers can point to nirvana. It is therefore better to check that data is not the null pointer nullptr. We will discuss this topic in more detail in the next lecture.

Example:

double mean(double* data, int n) { 
    if (data == nullptr) { 
        throw std::invalid_argument("mean: data pointer is null."); 
    } 
    ...
}

What did we learn today?¶

  1. Basic concepts of C++: variables, constants, loops, namespaces, arrays, pointers.
  2. Basic experience with writing meaningful prompts for AI coding agents.

Your turn:

  1. Read the lecture notes for today's lecture and work on the self-study exercises
  2. Work on the additional weblab exercises during the lab session