9.2 Algorithms (3)
Resources |
Revision Questions |
Computer Science
Login to see all questions
Click on a question to view the answer
1.
Write pseudo-code to calculate the average of three numbers. The program should prompt the user to enter three numbers, store these values, calculate the average, and then display the average to the user. The average should be displayed to two decimal places.
Pseudo-code:
- Start
- Display a message prompting the user to enter the first number.
- Get the first number from the user and store it in variable
num1
. - Display a message prompting the user to enter the second number.
- Get the second number from the user and store it in variable
num2
. - Display a message prompting the user to enter the third number.
- Get the third number from the user and store it in variable
num3
. - Calculate the sum:
sum = num1 + num2 + num3
- Calculate the average:
average = sum / 3
- Display the message "The average is: " followed by the value of
average
, formatted to two decimal places. - End
2.
Consider an algorithm to determine if a given year is a leap year. A year is a leap year if it is divisible by 4, except for years divisible by 100 but not by 400. Write an algorithm, using logic statements, to determine if a given year is a leap year.
Algorithm:
- Input: Year (e.g., 2024)
- Check if Year is divisible by 4:
- Else if Year is divisible by 100:
- Check if Year is divisible by 400:
- If Yes: Leap year
- If No: Not a leap year
- Else if Year is divisible by 4 and not by 100:
- Output: Leap Year (True/False)
Pseudocode:
IF Year MOD 4 = 0 THEN
IF Year MOD 100 = 0 THEN
IF Year MOD 400 = 0 THEN
LeapYear = TRUE
ELSE
LeapYear = FALSE
ENDIF
ELSE
LeapYear = TRUE
ENDIF
ELSE
LeapYear = FALSE
ENDIF
3.
The following flowchart illustrates an algorithm for calculating the factorial of a non-negative integer. Write pseudo-code to represent this algorithm.
Pseudo-code:
- START
- INPUT a non-negative integer,
n
- SET
factorial
EQUALS 1 - IF
n
EQUALS 0 THEN - DISPLAY "Factorial is 1"
- ELSE
- FOR
i
FROM 1 TO n
DO - SET
factorial
EQUALS factorial
MULTIPLY i
- END FOR
- DISPLAY "Factorial is " EQUALS
factorial
- END IF
- END