Learn how to declare a C array, fill it, print it, and sum its elements, reinforcing the idea of bounds.
- C array:
int a[5];is a contiguous block of 5ints. - Valid indices:
0toN-1. std::size(a): gets the number of elements of a “real” array (C++17+).- Out-of-bounds access (e.g.,
a[10]) causes UB (undefined behavior).
File: 01_basic_c_array.cpp
- Declare
int a[5];. - Fill it with a
forloop, usingstd::size(a)to avoid hardcoding the size. - Print each element with
std::cout. - Compute the sum with another
forloop.
- Using
i <= Ninstead ofi < N(a classic off-by-one). - Thinking
a[5]is the “5th element” (the last one isa[4]). - Mixing
intwithstd::size_tand getting signed/unsigned comparison warnings.
- Change the fill to
a[i] = i*iand see the new sum. - Compute the average of the elements (use
double). - Find the largest and smallest element (without using algorithms yet).
g++ -std=c++20 -O2 -Wall -Wextra -pedantic -g 01_basic_c_array.cpp -o app
./app