slug
type
status
category
date
summary
tags
password
icon
Let's walk through each of the following code step by step, explaining what each part does.
Step 1: Variables
Code:
Explanation:
- Variable Declaration:
DECLARE sum :INTEGER: Declares a variable namedsumof typeINTEGER.DECLARE name : STRING: Declares a variable namednameof typeSTRING.DECLARE flag : BOOLEAN: Declares a variable namedflagof typeBOOLEAN.
- Variable Initialization:
sum <-- 100: Assigns the integer value100tosum.name <-- "Victor": Assigns the string"Victor"toname.flag <-- TRUE: Assigns the boolean valueTRUEtoflag.
- Output Statements:
OUTPUT sum: Displays the value ofsum(which is100).OUTPUT name: Displays the value ofname(which is"Victor").OUTPUT flag: Displays the value offlag(which isTRUE).
Summary: This step demonstrates how to declare variables of different types, assign values to them, and output their values.
Step 2: Simple Loop
Code:
Explanation:
- Variable Declaration and Initialization:
DECLARE sum :INTEGER: Declares an integer variablesum.sum <-- 0: Initializessumto0.
- FOR Loop:
FOR i <-- 1 TO 100: Initiates a loop where the variableistarts at1and increments by1each iteration until it reaches100.sum <-- sum + i: In each iteration, adds the current value ofitosum.NEXT i: Marks the end of the loop block for the variablei.
- Output Statement:
OUTPUT sum: After the loop completes, outputs the final value ofsum.
What It Does:
- This loop calculates the sum of all integers from
1to100. After the loop,sumwill hold the value5050, which is the result of 100*101/2.
Step 3: Loop with Step and While Loop
Code:
Explanation:
Part 1: FOR Loop with STEP
- First Loop: Summing Odd Numbers
DECLARE sum :INTEGERandsum <-- 0: Initializessumto0.FOR i <-- 1 TO 100 STEP 2: Starts a loop withifrom1to100, incrementing by2each time (i.e.,1, 3, 5, ..., 99).sum <-- sum + i: Adds the current odd numberitosum.OUTPUT sum: Outputs the total sum of odd numbers between1and100. The result is2500.
- Second Loop: Summing Even Numbers
DECLARE sum2 :INTEGERandsum2 <-- 0: Initializessum2to0.FOR i <-- 0 TO 100 STEP 2: Starts a loop withifrom0to100, incrementing by2each time (i.e.,0, 2, 4, ..., 100).sum2 <-- sum2 + i: Adds the current even numberitosum2.OUTPUT sum2: Outputs the total sum of even numbers between0and100. The result is2550.
Part 2: WHILE Loop
- Variable Declaration and Initialization:
DECLARE target, generated, count : INTEGER: Declares three integer variables.target <-- 8: Sets the target number to8.generated <-- INT(RAND(10)): Generates a random integer between0and9and assigns it togenerated.count <-- 1: Initializescountto1.
- WHILE Loop:
WHILE generated <> target DO: Continues looping as long asgeneratedis not equal totarget.OUTPUT generated: Outputs the currently generated number.generated <-- INT(RAND(10)): Generates a new random integer between0and9.count <-- count + 1: Increments thecountby1.ENDWHILE: Marks the end of the loop.
- Final Output:
OUTPUT "Found target number ", target, " in ", count, " random guesses": After finding the target number, outputs a message indicating how many guesses it took to find the target.
What It Does:
- First Part: Demonstrates how to use a
FORloop with a step value to sum odd and even numbers separately.
- Second Part: Uses a
WHILEloop to repeatedly generate random numbers until the target number (8) is found, keeping track of the number of attempts.
Step 4: PROCEDURE
Code:
Explanation:
- Procedure Declaration:
PROCEDURE Greetings(): Defines a procedure namedGreetingsthat takes no parameters.
- Procedure Body:
FOR count <-- 1 TO 90: Initiates a loop that runs90times.OUTPUT "Hello": In each iteration, outputs the string"Hello".NEXT count: Marks the end of the loop block.
- Procedure Call:
Greetings(): Calls theGreetingsprocedure, executing its body.
What It Does:
- This procedure, when called, prints the word
"Hello"ninety times. It's a way to encapsulate reusable code; you can callGreetings()wherever you need to perform this action without rewriting the loop each time.
Step 5: FUNCTION 1
Code:
Explanation:
- Function Declaration:
FUNCTION findArea(radius : REAL) RETURNS REAL: Defines a function namedfindAreathat takes one parameterradiusof typeREAL(floating-point number) and returns aREALvalue.
- Function Body:
CONSTANT pi = 3.1415962653: Declares a constantpiwith its approximate value.DECLARE area : REAL: Declares a variableareaof typeREAL.area <-- pi * radius ** 2: Calculates the area of a circle using the formula \( \pi r^2 \) and assigns it toarea. Here,*denotes exponentiation.RETURN area: Returns the calculated area.
- Function Call and Output:
OUTPUT findArea(100): Calls thefindAreafunction withradiusset to100and outputs the returned area.
What It Does:
- The
findAreafunction calculates the area of a circle given its radius. In this example, it calculates the area for a circle with a radius of100, resulting in \( \pi \times 100^2 = 31,415.92653 \).
Step 6: FUNCTION 2
Code:
Explanation:
- Function Declaration:
FUNCTION isPrime(n : INTEGER) RETURNS BOOLEAN: Defines a function namedisPrimethat takes an integernand returns a boolean value (TRUEorFALSE).
- Function Body:
DECLARE max : INTEGER: Declares an integer variablemax.max <-- INT(n ** 0.5): Calculates the integer part of the square root ofnand assigns it tomax. This is used to optimize the prime checking process.FOR count <-- 2 TO max: Starts a loop from2tomax.IF n MOD count = 0 THEN: Checks ifnis divisible bycountwithout a remainder.RETURN FALSE: Ifnis divisible by any number between2andmax, it is not prime; thus, returnsFALSE.NEXT count: Ends the loop.RETURN TRUE: If no divisors are found, the number is prime; returnsTRUE.
- Function Call and Output:
OUTPUT isPrime(18): Calls theisPrimefunction withn = 18and outputs the result.
What It Does:
- The
isPrimefunction determines whether a given integernis a prime number.
- In the example,
isPrime(18)checks if18is prime. Since18is divisible by2,3,6, and9, the function returnsFALSE, indicating that18is not a prime number.
Step 7: Loops & Functions
Code:
Explanation:
- FOR Loop:
FOR n <-- 2 TO 1000: Initiates a loop wherenranges from 2 to1000.IF isPrime(n) THEN: Calls the previously definedisPrimefunction to check ifnis prime.OUTPUT "🟢 ", n, " is prime!": Ifnis prime, outputs a green circle emoji followed by the message thatnis prime.ELSE: Ifnis not prime,OUTPUT "🔴 ", n, " is not prime...": Outputs a red circle emoji followed by the message thatnis not prime.ENDIF: Ends theIFstatement.NEXT n: Moves to the next value ofn.
- Function Definition:
- The
isPrimefunction is the same as defined in Step 6. It checks whether a given numbernis prime.
What It Does:
- This code iterates through all numbers from 2 to
1000, checks each number to see if it's prime using theisPrimefunction, and outputs a message indicating whether each umber is prime or not with corresponding emojis.
Example Output:
Step 8: Nested Loops
Code:
Explanation:
- FOR Loop:
FOR n <-- 3 TO 1000: Starts a loop withnranging from3to1000.
- Nested IF Statements:
IF isPrime(n) THEN: Checks ifnis a prime number.IF isPrime(n+2) THEN: Ifnis prime, checks ifn + 2is also prime.OUTPUT "🟢🟢 ", n," and ",n+2, " are twin primes": If bothnandn + 2are prime, outputs a message indicating they are twin primes with two green circle emojis.ENDIF: Ends the innerIF.ENDIF: Ends the outerIF.NEXT n: Proceeds to the next value ofn.
- Function Definition:
- The
isPrimefunction is the same as previously defined in Step 6 and Step 7.
What It Does:
- This code identifies and outputs all twin primes between
3and1000.
- Twin primes are pairs of prime numbers that have a difference of
2(e.g.,3and5,5and7,11and13).
Example Output:
(Note:
999 is not a prime number, so the last line would not actually appear.)Step 9: Array
Code:
Explanation:
Part 1: Static Array Initialization
- Array Declaration:
DECLARE scores : ARRAY [1:5] OF INTEGER: Declares an array namedscoreswith indices from1to5, each element being an integer.
- Assigning Values:
scores[1] <-- 78scores[2] <-- 91scores[3] <-- 27scores[4] <-- 63scores[5] <-- 42- Assigns specific integer values to each element of the
scoresarray.
- FOR Loop to Output Array Elements:
FOR n <-- 1 TO LENGTH(scores): Loops from1to the length ofscores(which is5).OUTPUT scores[n]: Outputs each element in the array.NEXT n: Moves to the next index.
What It Does:
- Initializes an array with predefined scores and outputs each score:
Part 2: Dynamic Array with Random Values
- Array Declaration:
DECLARE scores : ARRAY [1:18] OF INTEGER: Declares an array namedscoreswith indices from1to18, each element being an integer.
- FOR Loop to Assign Random Values:
FOR i <-- 1 TO LENGTH(scores): Loops from1to18.scores[i] <-- INT(RAND(100)): Assigns a random integer between0and99to each element in the array.NEXT i: Moves to the next index.
- FOR Loop to Output Array Elements:
FOR n <-- 1 TO LENGTH(scores): Loops from1to18.OUTPUT scores[n]: Outputs each randomly assigned score.NEXT n: Moves to the next index.
What It Does:
- Creates an array of
18integers, assigns each element a random number between0and99, and then outputs all the scores.
Example Output:
Step 10: 2D Array
Code:
Explanation:
- Initial Output:
OUTPUT "三阶幻方": Outputs the string"三阶幻方", which is Chinese for "3x3 Magic Square".
- 2D Array Declaration:
DECLARE numbers : ARRAY[1:3, 1:3] OF STRING: Declares a two-dimensional array namednumberswith rows and columns both ranging from1to3. Each element is aSTRING.
- Array Initialization:
numbers <-- [ ["8", "1", "6"], ["3", "5", "7"], ["4", "9", "2"] ]: Initializes thenumbersarray with the values of a classic 3x3 magic square. In a magic square, the sums of numbers in each row, column, and both main diagonals are equal (here, each sum is15).
- FOR Loop to Output the Magic Square:
FOR n <-- 1 TO LENGTH(numbers): Loops through each row of thenumbersarray. AssumingLENGTH(numbers)returns the number of rows (3).OUTPUT numbers[n, 1] & " " & numbers[n, 2] & " " & numbers[n, 3]: Concatenates and outputs the three elements of each row separated by spaces.NEXT n: Moves to the next row.
What It Does:
- Prints out a 3x3 magic square. The output will look like:
Visual Representation:
Each row, column, and diagonal sums to
15.Step 11: Nested Loops with Conditions
Code:
Explanation:
Part 1: Creating a 23x23 Grid with Specific Conditions
- Variable Declaration and Initialization:
DECLARE MyString : STRING: Declares a string variableMyString.MyString ← "": InitializesMyStringas an empty string.
- Nested FOR Loops:
FOR a <-- 1 TO 23: Outer loop iteratesafrom1to23.FOR b <-- 1 TO 23: Inner loop iteratesbfrom1to23.- IF Conditions:
(a = b AND a<>11 AND a<>10 AND a<>1): Checks if the current position is on the main diagonal (a = b) but not at positions1,10, or11.(a + b = 24 AND a<>11 AND a<>10 AND a<>1): Checks if the current position is on the opposite diagonal (a + b = 24) but not at positions1,10, or11.a = 12 OR b = 12: Checks if the current row or column is12.THEN MyString ← MyString & "❤️": If any of the above conditions are true, appends a heart emoji toMyString.ELSE MyString ← MyString & "🟢": Otherwise, appends a green circle emoji.NEXT b: Ends the inner loop.MyString ← MyString & "\\n": Adds a newline character after completing each row.NEXT a: Ends the outer loop.
- Output Statement:
OUTPUT MyString: Displays the constructed string representing the grid.
What It Does:
- Constructs and outputs a 23x23 grid where:
- Cells on the main diagonal and the opposite diagonal (excluding specific positions) are marked with heart emojis.
- The entire 12th row and column are also marked with heart emojis.
- All other cells are marked with green circles.
- The result is a pattern of hearts and green circles forming specific shapes within the grid.
Part 2: Creating a 7x7 Grid with Diagonals
- Initial Output:
OUTPUT "shapes","\\n","\\n": Outputs the string"shapes"followed by two newline characters.
- 2D Array Declaration:
DECLARE numbers : ARRAY[1:7, 1:7] OF STRING: Declares a two-dimensional arraynumberswith rows and columns from1to7.
- Nested FOR Loops to Assign Emojis:
FOR a <-- 1 TO 7: Outer loop for rows.FOR b <-- 1 TO 7: Inner loop for columns.IF a = b OR a + b = 8 THEN: Checks if the cell is on the main diagonal (a = b) or the opposite diagonal (a + b = 8).numbers[a, b] <-- "❤️": Assigns a heart emoji.ELSE: Otherwise,numbers[a, b] <-- "🟢": Assigns a green circle emoji.NEXT b: Ends the inner loop.NEXT a: Ends the outer loop.
- FOR Loop to Output the 7x7 Grid:
FOR n <-- 1 TO LENGTH(numbers): Iterates through each row.OUTPUT numbers[n, 1] & " " & numbers[n, 2] & " " & numbers[n, 3] & " " & numbers[n, 4] & " " & numbers[n, 5] & " " & numbers[n, 6] & " " & numbers[n, 7]: Concatenates and outputs all seven elements of the current row separated by spaces.NEXT n: Moves to the next row.
What It Does:
- Creates and displays a 7x7 grid where:
- Cells on the main diagonal (
a = b) and the opposite diagonal (a + b = 8) are marked with heart emojis. - All other cells are marked with green circles.
Example Output:
This forms an 'X' shape with hearts on both diagonals.
Step 12: Files
Code:
Explanation:
- Variable Declaration:
DECLARE file : STRING: Declares a string variablefile.
- FOR Loop:
FOR n <-- 1 TO 6: Initiates a loop that runs six times withnfrom1to6.
- File Operations Inside the Loop:
file <-- n & "a" & ".txt":- Concatenates the current value of
nwith"a"and".txt"to form a filename. For example, whenn = 1,filebecomes"1a.txt". OPENFILE file FOR WRITE: Opens the file namedfilein write mode. If the file doesn't exist, it is created.WRITEFILE file, RANDOM() * 1000:- Generates a random floating-point number between
0and1withRAND(). - Multiplies it by
1,000to scale it up. - Writes this number to the file.
CLOSEFILE file: Closes the file after writing.
- Loop Progression:
NEXT n: Moves to the next iteration, incrementingnby1.
What It Does:
- Creates six text files named
1a.txt,2a.txt,3a.txt,4a.txt,5a.txt, and6a.txt.
- Each file is written with a random number between
0and1,000.
- Ensures that each file is properly closed after writing to prevent data corruption.
Example Outcome:
- File
1a.txt: Contains a random number like345.67.
- File
2a.txt: Contains a random number like123.45.
- ...
- File
6a.txt: Contains a random number like987.65.
Note:
- The actual random numbers will vary each time the code is executed.
- This code demonstrates basic file I/O operations: creating, writing to, and closing files within a loop.
STEP 1-12 Summary
You've covered a wide range of programming concepts across these steps, including:
- Variables: Declaration, initialization, and output.
- Loops:
FORloops with and without step values, andWHILEloops.
- Procedures and Functions: Creating reusable code blocks that perform specific tasks.
- Conditional Statements: Using
IF,ELSE, and logical operators to control program flow.
- Arrays: Handling both one-dimensional and two-dimensional arrays.
- Nested Loops and Conditions: Creating complex patterns and performing advanced computations.
- File Operations: Automating file creation and data writing.
Each step builds upon fundamental programming principles, demonstrating how to structure and manipulate data, control program flow, and interact with external resources like files. Understanding these concepts is crucial for developing more complex and efficient programs.
If you have any specific questions or need further clarification on any of these steps, feel free to ask!
STEP 13 Symbols and Keywords
Symbols and Keywords
STEP 14 Past Paper Questions 001
9618/23/M/J/23 Q4:
A function MakeString () will:
- take two parameters:
- a count as an integer
- a character
- generate a string of length equal to the count, made up of the character
- return the string generated, or return "ERROR" if the count is less than 1.
For example, the function call:
MakeString ( 3, ‘Z’) will return the string " Z Z Z"
Write pseudocode for function MakeString ( ) .
Solution:
STEP 15 Past Paper Questions 002
Step 16 Constructor
Step 17 Inheritance & Polymorphism
STEP 18 Recursive
STEP 19 More Past paper Questions
Q1:
????
- 作者:现代数学启蒙
- 链接:https://www.math1234567.com/article/Pseudocodesv
- 声明:本文采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。
相关文章










