Back to homeAP® Computer Science Principles · AP Computer Science Principles · Change subject
Start for free
AP CSP · AP® Computer Science Principles
Computer systems · Text-based programming

Program structures

Picture a video game on your phone: it stores your score, decides whether you leveled up, repeats the same action every frame, and reuses code for every enemy. However complex a program is, it is always built by combining the same pieces: variables that store data, selection that chooses one path or another, iteration that runs the same thing several times, and procedures (called functions in many languages) that group code under a name. Here you will learn to read and design those pieces in pseudocode like the kind on the AP® Exam Reference Sheet, using ←, IF/ELSE, REPEAT n TIMES, REPEAT UNTIL, FOR EACH and PROCEDURE ... RETURN. At the end we will go back to that game score.

Variables, constants and data types

Assignment code with the constant TAX_RATE, which is set once, and the variable price, which changes value when the sales tax is added to it. TAX_RATE ← 0.08 price ← 15.00 price ← price + price * TAX_RATE constant variable does not change changes
Practice★☆☆Not started
Explain what a variable is in a program and give an example: what name and content would a variable have in a video game that stores the player's score? What operation…

Explain what a variable is in a program and give an example: what name and content would a variable have in a video game that stores the player's score? What operation would change its value upon completing a level?

Solve
Practice★☆☆Not started
Explain the difference between a variable and a constant in a program, giving an example of each in a billing program (the product price versus the sales tax percentage).

Explain the difference between a variable and a constant in a program, giving an example of each in a billing program (the product price versus the sales tax percentage).

Solve
Practice★☆☆Not started
Data in a program has a type: integer, decimal (float), string/text, or boolean. State the most suitable data type for each item and justify your choice: a person's age,…

Data in a program has a type: integer, decimal (float), string/text, or boolean. State the most suitable data type for each item and justify your choice: a person's age, their height in meters, their name, and whether they have passed or failed.

Solve
Practice★☆☆Not started
Read this snippet and perform a trace: Indicate which value is displayed on the screen and explain why the second instruction is not a mathematical equation but an…

Read this snippet and perform a trace:

start

    x ← 4

    x ← x + 2

    print x

end

Indicate which value is displayed on the screen and explain why the second instruction is not a mathematical equation but an assignment.

Solve

Selection: conditional structures

Practice★☆☆Not started
Explain what a conditional structure is (if... then... else...) and write two examples of everyday decisions expressed using this structure, indicating the condition and…

Explain what a conditional structure is (if... then... else...) and write two examples of everyday decisions expressed using this structure, indicating the condition and the two possible actions.

Solve
Practice★★☆Not started
Write a program in pseudocode that reads an exam score (a number from 0 to 10) and prints "pass" if the score is 5 or greater, and "fail" otherwise. Use a variable, an…

Write a program in pseudocode that reads an exam score (a number from 0 to 10) and prints "pass" if the score is 5 or greater, and "fail" otherwise. Use a variable, an input operation, and a conditional structure.

Solve
Practice★★☆Not started
This program classifies a person according to their age: Trace the program for an input of 17 and an input of 21, stating in each case which condition is evaluated and…

This program classifies a person according to their age:

start

    read age

    if age ≥ 18 then

        print "adult"

    else

        print "minor"

    end if

end

Trace the program for an input of 17 and an input of 21, stating in each case which condition is evaluated and what is printed on the screen.

Solve

Iteration: loops and their traces

Flowchart of a loop: n is read and, while n is greater than 0, n is written and 1 is subtracted; when the condition stops being met, the program ends. start read n n > 0 ? yes write n n ← n − 1 no end
Practice★☆☆Not started
Explain what a loop is and what problem it solves compared to repeating the same instructions many times. Write in pseudocode a loop that prints the numbers from 1 to 5.

Explain what a loop is and what problem it solves compared to repeating the same instructions many times. Write in pseudocode a loop that prints the numbers from 1 to 5.

Solve
Practice★★☆Not started
Read this pseudocode program: Trace it step by step (value of sum and n at the end of each iteration) and indicate how many times the loop repeats and what value is…

Read this pseudocode program:

start

    sum ← 0

    n ← 1

    while n ≤ 5 do

        sum ← sum + n

        n ← n + 1

    end while

    print sum

end

Trace it step by step (value of sum and n at the end of each iteration) and indicate how many times the loop repeats and what value is printed at the end.

Solve
Practice★★☆Not started
The flowchart in the figure represents a program with a loop: it reads a number n and, while n is greater than 0, prints its value and subtracts 1 from it, as shown in…

The flowchart in the figure represents a program with a loop: it reads a number n and, while n is greater than 0, prints its value and subtracts 1 from it, as shown in the figure.

start read n n > 0 ? yes print n n ← n − 1 no end

If the user enters n = 3: (a) trace the program indicating what values n takes and what is printed in each iteration; (b) state how many times the body of the loop is executed; (c) explain what would happen if the user entered n = 0.

Solve
Practice★★☆Not started
Write a program in pseudocode that prints a countdown from 10 to 1 and, when the loop ends, prints "Liftoff!". Use a variable and a while loop.

Write a program in pseudocode that prints a countdown from 10 to 1 and, when the loop ends, prints "Liftoff!". Use a variable and a while loop.

Solve
Practice★★☆Not started
This program adds up numbers entered by the user until zero is entered: Trace the program for the input sequence 4, 3, 0: indicate the value of n and sum after each…

This program adds up numbers entered by the user until zero is entered:

start

    sum ← 0

    read n

    while n ≠ 0 do

        sum ← sum + n

        read n

    end while

    print sum

end

Trace the program for the input sequence 4, 3, 0: indicate the value of n and sum after each input and what is printed at the end. In addition, explain why the first read n is outside the loop.

Solve
Practice★★☆Not started
This program should write the numbers from 1 to 5, but it has a bug: a) Identify the error: what is missing from the body of the loop? b) Explain what happens when the…

This program should write the numbers from 1 to 5, but it has a bug:

inicio

    n ← 1

    mientras n ≤ 5 hacer

        escribir n

    fin mientras

fin
  1. a) Identify the error: what is missing from the body of the loop?
  1. b) Explain what happens when the program is run as written.
  1. c) Write the corrected pseudocode.
Solve

Combining loops and conditionals

Flowchart of an access control: after setting attempts to 0, a loop checks whether attempts remain, reads the passcode and, if it is incorrect, adds one attempt and goes back to check; if it is correct it allows access, and if no attempts remain it blocks access. start attempts ← 0 attempts left? no Access blocked yes read passcode passcode correct? yes Access granted no attempts ← attempts + 1
Practice★★☆Not started
The flowchart in the figure represents access control for a device: there is a maximum of three attempts to enter the correct passcode, as shown in the figure. (a)…

The flowchart in the figure represents access control for a device: there is a maximum of three attempts to enter the correct passcode, as shown in the figure.

start attempts ← 0 attempts remaining? no Access blocked yes read passcode correct passcode? yes Access granted no attempts ← attempts + 1

(a) Explain the full execution path of the program when the user enters the wrong passcode twice and gets it right on the third try. (b) State the maximum number of times the program asks for the passcode. (c) Reason why the variable attempts is incremented in only one of the branches of the second decision diamond.

Solve
Practice★★★Not started
A classmate claims that to count how many numbers between any two positive integers $A$ and $B$ ($A \le B$) are simultaneously divisible by $3$ and by $5$, the following…

A classmate claims that to count how many numbers between any two positive integers $A$ and $B$ ($A \le B$) are simultaneously divisible by $3$ and by $5$, the following pseudocode always works and is the most efficient:

start

    read A, B

    total ← 0

    while A ≤ B do

        if (A mod 3 = 0) or (A mod 5 = 0) then

            total ← total + 1

        end if

        A ← A + 1

    end while

    write total

end

(a) Refute two flaws in their proposal: a conditional logic error according to the required specification and an algorithmic inefficiency (analyze how many iterations and condition evaluations it performs if $B - A = 1\,000\,000$).

(b) If a while loop must strictly be used, rewrite the algorithm optimizing the initial value and the increment step to perform the fewest possible iterations without evaluating any conditionals inside the loop.

(c) Design a mathematical solution in constant time $O(1)$ without loops in pseudocode and formally justify the formula used.

Solve
Practice★★★Not started
Design in pseudocode the control algorithm for a push-button regulated pedestrian crossing traffic light that safely manages the traffic of an avenue with the following…

Design in pseudocode the control algorithm for a push-button regulated pedestrian crossing traffic light that safely manages the traffic of an avenue with the following requirements:

  1. At idle, the vehicular traffic light remains green.

  2. To avoid traffic jams caused by continuous calls, a minimum vehicular green time of $30$ seconds must be guaranteed between two consecutive pedestrian phases.

  3. Once said minimum time has elapsed and a pedestrian press is detected, the mandatory sequence is: vehicular yellow for $3$ seconds, vehicular red and pedestrian green for $15$ seconds, and finally flashing pedestrian green for $4$ seconds before restoring vehicular green.

(a) Write the pseudocode of the system structured within a continuous supervisory loop.

(b) Analyze what locking failure the intersection would suffer if the sensor failed in a continuous active state (stuck push-button), and justify how your design prevents the avenue from collapsing indefinitely.

(c) Technically justify why in concurrent real-time control systems it is preferable to query a clock timestamp (current_time()) instead of suspending the CPU using passive blocking delays (wait()).

Solve
Practice★★★Not started
Analyze the following algorithm that processes index pairs $(i, j)$: (a) Deduce and algebraically justify a formula that expresses how many times in total the if…

Analyze the following algorithm that processes index pairs $(i, j)$:

start

    read N

    counter ← 0

    for i from 1 to N do

        for j from i to N do

            if (i + j) mod 2 = 0 then

                counter ← counter + 1

            end if

        end for

    end for

    write counter

end

(a) Deduce and algebraically justify a formula that expresses how many times in total the if condition is evaluated as a function of $N$ (calculating the sum of iterations of the inner loop with respect to the outer loop).

(b) Predict the exact final value of counter if the input is $N = 5$, building a trace table showing the values of $i$, $j$, the result of the condition, and the updates to counter.

(c) A student states: "Since the nested loop iterates over pairs of numbers, changing for j from i to N to for j from 1 to N and dividing the final result by $2$ would produce exactly the same result for any $N$". Prove through formal reasoning or a counterexample whether this statement is true or false.

Solve

Functions: dividing the program into pieces

The function circle_area is written once and called twice: with radius 1 it returns an area of 3.14 and with radius 2 it returns 12.57, four times as much. function circle_area(radius) return π·radius² write circle_area(1) radius = 1 ≈ 3.14 write circle_area(2) radius = 2 ≈ 12.57
Practice★☆☆Not started
Explain what a function is in a program and two advantages of breaking code down into named functions (reusing without copying, understanding and testing each part…

Explain what a function is in a program and two advantages of breaking code down into named functions (reusing without copying, understanding and testing each part separately).

Solve
Practice★☆☆Not started
What is a comment in source code? Explain who comments are intended for (not the computer, but whoever reads the code later) and what a good comment should explain (the…

What is a comment in source code? Explain who comments are intended for (not the computer, but whoever reads the code later) and what a good comment should explain (the reasoning behind decisions, not what is already obvious).

Solve
Practice★★★Not started
Design in pseudocode an algorithm for the "guess the number" game where the roles are reversed: the user thinks of a secret integer between $1$ and $100$, and the…

Design in pseudocode an algorithm for the "guess the number" game where the roles are reversed: the user thinks of a secret integer between $1$ and $100$, and the computer must guess it using the optimal binary search strategy.

(a) Write the pseudocode for the algorithm. In each iteration, the computer will propose the midpoint of the current interval, and the user will respond whether the secret number is "higher", "lower", or if the machine has "guessed correctly".

(b) Incorporate a validation mechanism that detects if the user makes a contradiction or cheats (for example, if the boundaries of the search interval cross because the lower bound exceeds the upper bound), halting the program with an explanatory warning message.

(c) Formally justify what the maximum number of attempts required by the computer will be to guess any number in the range $[1, 100]$, and predict how many maximum attempts would be required if the range were extended to $[1, 1\,000]$.

Solve
Practice★★★Not started
A cybersecurity analyst reviews the following pseudocode designed to control card and PIN access at a bank terminal: (a) Identify and justify a serious flow control flaw…

A cybersecurity analyst reviews the following pseudocode designed to control card and PIN access at a bank terminal:

start

    secret_pin ← 3852

    attempts ← 0

    blocked ← false

    while attempts < 3 and not blocked do

        read entered_pin

        if entered_pin = secret_pin then

            write "Welcome to the system"

        else

            attempts ← attempts + 1

            write "Incorrect PIN"

        end if

    end while

    if attempts = 3 then

        blocked ← true

        write "Card blocked for security"

    end if

end

(a) Identify and justify a serious flow control flaw that occurs when the user enters the correct PIN on the first attempt.

(b) Predict the behavior of the program and the final value of the variables attempts and blocked if the user enters the input sequence: 1111, 3852, 9999.

(c) Rewrite the algorithm in pseudocode, correcting the execution flow to guarantee an immediate clean exit upon success and strict lockout after three consecutive failures, ensuring that under no circumstances is the welcome message displayed if the card becomes blocked.

Solve
Practice★★★Not started
In the design of a hydraulic installation, cylindrical nodular cast iron bushings with an annular cross-section (circular ring) and a density $\rho = 7.2\text{ g/cm}^3$…

In the design of a hydraulic installation, cylindrical nodular cast iron bushings with an annular cross-section (circular ring) and a density $\rho = 7.2\text{ g/cm}^3$ are used.

(a) Design in pseudocode a function area_anillo(radio_int, radio_ext) that calculates and returns the area of the circular ring ($\pi \times (r_{ext}^2 - r_{int}^2)$). The function must validate that $radio\_ext > radio\_int > 0$; if the parameters violate this physical condition, it must return $-1.0$ as an error code. Consider $\pi \approx 3.1416$.

(b) Design a second function masa_tubo(radio_int, radio_ext, longitud, densidad) that calls area_anillo to calculate the volume and the total mass of the section in kilograms (considering that dimensions are entered in centimeters and density in $\text{g/cm}^3$). If area_anillo returns an error or the length is less than or equal to zero, the function must propagate the value $-1.0$.

(c) Perform a full execution trace of masa_tubo(4{,}0, 5{,}0, 100{,}0, 7{,}2), indicating the input and output values of each function and justifying the numerical result obtained.

Solve
Practice★★★Not started
The quality assurance committee of a school evaluates the following algorithm, intended to determine the final grade of a technical course from three partial scores…

The quality assurance committee of a school evaluates the following algorithm, intended to determine the final grade of a technical course from three partial scores ($N_1, N_2, N_3 \in [0.0; 10.0]$). Official regulations establish: "The student is graded 'Pass' if the weighted average ($30\,\%$ for $N_1$, $30\,\%$ for $N_2$, and $40\,\%$ for $N_3$) is equal to or greater than $5.0$, provided that none of the individual scores is below $4.0$; otherwise, the grade is 'Fail'".

start

    read N1, N2, N3

    average ← N1 · 0.3 + N2 · 0.3 + N3 · 0.4

    if average ≥ 5.0 or (N1 ≥ 4.0 and N2 ≥ 4.0 and N3 ≥ 4.0) then

        write "Pass"

    else

        write "Fail"

    end if

end

(a) Explain in detail why the program produces no syntax errors and executes normally despite containing a critical logical flaw in the conditional structure.

(b) Design two triplets of test scores $(N_1, N_2, N_3)$ that expose the algorithm's flaw: one that causes a false positive (the program declares 'Pass' when it should be 'Fail') and another that causes a false negative (or justify whether the latter is possible with the current expression).

(c) Rewrite the algorithm in pseudocode, correcting the logical condition and adding a prior check to verify that the three entered scores lie within the valid range $[0.0; 10.0]$.

Solve
Practice★★★Not started
A novice programmer has implemented the "guess the number" game using a single function that directly accesses global variables: (a) Justify three disadvantages of this…

A novice programmer has implemented the "guess the number" game using a single function that directly accesses global variables:

global variables: secret, attempts

function play_round()

    write "Enter a number (1-100): "

    read guess

    attempts ← attempts + 1

    if guess = secret then

        write "You got it right in ", attempts, " attempts!"

    else

        if guess < secret then

            write "The secret number is higher"

        else

            write "The secret number is lower"

        end if

    end if

end function

(a) Justify three disadvantages of this design based on the concepts of coupling, side effects, and lack of cohesion. Why does mixing console input/output with comparison logic prevent this function from being reused in a graphical user interface or in a web application?

(b) Redefine the modular architecture by creating three loosely coupled functions: a pure comparison function (taking the guess and the secret and returning an indicator of the result), an input validation function (verifying the range $[1, 100]$), and a state update function. Specify for each its exact signature (name, parameter types, and return type) and its responsibilities.

(c) Write in pseudocode the main program that coordinates these functions using parameter passing and return values, without using any global variables.

Solve

Summary

See all the exercises in this section