Today's plan:
#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;
}
The code below has errors. Fix it so it compiles and prints "Hi!".
int main() {
cout << "Hi!"
return 0
}
Declare and initialize, then print on separate lines with labels:
#include <iostream>
#include <string>
int main() {
// TODO: declare variables as specified
// TODO: print each with a label (e.g., "Year: 2025")
return 0;
}
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;
}
Read two integers a and b. Compute and print:
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;
}
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;
}
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;
}
Write a function that returns the larger of two ints:
int max2(int a, int b)
main.main.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
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
-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;
}
Same task as C++: simple sum in a for-loop with identical N.
Run: python loop.py
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")
An array is a data structure that stores a fixed-size sequential collection of elements of the same type.
To declare an array, you specify the type of the elements and the number of elements the array will hold.
type arrayName[arraySize];
This code declares an array of 5 integers.
int numbers[5];
You can initialize an array at the time of declaration.
This code declares and initializes an array of 5 integers.
int numbers[5] = {10, 20, 30, 40, 50};
You can access individual elements of an array using their index. Array indices start at 0.
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
You can use a for loop to iterate through the elements of an array.
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;
}
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;
}
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;
}
In C, strings are represented as arrays of characters, terminated by a null character (\0).
This code declares a C-style string.
char greeting[] = "Hello";
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.
This code uses the std::string class.
#include <iostream>
#include <string>
int main() {
std::string greeting = "Hello, C++!";
std::cout << greeting;
return 0;
}
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.
To declare a pointer, you use the * operator.
type *pointerName;
This code declares a pointer to an integer.
int *p;
The address-of operator (&) returns the memory address of a variable.
This code gets the memory address of the myVar variable and stores it in the pointer p.
int myVar = 42;
int *p = &myVar;
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 (*) 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.
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;
}
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;
}
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.
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;
}
The name of an array is actually a pointer to the first element of the array.
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;
}
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]