Skip to main content

Exploring Calculus with Maple Introductory Calculus

Section 18.3 Combining Loops and Conditionals

We now combine all of the various conditional statements and loops together into one example.

Example 18.7. Outputting the Primes up to \(50\).

In this example, we will create a small loop through the integers from 1 and to 50, only outputting the integer if it is prime.
Creating a loop that prints every integer from 1 to 50 is fairly simple:

Aside

> for i from 1 to 50 do
      print(i);
    end do
We only need to include an β€˜if’ statement inside the loop that runs the print() command when \(i\) is prime. We can make use of the isprime() command for this if statment and we do not require an else.
> for i from 1 to 50 do
    if isprime(i) then
      print(i);
    end if
  end do
\begin{equation*} \displaystyle 2 \end{equation*}
\begin{equation*} \displaystyle 3 \end{equation*}
\begin{equation*} \displaystyle 5 \end{equation*}
\begin{equation*} \displaystyle 7 \end{equation*}
\begin{equation*} \displaystyle 11 \end{equation*}
\begin{equation*} \displaystyle 13 \end{equation*}
\begin{equation*} \displaystyle 17 \end{equation*}
\begin{equation*} \displaystyle 19 \end{equation*}
\begin{equation*} \vdots \end{equation*}

Example 18.8.

In this example, we will test to see whether a function \(g(x)=x^4-4x^3+3x^2\) is (i) increasing (\(g'(x) > 0\)), (ii) decreasing (\(g'(x) \lt 0\)), or (iii) neither (critical point (\(g'(x) = 0\))) at a variety of \(x\)-values.

Aside

In this case, the for loop is given an ordered list of values for which to apply the first derivative test. The test performs its iterations and conditionals as follows:
  1. Begin with the value \(j=-2\text{.}\)
  2. If \(g'(j)>0\text{,}\) then \(g\) is increasing at \(x=j\text{.}\)
  3. If \(g'(j)\lt 0\text{,}\) then \(g\) is decreasing at \(x=j\text{.}\)
  4. If \(g'(j)=0\text{,}\) then \(g\) is neither increasing nor decreasing at \(x=j\text{.}\)
  5. Update \(j\) to the next value in the list and repeat steps \(2\) through \(4\text{.}\)
Within each iteration, the value of \(x\) is output, along with whether \(g(x)\) is increasing, decreasing, or neither at that value.
> g(x) := x^4 - 4*x^3 + 3*x^2:
> for j in [-2, 0, 4] do
    if subs(x = j, diff(g(x), x)) > 0 then
      print(j, "increasing")
    elif subs(x = j, diff(g(x), x)) < 0 then
      print(j, "decreasing")
    else 
      print(j, "neither")
    end if
  end do
\begin{equation*} \displaystyle -2,\,\text{ "decreasing" } \end{equation*}
\begin{equation*} \displaystyle 0,\,\text{ "neither" } \end{equation*}
\begin{equation*} \displaystyle 4,\,\text{ "increasing" } \end{equation*}
From the output, we an see that \(g'(-2) \lt 0\text{,}\) \(g'(0) = 0\text{,}\) and \(g'(4) \gt 0\text{.}\)