if + Looping Examples#
Prime numbers#
One way to check if a number \(N\) is prime is to check if it is evenly divisible by all integers up to \(\sqrt{N}\). Let’s look at a code that can do this, up to an arbitrary maximum integer.
#include <iostream>
#include <cmath>
int main() {
const int n_max = 100;
for (int n = 2; n <= n_max; ++n) {
bool is_prime{true};
int max_factor = static_cast<int>(std::sqrt(n));
for (int q = 2; q <= max_factor; ++q) {
if (n % q == 0) {
is_prime = false;
break;
}
}
if (is_prime) {
std::cout << n << " is prime!" << std::endl;
}
}
}
Some notes:
We have nested loops here. The outer loop using loop variable
nand the inner loop uses loop variableq.In the inner loop, once we find a factor, we don’t have to check any more—we already know it is not prime. So we
break. This jumps us out of the inner loop (theqloop), but not the outer loop.We don’t have to do the
breakhere, but it saves on computation—there is no point in checking more, so the code will run faster.Our final
if-test is justif (is_prime). Sinceis_primeis abool, this is already a valid condition, and we don’t need to do something likeis_prime == true.
Fibonacci sequence#
The Fibonacci sequence is such that each
term is the sum of the previous two. We can write a code to create a
vector with the Fibonacci sequence up to a desired number of terms.
We’ll use a while loop for this, testing on the size of the
vector.
#include <cstdlib>
#include <iostream>
#include <vector>
int main() {
std::vector<long> fib{0, 1};
std::cout << "How many terms of the Fibonacci sequence to compute? (N > 2) ";
int N{};
std::cin >> N;
if (N <= 2) {
// we already have that -- abort
std::cout << "too few" << std::endl;
std::exit(1);
}
// add to the sequence
while (static_cast<int>(fib.size()) < N) {
auto s = fib.size();
fib.push_back(fib[s-1] + fib[s-2]);
}
// now output
for (auto e : fib) {
std::cout << e << " ";
}
std::cout << std::endl;
}
Some notes:
We are using a
longinteger as the datatype for our vector. This is to help with integer overflows. Even withlonghowever, we will overflow the limits of the 64-bit integer at about 100 terms.We could get a little further (~ 1 more element) by using an
unsigned long.In our
whileloop, we are testing on the size of the vector.fib.size()will return a datatype ofstd::size_t. To be To be absolutely correct, we cast it to aninthere, the same datatype asN. We probably don’t have to, but this is safest.We check to make sure the user asks for at least 3 elements, since we already start with
{0, 1}. And we exit using std::exit if they ask for too few. This requires thecstdlibheader.Tip
It is tradition in Unix to exit with a non-zero code if a problem was encountered. This can then be checked in a Bash script or the command line via the
$?shell variable.See Understanding exit status codes for more details.