Skip to main content
Logo image

PreTeXt Sample Book Abstract Algebra (SAMPLE ONLY)

Section 3.3 Code Lens

CodeLens is an interactive tool for following program execution, much like a debugger, without the ability to influence flow control or variable values. For use without a server, traces must be computed beforehand. First, we have some trivial programs, to provide minimal testing.
Listing 3.3.1. A Python program, stepable with CodeLens
Listing 3.3.2. An C program, stepable with CodeLens
Listing 3.3.3. A Java program, stepable with CodeLens
Codelens interactives can be given one or more checkpoints where the user is asked a question as the code is executed:
Listing 3.3.4. A Python program, stepable with CodeLens, with questions
View Source for program
<program label="python-code-lens-questions" interactive="codelens" language="python" include-source="yes">
    <code>
    def foo(n):
        n = n + 1
        return n
    x = 7
    y = x // 3
    z = foo(y)
    </code>
    <checkpoint line="4" answer="x">
        <prompt>What variable is being assigned to?</prompt>
    </checkpoint>
    <checkpoint line="5" answer-variable="globals.y">
        <prompt>What value will be assigned to <c>y</c>?</prompt>
        <feedback><c>//</c> does integer division</feedback>
    </checkpoint>
    <checkpoint line="3" answer-variable="current_frame.n">
        <prompt>What value will be returned?</prompt>
        <feedback>What is <c>n</c> right now?</feedback>
    </checkpoint>
</program>
If a Codelens contains checkpoints, it is also possible to make it into an exercise. For use on Runestone, there should be an @label on the exercise:

Checkpoint 3.3.5. A C++ program as CodeLens exercise.

Run the codelens and answer the questions it asks.
Now some moderately more complicated programs to find the prime numbers less than \(20\text{.}\) We do not vouch for the quality of these, or even their correctness!
Listing 3.3.6. Sieve of Eratosthenes, Java
View Source for program
<program label="sieve-codelens-python" interactive="codelens" language="python" starting-step="73" include-source="yes">
    <code>
    def SieveOfEratosthenes(n):
       # array of type boolean with True values in it
       prime = [True for i in range(n + 1)]
       p = 2
       while (p * p &lt;= n):
          # If it remain unchanged it is prime
          if (prime[p] == True):
             # updating all the multiples
             for i in range(p * 2, n + 1, p):
                prime[i] = False
          p += 1
       prime[0]= False
       prime[1]= False
       # Print
       for p in range(n + 1):
          if prime[p]:
             print (p,end=" ")
    # main
    if __name__=='__main__':
       n = 20
       print ("The prime numbers smaller than or equal to", n,"is")
       SieveOfEratosthenes(n)
    
    </code>
</program>
Listing 3.3.7. Sieve of Eratosthenes, C++
Listing 3.3.8. Sieve of Eratosthenes, Java